79 Commits

Author SHA1 Message Date
Surya Paolo
0cfabed233 - tutorial Circuito Ris Italia
- Invia RIS (visibile per tutti)
2023-11-26 01:38:02 +01:00
Surya Paolo
c92dc8f216 fixed: se aggiungo una Provincia sul frontend non si aggiungeva 2023-11-24 17:52:17 +01:00
Surya Paolo
7b14c09fd5 Merge branch 'develop' of ssh://risosrv:5522/~/repository/freeplanet_serverside into develop 2023-11-23 16:06:38 +01:00
Surya Paolo
2258e8e7e1 aaa 2023-11-23 16:06:20 +01:00
Surya Paolo
e8c961f500 aaa 2023-11-23 15:58:13 +01:00
Surya Paolo
b395d1a30a aaa 2023-11-23 15:57:02 +01:00
Surya Paolo
341af6a3b2 test 2 2023-11-23 15:55:55 +01:00
Surya Paolo
3d876687b6 Merge branch 'develop' of ssh://risosrv:5522/~/repository/freeplanet_serverside into develop 2023-11-23 15:55:16 +01:00
Surya Paolo
560a532a85 aaa 2023-11-23 15:33:45 +01:00
Surya Paolo
aac8ce0a4c ok 2023-11-23 12:45:27 +01:00
Surya Paolo
d434374ed9 Click per mandare un messaggio al Destinatario dei RIS, se non è entrato ancora in RIS ITALIA. 2023-11-19 23:40:38 +01:00
Surya Paolo
045057082c Se aggiorno il fido e massimo di un circuito, devo aggiornare anche tutti gli account dei Circuiti Nazionali 2023-11-15 18:23:10 +01:00
Surya Paolo
18c5630a45 Quando accedi al Circuito RIS Nazionale, ti imposta il Fido e QtaMax DOPPIA rispetto al tuo Circuito Locale 2023-11-15 17:50:14 +01:00
Surya Paolo
7f1bd15bcf ver 1.0.19 2023-11-03 12:49:10 +01:00
Surya Paolo
c1a9a9a555 Versione 1.0.17
- Fix saldo pendente
- aggiunto bottone markup Telegram
- aggionta opzione per registrarsi direttamente su Telegram, senza doversi registrare ad un sito
2023-10-21 15:27:53 +02:00
Surya Paolo
536fbd1752 - se iOS non ricarica la pagina ma disinstalla il SW precedente e chiede di riavviare
- fixed: Creando un Conto di Gruppo, pare che venga impostato anche l'username... invece dev'essere solo il groupname
-
2023-10-03 23:16:52 +02:00
Surya Paolo
d6303f5880 Merge branch 'develop' of gitlab.com:surya89/freeplanet_serverside into develop 2023-10-03 00:44:24 +02:00
Surya Paolo
b6579832b6 correzione numseen, numfav, ...: ora li ho aggiunti alle tabelle... 2023-10-03 00:40:42 +02:00
Surya Paolo
04c8e929ee - Migliorata la Notifica degli Eventi su Telegram
- Gli annunci (beni/servizi/ospitalità) ora possono essere visti anche tramite un link, anche per chi non è dentro alla App.
- Aggiunto bottone "Aggiorna" per aggiornare il Saldo attuale.
- I "Conti Collettivi" ora vengono chiamati Gruppi (o Conto di Gruppo).
2023-10-01 01:24:47 +02:00
Surya Paolo
142dcadca9 Fixed: le reactions devono stare in una tabella a parte (reactions).
- cambiata la gestione dei seen, fav, book, attend
2023-09-27 18:38:57 +02:00
Surya Paolo
ad6b4c2bfa Modifiche prima di Luglio... 2023-08-27 23:55:31 +02:00
Surya Paolo
ba81a33c88 l'admin non riesce a cambiare il fido degli utenti... 2023-06-20 01:07:57 +02:00
Surya Paolo
baf56b59d0 default min e max fido e accumulo, per Circuito 2023-06-19 00:47:13 +02:00
Surya Paolo
3393af36aa la creazione dell'annuncio impiega troppo tempo (e le persone cliccavano su "Salva" più volte)... 2023-06-18 22:29:06 +02:00
Surya Paolo
95a812f002 - transazioni pendenti errore fixed (Elena) 2023-06-15 23:30:48 +02:00
Surya Paolo
aff50b03d4 Controllare che le notifiche per gli Eventi arrivino agli utenti (se io sono in una provincia mi deve arrivare almeno quella) 2023-06-07 18:46:04 +02:00
Surya Paolo
e28cd5f043 Poter modificare i limiti min e max su di 1 circuito specifico 2023-06-07 12:41:01 +02:00
Surya Paolo
9e499b8f43 Notifica Telegram e Push quando mandi la stretta di mano 2023-06-07 10:14:57 +02:00
Surya Paolo
84328e7bcd Filtra Ricerca... 2023-06-05 16:36:00 +02:00
Surya Paolo
a79e79a85e - L'utente entra direttamente sul circuito, con fido a zero.
++Abilitazione Fido utente (per admin).
2023-06-01 11:39:53 +02:00
Surya Paolo
0945f1af08 ++ aggiunta la prenotazione negli eventi. con la lista degli utenti. 2023-04-17 00:11:36 +02:00
Surya Paolo
eea6e63c58 aggiunto "Seen" 2023-04-13 14:27:00 +02:00
Surya Paolo
cda0bff21f set notif if service your province 2023-04-13 13:46:48 +02:00
Surya Paolo
cada7aa0b6 favorite: send if alert active 2023-04-12 16:29:22 +02:00
Surya Paolo
f13786fca1 fix: ordinamento membri (namecomplete (concat: name, surname, username) 2023-04-12 15:37:54 +02:00
Surya Paolo
5bb6611384 Revert "Aggiornamento a 0.6.1"
This reverts commit 198b5914bc.
2023-04-07 21:02:33 +02:00
Surya Paolo
0d5bff5849 Revert "cambio nome ai circuiti"
This reverts commit 6d1ad4132f.
2023-04-07 17:19:59 +02:00
Surya Paolo
198b5914bc Aggiornamento a 0.6.1 2023-04-07 17:14:44 +02:00
Surya Paolo
94ef2c4c85 nuova veste grafica: myskills, mygoods, mybachecas, myhosps,
- cambiato id (da numero a stringa)
2023-04-07 02:45:21 +02:00
Surya Paolo
8a77dabc22 new version Visualizzazione Service 2023-04-04 15:26:56 +02:00
Surya Paolo
6d1ad4132f cambio nome ai circuiti 2023-03-23 15:37:22 +01:00
Surya Paolo
e92edcbe78 - Cerca Amici persone: filtro per Regione o Provincia 2023-03-23 00:09:52 +01:00
Surya Paolo
561bab57a8 circuito 2023-03-22 18:10:23 +01:00
Surya Paolo
00e9aafd4c - Provincia obbligatoria, chiedo conferma se non vuole entrare nel circuito. 2023-03-22 15:54:45 +01:00
Surya Paolo
5993112a8e - Il circuito viene creato in automatico, quando scegli una provincia. 2023-03-21 18:11:56 +01:00
Surya Paolo
7482b65743 - Visu Saldo su Home
- SendRisTo
- Movimenti conto Comunitario
- Profilo
2023-03-17 19:07:31 +01:00
Surya Paolo
e705594294 - Invia Ris a e Ricevi Ris
- Tutorial Guidato Passi da Compiere
- Provincia in cui vivi
- Policy aggiornata
2023-03-11 01:01:11 +01:00
Surya Paolo
6a4c270c91 - fix: se salvavo un record 'settable' e non era completo con tutti i campi, andava a troncare gli altri precedentemente inseriti
- ordinamento Circuiti per stato e numiscritti e descr
2023-03-05 22:04:14 +01:00
Surya Paolo
39cc9b66d6 ver 0.5.73:
- corretto invia monete da Conto Collettivo a Utente
- Aggiunto Provincia (tutorial).. in corso...
2023-03-04 10:20:43 +01:00
Surya Paolo
4effda98ec ver 0.5.71:
- Info Conto
- Admin: poter modificare Fido e QtaMax, sia per i Conti Collettivi sia per gli Utenti.
2023-02-23 17:20:46 +01:00
Surya Paolo
84ceed500d ver 0.5.71:
- Info Conto
- Admin: poter modificare Fido e QtaMax.
2023-02-23 16:07:43 +01:00
Surya Paolo
0076adac76 - Info sul Conto Collettivo
- HomePage
2023-02-20 02:19:53 +01:00
Surya Paolo
874114942a Lista Richieste e Rifiutati dei Conti Collettivi 2023-02-16 20:13:38 +01:00
Surya Paolo
a81300e13d Unsubscribe 2023-02-15 21:40:19 +01:00
Surya Paolo
81d7d32b85 Unsubscribe 2023-02-15 21:39:47 +01:00
Surya Paolo
402a9c373e fix log 2023-02-06 23:26:30 +01:00
Surya Paolo
6e7eb31d38 - pagine admin: Accounts, Movements e Circuits.
- add change min e max range circuiti (per tutti i record).
2023-02-06 22:58:10 +01:00
Surya Paolo
022ad11747 fix Conti Collettivi + messaggi 2023-02-02 13:53:02 +01:00
Surya Paolo
7bf6f91a97 ver: 0.5.62
Conti Collettivi visibili solo se sei admin...
2023-02-02 02:31:04 +01:00
Surya Paolo
2d213b7020 Invio RIS da User a Conto Comunitario 2023-02-01 23:50:39 +01:00
Surya Paolo
aa9d27c8fd Conti Comunitari e Collettivi 2023-02-01 16:36:10 +01:00
Surya Paolo
9a0f0a0cc6 go on Conto Comunitario 2023-02-01 01:19:50 +01:00
Surya Paolo
5f3ce44a68 Pagina "Attività" non compare bene la scritta Beni e Servizi... ?! 2023-01-29 22:22:48 +01:00
Surya Paolo
73aa780733 Possibilità di scrivere l'username anche con la chiocciola @ 2023-01-25 10:47:41 +01:00
Surya Paolo
b9e4dbbaec Conto Comunitario all'interno di un Circuito 2023-01-21 19:02:19 +01:00
Surya Paolo
8e7b9fb5bd fix button registration disabled
Conto Comunitario... passo 2
2023-01-13 12:29:28 +01:00
Surya Paolo
f7d05eb856 Conto Comunitario... 2023-01-12 01:03:10 +01:00
Surya Paolo
e13fe84709 fix SdM
share link
2023-01-09 15:55:12 +01:00
Surya Paolo
dd51982795 fix strette di mano 2023-01-09 04:05:11 +01:00
Surya Paolo
a4b42a1fc3 ver: 0.5.55
Strette di Mano OK
2023-01-09 02:37:35 +01:00
Surya Paolo
331c2e6780 Stringi la mano (fase prima) 2023-01-08 19:20:02 +01:00
Surya Paolo
399153f477 ++Strette di Mano 2023-01-08 02:17:01 +01:00
Surya Paolo
d1135f1151 msg 2023-01-06 15:55:48 +01:00
Surya Paolo
d183a07bad strette di mano 2023-01-06 15:51:48 +01:00
Surya Paolo
f42a39d231 pagina Attivita + Video e PDF Presentazione 2023-01-05 01:37:20 +01:00
Surya Paolo
dd1c9d573f poter visualizzare i propri beni e servizi anche se non sei registrato alla app ! 2023-01-04 02:09:42 +01:00
Surya Paolo
18b827f5f4 ver 0.5.51 2023-01-03 16:51:32 +01:00
Surya Paolo
7a41e6a1d4 replace username 2022-12-23 17:06:54 +01:00
Surya Paolo
7e1407cbb1 Fare procedura per cambiare gli username in giro nelle varie tabelle 2022-12-23 00:36:35 +01:00
87 changed files with 21353 additions and 3329 deletions

BIN
.DS_Store vendored

Binary file not shown.

4
.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
./node_modules
Dockerfile
.dockerignore
docker-compose.yml

25
.env.test.risosrv Normal file
View File

@@ -0,0 +1,25 @@
DATABASE=test_FreePlanet
UDB=paofreeplanet
PDB=suerteFreePlanet@1A
SEND_EMAIL=1
PORT=3001
ENABLE_PUSHNOTIFICATION=1
DIRECTORY_SERVER=freeplanet_serverside
SERVERDIR_WEBSITE=test.freeplanet_server
PORT_APP1="0"
DOMAIN=mongodb://localhost:27018/
SIGNCODE=abc123
DEBUG=0
LOCALE=0
DELAY_SENDEMAIL=1000
VAPI_KEY_SUBJECT="mailto:surya@riso.app"
PUBLIC_VAPI_KEY="BGXRf1TgcqocqD6J7qnRgCG7AvM2lxAoW7peb7UEzB4SxBb6DxGRdJ0UvD9ewnrB9KrSrh0-aDCODXBm7sZ1DDs"
PRIVATE_VAPI_KEY="St9UMzcS76Q9yKG6RInAuYydYjFRliqwHTJY3A5wjO0"
GCM_API_KEY="AIzaSyD7w1jztfVV05mX1iyxoI-r1pZWxuxdUK8"
PATH_CERT_KEY=key.pem
PATH_SERVER_CRT=cert.pem
PATH_SSL_ROOT_PEM=root.pem
PATH_SSL_CHAIN_PEM=chain.pem
PROD=0
PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=iUUb38v23jjDFaosWj92axkBOXCQ

3
.gitignore vendored
View File

@@ -25,3 +25,6 @@ src/.DS_Store
.gitignore .gitignore
src/server/router/.DS_Store src/server/router/.DS_Store
src/server/.DS_Store src/server/.DS_Store
emails/.DS_Store
.DS_Store
.DS_Store

46
.vscode/launch.json vendored
View File

@@ -2,6 +2,48 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"type": "node",
"request": "launch",
"name": "Launch via Nodemon",
"program": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",
"restart": true,
"runtimeExecutable": "node",
"runtimeArgs": [
"--inspect=9229" // Use "--inspect=0.0.0.0:9229" for remote debugging
],
"args": ["${workspaceFolder}/src/server/server.js"], // Replace with your entry file
"cwd": "${workspaceFolder}",
"autoAttachChildProcesses": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"sourceMaps": true,
"env": {
"NODE_ENV":"development",
"TESTING_ON":"1"
},
},
{
"type": "node",
"request": "launch",
"name": "Launch Trace Warning",
"program": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",
"restart": true,
"runtimeExecutable": "node",
"runtimeArgs": [
"--trace-warnings" // Use "--inspect=0.0.0.0:9229" for remote debugging
],
"args": ["${workspaceFolder}/src/server/server.js"], // Replace with your entry file
"cwd": "${workspaceFolder}",
"autoAttachChildProcesses": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"sourceMaps": true,
"env": {
"NODE_ENV":"development",
"TESTING_ON":"1"
},
},
{
"name": "Server Debug", "name": "Server Debug",
"request": "launch", "request": "launch",
"runtimeArgs": [ "runtimeArgs": [
@@ -12,6 +54,10 @@
"skipFiles": [ "skipFiles": [
"<node_internals>/**" "<node_internals>/**"
], ],
"env": {
"NODE_ENV":"development",
"TESTING_ON":"1"
},
"type": "node" "type": "node"
}, },
{ {

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"search.useIgnoreFiles": false
}

7
Dockerfile Normal file
View File

@@ -0,0 +1,7 @@
FROM node:alpine
WORKDIR /Users/suryapaolo/myproject/freeplanet_serverside
COPY package*.json .
RUN npm ci
COPY . .
#CMD ["npm", "start"]
CMD ["npm", "run", "dev"]

18
deploy_solo1.sh Executable file
View File

@@ -0,0 +1,18 @@
#!/bin/bash
source ./.env.production
msg="*** SERVER DI PRODUZIONE **** SEI SICURO DI INVIARE IL SINGOLO FILE GENERAL.JS - SUL SERVER DI PRODUZIONE ?? $SERVERDIR_WEBSITE (Y/N) ? "
if [ "$1" = "" ]; then
read -p "$msg" risposta
else
echo $msg
risposta=$1
fi
if [[ $risposta == "Y" || $risposta == "y" ]]; then
echo "Sincronizzazione di 1 FILE in corso..."
rsync -avz -e 'ssh -p 8855' src/server/tools/general.js suryapaolo@servereng:/var/www/$SERVERDIR_WEBSITE/src/server/tools/general.js
echo "Sincronizzazione TERMINATA - SERVER PRODUZIONE!"
fi

16
deploynodejs_on_risosrv_test.sh Executable file
View File

@@ -0,0 +1,16 @@
#!/bin/bash
source ./.env.test.risosrv
echo "Sincronizzazione in corso..."
rsync -avz -e 'ssh -p 5522' css root@risosrv:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 5522' docs root@risosrv:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 5522' emails root@risosrv:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 5522' images root@risosrv:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 5522' plugins root@risosrv:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 5522' sass root@risosrv:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 5522' src root@risosrv:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 5522' .env.test.risosrv root@risosrv:/var/www/$SERVERDIR_WEBSITE/.env.test
rsync -avz -e 'ssh -p 5522' package.json root@risosrv:/var/www/$SERVERDIR_WEBSITE/package.json
echo "Sincronizzazione TERMINATA! - SERVER TEST!"

30
docker-compose.yml Normal file
View File

@@ -0,0 +1,30 @@
version: '3.9'
services:
# mongoDB service
mongo_db:
container_name: db_container
image: mongo:4.4
restart: always
ports:
- 2717:27017
volumes:
- mongo_db:/data/db
# Node API service
api:
build: .
ports:
- 4000:3000
volumes:
- .:/Users/suryapaolo/myproject/freeplanet_serverside
environment:
PORT: 3000
DOMAIN: mongodb://mongo_db:27017/
DATABASE: test_FreePlanet
UDB: paofreeplanet
depends_on:
- mongo_db
volumes:
mongo_db: {}

BIN
emails/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -1,5 +1,6 @@
p Ciao, p Ciao,
p Ti avvisiamo che #{username} (#{name} #{surname}) ha appena cancellato la prenotazione per l'evento #{event}: p Ti avvisiamo che #{username} (#{name} #{surname}) ha appena cancellato la prenotazione per l'evento #{event}:
span #{msgbooking}
span #{participants} span #{participants}
span #{participantsLunch} span #{participantsLunch}
span #{participantsDinner} span #{participantsDinner}

View File

@@ -1,5 +1,6 @@
p Ciao, p Ciao,
p Ti confermiamo che #{username} (#{name} #{surname}) ha appena inviato una richiesta di prenotazione per l'evento #{event} p Ti confermiamo che #{username} (#{name} #{surname}) ha appena inviato una richiesta di prenotazione per l'evento #{event}
p #{msgbooking}
p #{participants} p #{participants}
p #{participantsLunch} p #{participantsLunch}
p #{participantsDinner} p #{participantsDinner}

View File

@@ -1,5 +1,6 @@
p Ciao, p Ciao,
p Ti confermiamo che #{username} (#{name} #{surname}) ha appena Modificato la sua prenotazione per l'evento #{event} p Ti confermiamo che #{username} (#{name} #{surname}) ha appena Modificato la sua prenotazione per l'evento #{event}
p #{msgbooking}
p #{participants} p #{participants}
p #{participantsLunch} p #{participantsLunch}
p #{participantsDinner} p #{participantsDinner}

BIN
emails/admin/registration/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -1,5 +1,6 @@
p Ciao #{name}, p Ciao #{name},
p Ti confermiamo che la prenotazione per l'evento "#{event}" è stata cancellata. p Ti confermiamo che la prenotazione per l'evento "#{event}" è stata cancellata.
p #{msgbooking}
p #{participants} p #{participants}
p #{participantsLunch} p #{participantsLunch}
p #{participantsDinner} p #{participantsDinner}

View File

@@ -1,5 +1,6 @@
p Ciao #{name}, p Ciao #{name},
p Ti confermiamo che hai appena inviato una richiesta di prenotazione per l'evento #{event} p Ti confermiamo che hai appena inviato una richiesta di prenotazione per l'evento #{event}
p #{msgbooking}
p #{participants} p #{participants}
p #{participantsLunch} p #{participantsLunch}
p #{participantsDinner} p #{participantsDinner}

View File

@@ -1,5 +1,6 @@
p Ciao #{name}, p Ciao #{name},
p Ti confermiamo che hai modificato la prenotazione per l'evento #{event} p Ti confermiamo che hai modificato la prenotazione per l'evento #{event}
p #{msgbooking}
p #{participants} p #{participants}
p #{participantsLunch} p #{participantsLunch}
p #{participantsDinner} p #{participantsDinner}

View File

@@ -19,3 +19,77 @@ entrando sul bot riso premi su avvia (o start) e segui le istruzioni
3⃣ condividi il progetto ai tuoi amici ed aiuta così a far crescere questa rete e crescere insieme 💚 partecipa al cambiamento. riso sei anche tu. 3⃣ condividi il progetto ai tuoi amici ed aiuta così a far crescere questa rete e crescere insieme 💚 partecipa al cambiamento. riso sei anche tu.
se hai bisogno di aiuto chiedi in questa chat: 👉🏻 chat riso help se hai bisogno di aiuto chiedi in questa chat: 👉🏻 chat riso help
Gio 05/01 ORE 19:28: USER [paoloar77]: vai al sito
Gio 05/01 ORE 19:28: USER [paoloar77]: link da condividere
Gio 16/02 ORE 18:14: USER [paoloar77]: vai al sito
Mar 06/06 ORE 19:39: USER [paoloar77]: ciaooooooooooooooooo
Mar 06/06 ORE 19:54: USER [paoloar77]: dasjdalksjdasdklasjkldasjlkdjasl
Sab 17/06 ORE 20:03: USER [paoloar77]: pro v adsasdasdaksdas
Dom 18/06 ORE 19:22: USER [paoloar77]: /start inv
Dom 18/06 ORE 19:42: USER [paoloar77]: /start inv
Dom 18/06 ORE 19:58: USER [paoloar77]: /start inv
Dom 18/06 ORE 19:59: USER [paoloar77]: /start inv
Dom 18/06 ORE 19:59: USER [paoloar77]: /start inv
Ven 23/06 ORE 14:08: USER [paoloar77]: link da condividere
Sab 30/09 ORE 00:21: USER [SuryaArena]: vai al sito
Sab 30/09 ORE 00:32: USER [SuryaArena]: vai al sito
Gio 12/10 ORE 11:11: USER [paoloar77]: prova
Gio 12/10 ORE 11:48: USER [paoloar77]: prova
Gio 12/10 ORE 12:07: USER [SuryaArena]: prova
Gio 12/10 ORE 12:07: USER [SuryaArena]: prova
Gio 12/10 ORE 12:09: USER [SuryaArena]: prova
Gio 12/10 ORE 12:10: USER [SuryaArena]: prova
Gio 12/10 ORE 12:10: USER [SuryaArena]: prova
Gio 12/10 ORE 12:13: USER [SuryaArena]: prova
Gio 12/10 ORE 12:14: USER [SuryaArena]: prova
Gio 12/10 ORE 12:16: USER [SuryaArena]: prova
Gio 12/10 ORE 12:21: USER [SuryaArena]: prova
Gio 12/10 ORE 12:33: USER [paoloar77]: prova
Gio 12/10 ORE 12:33: USER [SuryaArena]: ciao
Gio 12/10 ORE 12:33: USER [SuryaArena]: prova
Gio 12/10 ORE 12:45: USER [SuryaArena]: bottone
Gio 12/10 ORE 14:49: USER [paoloar77]: bottone
Gio 12/10 ORE 14:49: USER [paoloar77]: bottone
Gio 12/10 ORE 14:49: USER [paoloar77]: bottone
Gio 12/10 ORE 14:52: USER [paoloar77]: bottone
Gio 12/10 ORE 14:57: USER [paoloar77]: bottone
Gio 12/10 ORE 15:06: USER [paoloar77]: bottone
Ven 13/10 ORE 11:05: USER [SuryaArena]: bottone
Ven 13/10 ORE 11:40: USER [SuryaArena]: bottone

27
logevents.txt Normal file
View File

@@ -0,0 +1,27 @@
Mar 06/06 ORE 19:06: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena2 è stato Abilitato correttamente (da paoloar77)!
Mar 06/06 ORE 19:07: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena2 è stato Abilitato correttamente (da paoloar77)!
Mar 06/06 ORE 19:38: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena2 è stato Abilitato correttamente (da paoloar77)!
Mar 06/06 ORE 19:39: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
ciaooooooooooooooooo
Mar 06/06 ORE 19:49: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena2 è stato Abilitato correttamente (da paoloar77)!
Mar 06/06 ORE 19:54: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
dasjdalksjdasdklasjkldasjlkdjasl
Sab 17/06 ORE 20:03: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
pro v adsasdasdaksdas
Dom 18/06 ORE 19:22: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
/start inv
Ven 23/06 ORE 14:13: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena è stato Abilitato correttamente (da paoloar77)!
Dom 25/06 ORE 16:11: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena è stato Abilitato correttamente (da paoloar77)!
Ven 29/09 ORE 23:18: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena è stato Abilitato correttamente (da paoloar77)!
Mar 03/10 ORE 22:49: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena è stato Abilitato correttamente (da paoloar77)!
Sab 04/11 ORE 15:17: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena è stato Abilitato correttamente (da paoloar77)!

99
logtrans.txt Normal file
View File

@@ -0,0 +1,99 @@
Lun 06/02 ORE 23:13: Inviate Monete da paoloar77 a surya1977 1 RISTEST [] [Saldo 1: -50] [Saldo 2: 5]
Lun 06/02 ORE 23:15: Inviate Monete da paoloar77 a surya1977 1 RISTEST [causale: ] [Saldo 1: -51 RISTEST] [Saldo 2: 6 RISTEST ]
Lun 06/02 ORE 23:17: Inviate Monete da paoloar77 a surya1977 1 RISTEST [causale: ] [Saldo paoloar77: -52 RISTEST] [Saldo surya1977: 7 RISTEST]
Dom 12/03 ORE 13:35: Inviate Monete da paoloar77 a 1 RIS [causale: ] [Saldo paoloar77: 3 RIS] [Saldo : 2 RIS]
Mer 15/03 ORE 22:15: Inviate Monete da pontiUmani (paoloar77) a paoloar77 1 RIS [causale: ] [Saldo pontiUmani (paoloar77): 1 RIS] [Saldo paoloar77: 4 RIS]
Mer 15/03 ORE 22:37: Inviate Monete da pontiUmani (paoloar77) a surya1977 1 RIS [causale: ] [Saldo pontiUmani (paoloar77): 0 RIS] [Saldo surya1977: 1 RIS]
Ven 28/04 ORE 01:33: Inviate Monete da surya1977 a risotest 1 RISTEST [causale: ] [Saldo surya1977: 0 RISTEST] [Saldo risotest: 9.5 RISTEST]
Gio 01/06 ORE 12:22: Inviate Monete da paoloar77 a surya1977 1 RIS [causale: ] [Saldo paoloar77: -2 RIS] [Saldo surya1977: 1 RIS]
Gio 01/06 ORE 12:25: Inviate Monete da paoloar77 a surya1977 2 RIS [causale: ] [Saldo paoloar77: -4 RIS] [Saldo surya1977: 3 RIS]
Gio 01/06 ORE 12:31: Inviate Monete da paoloar77 a surya1977 4 RIS [causale: ] [Saldo paoloar77: -8 RIS] [Saldo surya1977: 7 RIS]
Gio 01/06 ORE 17:26: Inviate Monete da paoloar77 a surya1977 1 RIS [causale: ] [Saldo paoloar77: -9 RIS] [Saldo surya1977: 8 RIS]
Gio 01/06 ORE 17:41: Inviate Monete da paoloar77 a surya1977 1 RIS [causale: ] [Saldo paoloar77: -10 RIS] [Saldo surya1977: 9 RIS]
Ven 02/06 ORE 19:29: Inviate Monete da paoloar77 a 2 RIS [causale: ] [Saldo paoloar77: 8 RIS] [Saldo : -261 RIS]
Ven 02/06 ORE 19:31: Inviate Monete da paoloar77 a pontiUmani 4 RIS [causale: ] [Saldo paoloar77: 0 RIS] [Saldo pontiUmani: -253 RIS]
Lun 26/06 ORE 23:23: [<b>Circuito RIS Ragusa</b>]: Inviate Monete da risragusa (paoloar77) a paogruppo2 300 RIS [causale: aaa]
Saldi:
risragusa (paoloar77): -300 RIS]
paogruppo2: 300 RIS]
Lun 26/06 ORE 23:27: [<b>Circuito RIS Ragusa</b>]: Inviate Monete da paoloar77 a paogruppo2 20 RIS [causale: ]
Saldi:
paoloar77: -20 RIS]
paogruppo2: 320 RIS]
Sab 30/09 ORE 13:32: [<b>Circuito RIS Bologna</b>]: Inviate Monete da SuryaArena a paoloar77 1 RIS [causale: aaa]
Saldi:
SuryaArena: -1 RIS]
paoloar77: 11 RIS]
Lun 09/10 ORE 09:04: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -2 RIS]
SuryaArena2: 1 RIS]
Lun 09/10 ORE 09:21: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -3 RIS]
SuryaArena2: 2 RIS]
Lun 09/10 ORE 10:25: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -4 RIS]
SuryaArena2: 3 RIS]
Lun 09/10 ORE 10:26: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -5 RIS]
SuryaArena2: 4 RIS]
Lun 09/10 ORE 23:26: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -2 RIS]
SuryaArena2: 1 RIS]
Lun 09/10 ORE 23:36: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -3 RIS]
SuryaArena2: 2 RIS]
Lun 09/10 ORE 23:36: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -4 RIS]
SuryaArena2: 3 RIS]
Mar 10/10 ORE 00:04: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -5 RIS]
SuryaArena2: 4 RIS]
Mar 10/10 ORE 00:21: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -6 RIS]
SuryaArena2: 5 RIS]
Mar 10/10 ORE 00:34: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -7 RIS]
SuryaArena2: 6 RIS]
Mar 10/10 ORE 22:47: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a PaoTEST1 1 RIS [causale: ]
Saldi:
paoloar77: -8 RIS]
PaoTEST1: 1 RIS]
Mar 10/10 ORE 22:49: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a PaoTEST1 1 RIS [causale: ]
Saldi:
paoloar77: -9 RIS]
PaoTEST1: 2 RIS]
Mar 10/10 ORE 23:08: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a PaoTEST1 2 RIS [causale: ]
Saldi:
paoloar77: -11 RIS]
PaoTEST1: 4 RIS]
Mar 10/10 ORE 23:13: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a PaoTEST1 3 RIS [causale: ]
Saldi:
paoloar77: -14 RIS]
PaoTEST1: 7 RIS]
Mar 10/10 ORE 23:22: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a PaoTEST1 1 RIS [causale: ]
Saldi:
paoloar77: -15 RIS]
PaoTEST1: 8 RIS]
Mer 11/10 ORE 22:33: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a PaoTEST1 1 RIS [causale: ]
Saldi:
paoloar77: -16 RIS]
PaoTEST1: 9 RIS]
Gio 12/10 ORE 08:05: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a PaoTEST1 1 RIS [causale: ]
Saldi:
paoloar77: -17 RIS]
PaoTEST1: 10 RIS]
Gio 12/10 ORE 08:06: [<b>Circuito RIS Rimini</b>]: Inviate Monete da paoloar77 a SuryaArena2 1 RIS [causale: ]
Saldi:
paoloar77: -18 RIS]
SuryaArena2: 7 RIS]

View File

@@ -10,91 +10,345 @@ let aggregation = [
{ {
$match: { $match: {
idapp: "13", idapp: "13",
},
},
{
$sort: {
date_updated: -1,
},
},
{
$addFields: {
myId1: {
$toObjectId: "$userId",
},
},
},
{
$lookup: {
from: "users",
localField: "myId1",
foreignField: "_id",
as: "user",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$user",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
"profile.resid_card": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$lookup: {
from: "goods",
localField: "idGood",
foreignField: "_id",
as: "recGood",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$recGood",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
"profile.resid_card": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$lookup: {
from: "sectorgoods",
localField: "idSectorGood",
foreignField: "_id",
as: "sectorGood",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$sectorGood",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$lookup: {
from: "cities",
localField: "idCity",
foreignField: "_id",
as: "mycities",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$mycities",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$match: {
$or: [ $or: [
{ {
deleted: { $and: [
$exists: false, {
}, "profile.mygroups": {
$elemMatch: {
groupname: {
$in: [
"000017",
"risoprova",
"VillaggiamoItalia",
"Terraw",
"RisoBenevento",
"111",
"gruppodefaultriso",
"pontiUmani",
],
},
},
},
},
{
pub_to_share: 1,
},
],
}, },
{ {
deleted: { $or: [
$exists: true, {
$eq: false, pub_to_share: {
}, $exists: false,
},
},
{
pub_to_share: {
$exists: true,
$eq: 0,
},
},
],
},
],
},
},
{
$match: {
$and: [
{
"mycities.reg": "EMR",
}, },
], ],
}, },
}, },
{ {
$group: { $group: {
_id: "$aportador_solidario", _id: null,
count: { count: {
$sum: 1, $sum: 1,
}, },
}, results: {
}, $push: "$$ROOT",
{
$match: { "count": { $gte: 2 } }
},
{
$sort: {
count: -1,
},
},
{
$lookup: {
from: "users",
let: {
username: "$_id",
idapp: "13",
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$$username",
"$username",
],
},
{
$eq: [
"$$idapp",
"$idapp",
],
},
],
},
},
},
],
as: "user",
},
},
{ $unwind: "$user" },
{
$replaceRoot: {
newRoot: {
$mergeObjects: [ "$user", "$$ROOT" ],
}, },
}, },
}, },
{ {
$project: { $project: {
_id: 0,
count: 1, count: 1,
aportador_solidario: 1, rows: {
username: 1, $slice: [
name: 1, "$results",
surname: 1, 0,
lasttimeonline: 1, 10,
idapp: 1, ],
"profile.img": 1, },
}, },
}, },
]; ];
db.users.aggregate(aggregation); db.myskills.aggregate(aggregation);

432
mongodb/Favorite.mongodb Normal file
View File

@@ -0,0 +1,432 @@
use('test_FreePlanet');
let aggregation = [
{
$match: {
idapp: "13",
},
},
{
$sort: {
date_updated: -1,
},
},
{
$lookup: {
from: "users",
let: {
tab: 1,
id: "$_id",
},
pipeline: [
{
$unwind: "$profile.favorite",
},
{
$match: {
$expr: {
$and: [
{
$eq: [
"$profile.favorite.id",
"$$id",
],
},
{
$eq: [
"$profile.favorite.tab",
"$$tab",
],
},
{
$eq: [
"$idapp",
"13",
],
},
],
},
},
},
{ $project: { username: 1, _id: 0 } },
],
as: "myfav",
},
},
{
$lookup: {
from: "users",
let: {
tab: 1,
id: "$_id",
},
pipeline: [
{
$unwind: "$profile.bookmark",
},
{
$match: {
$expr: {
$and: [
{
$eq: [
"$profile.bookmark.id",
"$$id",
],
},
{
$eq: [
"$profile.bookmark.tab",
"$$tab",
],
},
],
},
},
},
],
as: "mybook",
},
},
{
$addFields: {
myId1: {
$toObjectId: "$userId",
},
},
},
{
$lookup: {
from: "users",
localField: "myId1",
foreignField: "_id",
as: "user",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$user",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
myskill: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
myfav: 1,
mybook: 1,
},
},
{
$lookup: {
from: "skills",
localField: "idSkill",
foreignField: "_id",
as: "recSkill",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$recSkill",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
myskill: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
myfav: 1,
mybook: 1,
},
},
{
$lookup: {
from: "sectors",
localField: "idSector",
foreignField: "_id",
as: "sector",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$sector",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
myskill: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
myfav: 1,
mybook: 1,
myseen: 1,
},
},
{
$lookup: {
from: "cities",
localField: "idCity",
foreignField: "_id",
as: "mycities",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$mycities",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
myskill: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
myfav: 1,
mybook: 1,
},
},
{
$match: {
$or: [
{
$and: [
{
"profile.mygroups": {
$elemMatch: {
groupname: {
$in: [
"000017",
"risoprova",
"VillaggiamoItalia",
"Terraw",
"RisoBenevento",
"111",
"gruppodefaultriso",
"pontiUmani",
],
},
},
},
},
{
pub_to_share: 1,
},
],
},
{
$or: [
{
pub_to_share: {
$exists: false,
},
},
{
pub_to_share: {
$exists: true,
$eq: 0,
},
},
],
},
],
},
},
{
$match: {
$and: [
{
"mycities.reg": "EMR",
},
],
},
},
{
$group: {
_id: null,
count: {
$sum: 1,
},
results: {
$push: "$$ROOT",
},
},
},
{
$project: {
count: 1,
rows: {
$slice: [
"$results",
0,
10,
],
},
},
},
];
db.myskills.aggregate(aggregation);

203
mongodb/Members.mongodb Normal file
View File

@@ -0,0 +1,203 @@
use('test_FreePlanet');
let aggregation = [
{
$match: {
idapp: "13",
"profile.mycircuits": {
$elemMatch: {
circuitname: {
$eq: "Circuito RIS Bologna",
},
},
},
},
},
{
$lookup: {
from: "circuits",
as: "circuit",
let: {
circuitname: "Circuito RIS Bologna",
idapp: "$idapp",
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$name",
"$$circuitname",
],
},
{
$eq: [
"$idapp",
"$$idapp",
],
},
],
},
},
},
],
},
},
{
$unwind: "$circuit",
},
{
$project: {
username: 1,
name: 1,
surname: 1,
date_reg: 1,
profile: 1,
idapp: 1,
"circuit.name": 1,
"circuit._id": 1,
},
},
{
$lookup: {
from: "accounts",
as: "account",
let: {
username: "$username",
idapp: "$idapp",
circuitId: "$circuit._id",
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$$username",
"$username",
],
},
{
$eq: [
"$$idapp",
"$idapp",
],
},
{
$eq: [
"$$circuitId",
"$circuitId",
],
},
],
},
},
},
],
},
},
{
$unwind: "$account",
},
{
$match: {
idapp: "13",
},
},
{
$addFields: {
myId1: {
$toObjectId: "$userId",
},
namecomplete: {
$concat: [
{
$toLower: "$name",
},
{
$toLower: "$surname",
},
{ $toLower: "$username" },
],
},
},
},
{
$lookup: {
from: "users",
localField: "myId1",
foreignField: "_id",
as: "user",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$user",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
username: 1,
name: 1,
surname: 1,
"profile.img": 1,
"profile.mycircuits": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
"account._id": 1,
"account.saldo": 1,
"account.fidoConcesso": 1,
"account.qta_maxConcessa": 1,
"account.totTransato": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
namecomplete: 1,
date_reg: 1,
},
},
{
$sort: {
date_reg: 1,
},
},
{
$group: {
_id: null,
count: {
$sum: 1,
},
results: {
$push: "$$ROOT",
},
},
},
{
$project: {
count: 1,
rows: {
$slice: [
"$results",
1,
15,
],
},
},
},
];
db.users.aggregate(aggregation);

352
mongodb/MySkills.mongodb Normal file
View File

@@ -0,0 +1,352 @@
// MongoDB Playground
// To disable this template go to Settings | MongoDB | Use Default Template For Playground.
// Make sure you are connected to enable completions and to be able to run a playground.
// Use Ctrl+Space inside a snippet or a string literal to trigger completions.
// Select the database to use.
use('test_FreePlanet');
let aggregation = [
{
$match: {
idapp: "13",
},
},
{
$sort: {
date_updated: -1,
},
},
{
$addFields: {
myId1: {
$toObjectId: "$userId",
},
},
},
{
$lookup: {
from: "users",
localField: "myId1",
foreignField: "_id",
as: "user",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$user",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$lookup: {
from: "goods",
localField: "idGood",
foreignField: "_id",
as: "recGood",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$recGood",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$lookup: {
from: "sectorgoods",
localField: "idSectorGood",
foreignField: "_id",
as: "sectorGood",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$sectorGood",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$lookup: {
from: "cities",
localField: "idCity",
foreignField: "_id",
as: "mycities",
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: [
"$mycities",
0,
],
},
"$$ROOT",
],
},
},
},
{
$project: {
recGood: 1,
sectorGood: 1,
idSectorGood: 1,
idGood: 1,
mygood: 1,
idStatusSkill: 1,
idContribType: 1,
"profile.username_telegram": 1,
"profile.favorite": 1,
"profile.bookmark": 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
comune: 1,
mycities: 1,
"profile.img": 1,
"profile.mygroups": 1,
"profile.qualifica": 1,
"profile.resid_province": 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
},
{
$match: {
$or: [
{
$and: [
{
"profile.mygroups": {
$elemMatch: {
groupname: {
$in: [
"000017",
"risoprova",
"VillaggiamoItalia",
"Terraw",
"RisoBenevento",
"111",
"gruppodefaultriso",
"pontiUmani",
],
},
},
},
},
{
pub_to_share: 1,
},
],
},
{
$or: [
{
pub_to_share: {
$exists: false,
},
},
{
pub_to_share: {
$exists: true,
$eq: 0,
},
},
],
},
],
},
},
{
$match: {
$and: [
{
"mycities.reg": "EMR",
},
],
},
},
{
$group: {
_id: null,
count: {
$sum: 1,
},
results: {
$push: "$$ROOT",
},
},
},
{
$project: {
count: 1,
rows: {
$slice: [
"$results",
0,
10,
],
},
},
},
];
db.myskills.aggregate(aggregation);

View File

@@ -278,3 +278,11 @@ if (test) {
// Use toArray() to exhaust the cursor to return the whole result set. // Use toArray() to exhaust the cursor to return the whole result set.
// You can use hasNext()/next() to iterate through the cursor page by page. // You can use hasNext()/next() to iterate through the cursor page by page.
db.users.aggregate(aggregation); db.users.aggregate(aggregation);
db.getCollection('myskills').deleteMany({ '_id': { $lte: 10000 }})
db.getCollection('mygoods').deleteMany({ '_id': { $lte: 10000 }})
db.getCollection('mybachecas').deleteMany({ '_id': { $lte: 10000 }})
db.getCollection('myhosps').deleteMany({ '_id': { $lte: 10000 }})
db.getCollection('mygroups').deleteMany({ '_id': { $lte: 10000 }})

View File

@@ -0,0 +1,23 @@
use('test_FreePlanet');
let aggregation = [
{
$match: {
idapp: "13",
"profile.favorite": {
$elemMatch:
{ id: '10256', tab: 4 }
}
},
},
{
$group:
{
_id: null,
count: { $sum: 1 },
}
},
{ $project: { _id: 0 } }
];
db.users.aggregate(aggregation);

View File

@@ -4,15 +4,17 @@
"description": "freeplanet serverside", "description": "freeplanet serverside",
"main": "server/server.js", "main": "server/server.js",
"scripts": { "scripts": {
"start": "NODE_ENV=development nodemon src/server/server.js", "start": "node src/server/server.js",
"dev": "NODE_ENV=development nodemon src/server/server.js",
"build": "gulp build", "build": "gulp build",
"watch": "gulp watch", "watch": "gulp watch",
"test": "export NODE_ENV=development || SET NODE_ENV=development && mocha src/server/**/*.test.js", "test": "export NODE_ENV=development || SET NODE_ENV=development && mocha src/server/**/*.test.js",
"start:prod": "NODE_ENV=production node src/server/server.js", "start:prod": "NODE_ENV=production node src/server/server.js",
"starttest": "NODE_ENV=test node src/server/server.js",
"test-watch": "nodemon --exec 'npm test'" "test-watch": "nodemon --exec 'npm test'"
}, },
"engines": { "engines": {
"node": "^16.14.0" "node": "^16.19.0"
}, },
"author": "Paolo Arena", "author": "Paolo Arena",
"license": "MIT", "license": "MIT",
@@ -34,8 +36,8 @@
"i18n": "^0.15.0", "i18n": "^0.15.0",
"image-downloader": "^4.3.0", "image-downloader": "^4.3.0",
"internet-available": "^1.0.0", "internet-available": "^1.0.0",
"jade": "^1.11.0", "jade": "^1.9.2",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^9.0.1",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"mongodb": "^4.4.1", "mongodb": "^4.4.1",
"mongoose": "^5.13.15", "mongoose": "^5.13.15",
@@ -47,11 +49,12 @@
"node-telegram-bot-api": "^0.59.0", "node-telegram-bot-api": "^0.59.0",
"nodemailer": "^6.7.8", "nodemailer": "^6.7.8",
"npm-check-updates": "^16.1.0", "npm-check-updates": "^16.1.0",
"pem": "^1.14.6",
"preview-email": "^3.0.7", "preview-email": "^3.0.7",
"pug": "^3.0.2", "pug": "^3.0.2",
"rate-limiter-flexible": "^2.3.9", "rate-limiter-flexible": "^2.3.9",
"save": "^2.5.0", "save": "^2.5.0",
"sharp": "0.30.0", "sharp": "^0.30.7",
"superagent": "^8.0.0", "superagent": "^8.0.0",
"url-parse": "^1.5.10", "url-parse": "^1.5.10",
"validator": "^13.7.0", "validator": "^13.7.0",
@@ -61,15 +64,15 @@
"devDependencies": { "devDependencies": {
"browser-sync": "^2.27.10", "browser-sync": "^2.27.10",
"expect": "^29.0.2", "expect": "^29.0.2",
"gulp": "^4.0.2", "gulp": "^3.9.1",
"gulp-inline-css": "^4.0.0", "gulp-inline-css": "^2.0.0",
"gulp-pug": "^5.0.0", "gulp-pug": "^5.0.0",
"gulp-rename": "^2.0.0", "gulp-rename": "^2.0.0",
"gulp-replace": "^1.1.3", "gulp-replace": "^1.1.3",
"gulp-sass": "^5.1.0", "gulp-sass": "^5.1.0",
"jest": "^29.0.2", "jest": "^29.0.2",
"mocha": "^10.0.0", "mocha": "^10.0.0",
"nodemon": "^2.0.19", "nodemon": "^3.0.1",
"supertest": "^6.2.4" "supertest": "^6.2.4"
} }
} }

0
prova111 Normal file
View File

View File

@@ -8,7 +8,10 @@
} }
], ],
"settings": { "settings": {
"search.useIgnoreFiles": true, "search.useIgnoreFiles": false,
"search.useParentIgnoreFiles": true "search.useParentIgnoreFiles": false,
"files.exclude": {
"": true
}
} }
} }

View File

@@ -2,6 +2,8 @@ const tools = require('../tools/general');
// still in app.js // still in app.js
const node_env = process.env.NODE_ENV || 'production'; const node_env = process.env.NODE_ENV || 'production';
console.log('node_env=', node_env);
var file = `.env.${node_env}`; var file = `.env.${node_env}`;
@@ -18,7 +20,10 @@ require('dotenv').config({ path: file });
process.env.DATABASE = process.env.DATABASE || 'FreePlanet'; process.env.DATABASE = process.env.DATABASE || 'FreePlanet';
console.log('process.env.DOMAIN:', process.env.DOMAIN);
process.env.MONGODB_URI = process.env.DOMAIN + process.env.DATABASE; process.env.MONGODB_URI = process.env.DOMAIN + process.env.DATABASE;
console.log('process.env.MONGODB_URI:', process.env.MONGODB_URI);
/* /*

View File

@@ -44,6 +44,9 @@ const db = mongoose.connection;
// mongoose.connect(process.env.MONGODB_URI + '?authSource=admin', { options }) // mongoose.connect(process.env.MONGODB_URI + '?authSource=admin', { options })
// console.log(' -> PASSAGGIO PARAMETRI MONGOOSE') // console.log(' -> PASSAGGIO PARAMETRI MONGOOSE')
console.log('Node Version ' + process.version);
console.log('Mongoose Version ' + mongoose.version);
console.log('Connessione a ' + process.env.MONGODB_URI + ' in corso...');
mongoose.connect(process.env.MONGODB_URI, options); mongoose.connect(process.env.MONGODB_URI, options);
db.on('error', console.error.bind(console, 'connection error:')); db.on('error', console.error.bind(console, 'connection error:'));

View File

@@ -1,5 +1,5 @@
{ {
"L'Email è già stata Verificata": "L'Email è già stata Verificata" "L'Email è già stata Verificata": "L'Email è già stata Verificata",
"Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.", "Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.",
"Nuova Registrazione": "Nuevo Registro", "Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro", "Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",

View File

@@ -3,15 +3,25 @@
"Hello %s": "Ciao %s", "Hello %s": "Ciao %s",
"Good: %s": "Bene: %s", "Good: %s": "Bene: %s",
"Service: %s": "Servizio: %s", "Service: %s": "Servizio: %s",
"<strong>%s</strong> new Good: %s": "<strong>%s</strong> nuovo Bene: %s", "NEW_GOOD": "❇️ <strong>%s</strong> ha aggiunto un nuovo Bene: \n<strong>%s</strong>",
"<strong>%s</strong> new Service: %s": "<strong>%s</strong> nuovo Servizio: %s", "NEW_SERVICE": "❇️ <strong>%s</strong> ha aggiunto un nuovo Servizio: \n<strong>%s</strong>",
"NEW_HOSP": "❇️ <strong>%s</strong> ha aggiunto una nuova Ospitalità: \n<strong>%s</strong>",
"NEW_EVENT": "❇️ <strong>%s</strong> ha aggiunto un nuovo Evento: \n%s\n<strong>%s</strong>\n%s",
"NEW_EVENT_TELEGRAM": "%s\n\n❇ <strong>%s</strong>\n\n%s\n\n%s",
"ADDED_FROM": "\n\n<i>(Evento aggiunto da <strong>%s</strong>)</i>",
"CONTRIB": "\n💠 Contributo richiesto: %s",
"ORGANIZED_BY": "\n<i>Organizzato da <strong>%s</strong></i>",
"SHOW_POST": "👉🏻 vedi post su RISO",
"OPEN PAGE": "<em>APRI la APP RISO oppure visita riso.app</em>", "OPEN PAGE": "<em>APRI la APP RISO oppure visita riso.app</em>",
"<strong>%s</strong> asked you for Friendship": "<strong>%s</strong> ti ha chiesto l'Amicizia", "<strong>%s</strong> asked you for Friendship": "<strong>%s</strong> ti ha chiesto l'Amicizia",
"<strong>%s</strong> accepted your Friendship": "<strong>%s</strong> ha accettato l'Amicizia", "<strong>%s</strong> accepted your Friendship": "<strong>%s</strong> ha accettato l'Amicizia",
"<strong>%s</strong> refused your Friendship": "<strong>%s</strong> ha rifiutato l'Amicizia", "<strong>%s</strong> refused your Friendship": "<strong>%s</strong> ha rifiutato l'Amicizia",
"✅ %s accepted your Friendship request !": "✅ %s ha accettato la tua richiesta di Amicizia !", "✅ %s accepted your Friendship request !": "✅ %s ha accettato la tua richiesta di Amicizia !",
"✅ You have accepted %s' Friendship request!": "✅ Hai accettato la richiesta di Amicizia di %s !", "✅ You have accepted %s' Friendship request!": "✅ Hai accettato la richiesta di Amicizia di %s !",
"GROUPS_ACCEPTED": "✅ Sei stato accettato da %s a far parte del Gruppo %s (da parte di %s)", "HANDSHAKE_SET": "<strong>%s</strong> ha comunicato che ti conosce personalmente e ha fiducia in te.",
"HANDSHAKE_CONFIRMED": "🤝 Hai contraccambiato la fiducia in <strong>%s</strong>!",
"HANDSHAKE_ACCEPTED": "🤝 <strong>%s</strong> ha contraccambiato la stretta di mano (fiducia) !",
"GROUPS_ACCEPTED": "✅ Sei stato accettato a far parte del Gruppo %s (da parte di %s)",
"GROUPS_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del Gruppo %s. Se pensi sia un'errore, contatta l'amministratore del Gruppo.", "GROUPS_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del Gruppo %s. Se pensi sia un'errore, contatta l'amministratore del Gruppo.",
"GROUPS_REMOVED": "❌ l'utente %s è stato rimosso del Gruppo %s (da parte di %s)", "GROUPS_REMOVED": "❌ l'utente %s è stato rimosso del Gruppo %s (da parte di %s)",
"GROUPS_EXIT_USER": "❌ l'utente %s è uscito dal Gruppo %s", "GROUPS_EXIT_USER": "❌ l'utente %s è uscito dal Gruppo %s",
@@ -33,36 +43,69 @@
"FRIEND_UNBLOCKED_TO_ME": "Sei stato riattivato da %s", "FRIEND_UNBLOCKED_TO_ME": "Sei stato riattivato da %s",
"FRIEND_UNBLOCKED": "E' stato riattivato %s da %s.", "FRIEND_UNBLOCKED": "E' stato riattivato %s da %s.",
"FRIEND_UNBLOCKED_YOU": "Hai riattivato %s.", "FRIEND_UNBLOCKED_YOU": "Hai riattivato %s.",
"CIRCUIT_ACCEPT_NEWENTRY": "❇️👥 🧍‍♂️ Accetta Ingresso nel Circuito %s:", "CIRCUIT_ACCEPT_NEWENTRY": "❇️👥 🧍‍♂️ Abilita fido a %s nel '%s':",
"CIRCUIT_REQUEST_TO_ENTER": "%s ha chiesto di entrare nel circuito %s", "CIRCUIT_ACCEPT_NEWENTRY_BYGROUP": "❇️👥 🧍‍♂️ Abilita fido nel Circuito al gruppo %s:",
"CIRCUIT_OPEN_RISITALIA": "Apri il Circuito RIS Italia e chiedi di entrare",
"CIRCUIT_REQUEST_TO_ENTER": "%s è entrato nel %s (con %s iscritti) ed è in attesa di essere abilitato al Fido (è stato invitato da %s)",
"CIRCUIT_ADMINS": "Gli amministratori del circuito sono %s:\n%s",
"CIRCUIT_WHERE_IS_PRESENT": "\nAttualmente è presente in: %s",
"CIRCUIT_REQUEST_TO_ENTER_WITH_GROUP": "il gruppo %s ha chiesto di entrare nel %s (con %s iscritti)",
"CIRCUIT_CREATED": "✅ %s ha creato un nuovo Circuito chiamato %s", "CIRCUIT_CREATED": "✅ %s ha creato un nuovo Circuito chiamato %s",
"CIRCUIT_REQUEST": "Richiesta di entrare nel Circuito %s da parte di %s", "CIRCUIT_REQUEST": "Richiesta di entrare nel %s da parte di %s",
"CIRCUIT_ADDED_ADMIN": "E' stato aggiunto %s come Amministratore del circuito %s da parte di %s", "CIRCUIT_ADDED_ADMIN": "E' stato aggiunto %s come Amministratore del %s da parte di %s",
"CIRCUIT_ADDED_ADMIN_YOU": "Sei stato aggiunto come Amministratore del circuito %s da parte di %s", "CIRCUIT_ADDED_ADMIN_YOU": "%s sei stato aggiunto come Amministratore del %s da parte di %s",
"CIRCUIT_REMOVED_ADMIN": "E' stato rimosso l'incarico di Amministratore a %s del circuito %s da parte di %s", "CIRCUIT_REMOVED_ADMIN": "E' stato rimosso l'incarico di Amministratore a %s del %s da parte di %s",
"CIRCUIT_REMOVED_ADMIN_YOU": "Ti è stato rimosso l'incarico di Amministratore del circuito %s da parte di %s", "CIRCUIT_REMOVED_ADMIN_YOU": "%s ti è stato rimosso l'incarico di Amministratore del %s da parte di %s",
"RICHIESTA_BLOCCO_CIRCUIT": "Richiesta di bloccare il Circuito %s da parte di %s", "RICHIESTA_BLOCCO_CIRCUIT": "Richiesta di bloccare il %s da parte di %s",
"CIRCUIT_ELIMINATO": "Il circuito %s è stato eliminato da parte di %s", "CIRCUIT_ELIMINATO": "Il %s è stato eliminato da parte di %s",
"ACCETTATO_NOTIFICA_ADMINS_CIRCUIT": "✅ l'utente %s è stato accettato a far parte del Circuito %s (da parte di %s)", "FIDO_IMPOSTATO_ADMINS_CIRCUIT": "✅ l'utente %s è stato abilitato al Fido (%s RIS) sul '%s' (da parte di %s)",
"CIRCUIT_ACCEPTED": "✅ Sei stato accettato da %s a far parte del Circuito %s.\nApri la APP e clicca in alto a destra sull'icona delle monete, oppure clicca qui: %s", "FIDO_IMPOSTATO_ADMINS_CIRCUIT_MYGROUP": "✅ il Conto di Gruppo %s è stato abilitato al Fido fino a -%s sul '%s' (da parte di %s)",
"CIRCUIT_ACCEPTED_YOU": "✅ Hai accettato %s a far parte del Circuito %s", "ACCETTATO_NOTIFICA_ADMINS_CIRCUIT": "✅ l'utente %s è stato accettato a far parte del '%s' (da parte di %s)",
"CIRCUIT_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del Circuito %s. Se pensi sia un'errore, contatta l'amministratore del Circuito.", "ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP": "✅ il Conto di Gruppo %s è stato accettato a far parte del '%s' (da parte di %s)",
"CIRCUIT_REMOVED": "❌ l'utente %s è stato rimosso del Circuito %s (da parte di %s)", "CIRCUIT_ACCEPTED": "✅ Sei stato accettato da %s a far parte del %s.\nApri la APP e clicca in alto a destra sull'icona delle monete, oppure clicca qui: %s",
"CIRCUIT_REFUSED_TO_ME": "All'utente %s gli è stato rifiutato l'accesso a far parte del Circuito %s (da parte di %s).", "FIDO_IMPOSTATO": "✅ Ti è stata attivata la possibilità di utilizzare il fido (Fiducia Concessa) fino a %s RIS da %s sul '%s'.",
"CIRCUIT_EXIT_USER": "❌ l'utente %s è uscito dal Circuito %s", "CIRCUIT_ACCEPTED_YOU": "✅ Hai accettato %s a far parte del '%s'",
"CIRCUIT_EXIT_USER_TO_ME": "❌ Sei uscito dal Circuito %s", "CIRCUIT_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del '%s'. Se pensi sia un'errore, contatta l'amministratore del Circuito.",
"CIRCUIT_REMOVED_TO_ME": "❌ Sei stato rimosso dal Circuito %s (da parte di %s)", "CIRCUIT_REMOVED": "❌ l'utente %s è stato rimosso del %s (da parte di %s)",
"CIRCUIT_SENDCOINSREQ": "%s ti sta inviando <strong>%s %s</strong>.", "CIRCUIT_REFUSED_TO_ME": "All'utente %s gli è stato rifiutato l'accesso a far parte del '%s' (da parte di %s).",
"CIRCUIT_SENDCOINSREQ_TO_ME": "Stai inviando <strong>%s %s</strong> a %s. \nIl destinatario deve accettare la transazione.", "CIRCUIT_REFUSED_TO_MYGROUP": "Al Conto Collettivo %s gli è stato rifiutato l'accesso a far parte del '%s' (da parte di %s).",
"ID_CIRCUIT_COINS_ACCEPTED": "<strong>%s %s</strong> accettati da %s.", "CIRCUIT_EXIT_USER": "❌ l'utente %s è uscito dal '%s'",
"SALDO_UPDATE": "[Saldo <strong>%s %s</strong>]", "CIRCUIT_EXIT_USER_TO_ME": "❌ Sei uscito dal '%s'",
"ID_CIRCUIT_COINS_ACCEPTED_TO_ME": "<strong>%s %s</strong> sono stati accettati da %s.", "CIRCUIT_REMOVED_TO_ME": "❌ Sei stato rimosso dal '%s' (da parte di %s)",
"ID_CIRCUIT_COINS_REFUSED": "%s %s rifiutati da %s.", "CIRCUIT_SENDCOINSREQ": "%s ti sta inviando <strong>%s %s</strong> sul '%s'.",
"ID_CIRCUIT_COINS_REFUSED_TO_ME": "%s %s rifiutati da %s.", "COMUNITARIO": "Comunitario",
"COLLETTIVO": "Gruppo",
"CIRCUIT_SENDCOINSREQ_GROUP": "%s sta inviando <strong>%s %s</strong> al Conto %s '%s' sul '%s'.",
"CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER": "il conto %s '%s' (%s) sta inviando <strong>%s %s</strong> a %s sul '%s'.",
"CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_YOU": "il conto %s '%s' (%s) ti sta inviando <strong>%s %s</strong> sul '%s'",
"CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_GROUP": "il conto %s '%s' (%s) sta inviando <strong>%s %s</strong> al conto %s '%s' sul '%s'.",
"CIRCUIT_SENDCOINSREQ_TO_ME": "Stai inviando <strong>%s %s</strong> a %s sul '%s'. \nIl destinatario deve accettare la transazione.",
"CIRCUIT_SENDCOINSREQ_TO_GROUP": "Stai inviando <strong>%s %s</strong> al Conto %s '%s' sul '%s'. \nIl destinatario deve accettare la transazione.",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_YOU": "<strong>%s %s</strong> accettati dal Conto %s '%s' sul '%s' (%s) .",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_GROUP": "il conto %s '%s' (%s) ha accettato <strong>%s %s</strong> dal conto %s '%s' sul '%s' (%s).",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_GROUP": "il conto %s '%s' (%s) ha accettato <strong>%s %s</strong> da %s sul '%s'.",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_YOU": "<strong>%s %s</strong> accettati da %s sul '%s'.",
"ID_CIRCUIT_COINS_ACCEPTED": "<strong>%s %s</strong> accettati da %s sul '%s'.",
"SALDO_UPDATE": "[Saldo <strong>%s %s</strong> sul '%s']",
"SALDO_UPDATE_WHO": "[Saldo %s <strong>%s %s</strong> sul '%s']",
"ID_CIRCUIT_COINS_ACCEPTED_TO_ME": "<strong>%s %s</strong> sono stati accettati 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'.",
"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",
"SALDO_VARIATO": "[%s] l'utente %s ha variato il Saldo di %s da %s a %s %s",
"FIDOCONCESSO_VARIATO": "[%s] l'utente %s ha variato il Fido Concesso di %s da %s a %s %s",
"QTAMAX_VARIATO": "[%s] l'utente %s ha variato la quantità massima concessa di %s da %s a %s %s",
"SET_FAVORITE": "%s ha messo 'Mi Piace' al tuo post: %s",
"SET_FAVORITE_OTHERS": "%s e altre %s persone hanno messo 'Mi Piace' al tuo post: %s",
"EVENT_SEND_MSG": "%s ha mandato un messaggio sull'evento %s: \n%s",
"SET_ATTEND": "%s ha detto che Parteciperà all'evento: %s",
"SET_ATTEND_OTHERS": "%s e altre %s persone hanno detto che Parteciperanno all'evento: %s",
"DATEDAYONLY": "%s dalle %s alle %s",
"DATE_2DAYS": "%s dalle %s fino a %s alle %s",
"SENDMSG_ENTRA_IN_RISO_ITALIA": "Ciao %s!<br>%s che appartiene al <em>%s</em> vuole inviarti dei RIS. Per poterli ricevere dovete entrambi utilizzare il <strong>Circuito RIS Italia</strong>.",
"CLICCA_QUI": "CLICCA QUI" "CLICCA_QUI": "CLICCA QUI"
} }

View File

@@ -16,6 +16,17 @@ const authenticate = (req, res, next) => {
// console.log('authenticate... '); // console.log('authenticate... ');
let noaut = false;
if (req.body.hasOwnProperty('noaut')) {
noaut = req.body.noaut;
}
if (noaut) {
next();
return;
}
const access = 'auth'; const access = 'auth';
User.findByToken(token, access).then((user) => { User.findByToken(token, access).then((user) => {

View File

@@ -33,6 +33,12 @@ const AccountSchema = new Schema({
username: { username: {
type: String, type: String,
}, },
groupname: { // For the Groups
type: String,
},
contocom: { // For the Conto Comunitario dei Circuiti
type: String,
},
circuitId: { // ----- REF TO Circuit circuitId: { // ----- REF TO Circuit
type: String, type: String,
}, },
@@ -50,12 +56,23 @@ const AccountSchema = new Schema({
}, },
importo_iniziale: { importo_iniziale: {
type: Number, type: Number,
default: 0,
}, },
saldo: { saldo: {
type: Number, type: Number,
default: 0,
}, },
totTransato: { totTransato: {
type: Number, type: Number,
default: 0,
},
saldo_pend: {
type: Number,
default: 0,
},
totTransato_pend: {
type: Number,
default: 0,
}, },
regulation_ok: { regulation_ok: {
type: Boolean, type: Boolean,
@@ -94,6 +111,9 @@ AccountSchema.pre('save', async function (next) {
AccountSchema.statics.getFieldsForSearch = function () { AccountSchema.statics.getFieldsForSearch = function () {
return [ return [
{ field: 'name', type: tools.FieldType.string }, { field: 'name', type: tools.FieldType.string },
{ field: 'username', type: tools.FieldType.string },
{ field: 'groupname', type: tools.FieldType.string },
{ field: 'contocom', type: tools.FieldType.string },
]; ];
}; };
@@ -129,7 +149,7 @@ AccountSchema.statics.calcTotCircolante = async function (idapp, circuitId) {
{ $group: { _id: null, count: { $sum: '$saldo' } } } { $group: { _id: null, count: { $sum: '$saldo' } } }
]; ];
ris = await Account.aggregate(aggr1); const ris = await Account.aggregate(aggr1);
return ris ? ris[0].count : 0; return ris ? ris[0].count : 0;
@@ -138,23 +158,69 @@ AccountSchema.statics.calcTotCircolante = async function (idapp, circuitId) {
} }
}; };
AccountSchema.methods.addtoSaldoSave = async function (amount) { AccountSchema.methods.calcPending = async function (mittente) {
const account = this; try {
const account = this;
if (account) { const { SendNotif } = require('../models/sendnotif');
account.saldo = account.saldo + amount; const { Circuit } = require('../models/circuit');
if (!account.totTransato) {
account.totTransato = 0; // *** Calc Pending Transactions ***
const circuit = await Circuit.getCircuitById(account.circuitId);
if (circuit) {
let prec_saldo_pend = account.saldo_pend;
let prec_totTransato_pend = account.totTransato_pend;
let transatopending = 0;
if (mittente) {
let pendingtransactionsMittente = await SendNotif.getSumPendingTransactionsMittente(account.idapp, account.username, circuit.name, account.groupname);
let saldopendingMitt = pendingtransactionsMittente.reduce((sum, rec) => sum + rec.extrarec.qty, 0);
transatopending = pendingtransactionsMittente.reduce((sum, rec) => sum + Math.abs(rec.extrarec.qty), 0);
account.saldo_pend = account.saldo - saldopendingMitt;
} else {
// let pendingtransactionsDest = await SendNotif.getSumPendingTransactionsMittente(account.idapp, account.username, circuit.name, account.groupname);
// let saldopendingDest = pendingtransactionsDest.reduce((sum, rec) => sum + rec.extrarec.qty, 0);
// transatopending = pendingtransactionsDest.reduce((sum, rec) => sum + Math.abs(rec.extrarec.qty), 0);
// account.saldo_pend = account.saldo + saldopendingDest;
account.saldo_pend = account.saldo;
}
account.totTransato_pend = account.totTransato + transatopending;
if (prec_saldo_pend !== account.saldo_pend || prec_totTransato_pend !== account.totTransato_pend) {
const myaccountupdate = {
saldo_pend: account.saldo_pend,
totTransato_pend: account.totTransato_pend,
};
// Update Record
return await Account.findByIdAndUpdate(account.id,
{
$set: myaccountupdate
}).then((ris) => {
console.log('calcPending', ris);
}).catch((err) => {
console.error('calcPending', err);
});
}
} }
account.totTransato += Math.abs(amount);
account.date_updated = new Date();
return await account.save(); // -----
} catch (e) {
console.error(e);
} }
return null; }
};
AccountSchema.statics.addtoSaldo = async function (myaccount, amount) { AccountSchema.statics.addtoSaldo = async function (myaccount, amount, mitt) {
const Account = this; const Account = this;
try { try {
@@ -172,10 +238,16 @@ AccountSchema.statics.addtoSaldo = async function (myaccount, amount) {
myaccountupdate.totTransato = myaccount.totTransato; myaccountupdate.totTransato = myaccount.totTransato;
myaccountupdate.date_updated = myaccount.date_updated; myaccountupdate.date_updated = myaccount.date_updated;
return await Account.updateOne({ _id: myaccount.id }, const ris = await Account.updateOne({ _id: myaccount.id },
{ {
$set: myaccountupdate $set: myaccountupdate
}); });
await myaccount.calcPending(mitt);
return ris;
} }
} catch (e) { } catch (e) {
console.error('error', e); console.error('error', e);
@@ -186,13 +258,14 @@ AccountSchema.statics.addtoSaldo = async function (myaccount, amount) {
AccountSchema.pre('save', async function (next) { AccountSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
this.date_created = new Date(); if (!this.date_created)
this.date_created = new Date();
} }
next(); next();
}); });
AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp, username, circuitId, createifnotexist) { AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp, username, circuitId, createifnotexist, confido, groupname = '', contocom = "") {
const Account = this; const Account = this;
try { try {
@@ -203,11 +276,18 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp,
return false; return false;
let myquery = { let myquery = {
'idapp': idapp, idapp,
'username': username,
circuitId, circuitId,
}; };
if (groupname) {
myquery.groupname = groupname;
} else if (contocom) {
myquery.contocom = contocom;
} else {
myquery.username = username;
}
let mycircuit = await Circuit.getCircuitById(circuitId); let mycircuit = await Circuit.getCircuitById(circuitId);
if (mycircuit) { if (mycircuit) {
@@ -217,15 +297,42 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp,
myaccount = new Account({ myaccount = new Account({
_id: new ObjectID().toString(), _id: new ObjectID().toString(),
idapp, idapp,
username, username: (!groupname && !contocom) ? username : '',
groupname,
contocom,
circuitId: mycircuit._id, circuitId: mycircuit._id,
deperibile: false, deperibile: false,
fidoConcesso: mycircuit.fido_scoperto_default,
qta_maxConcessa: mycircuit.qta_max_default,
importo_iniziale: 0, importo_iniziale: 0,
saldo: 0, saldo: 0,
saldo_pend: 0,
fidoConcesso: 0,
qta_maxConcessa: 0,
totTransato: 0,
totTransato_pend: 0,
}); });
if (contocom) {
myaccount.fidoConcesso = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MIN_CONTO_COMUNITARIO;
myaccount.qta_maxConcessa = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MAX_CONTO_COMUNITARIO;
} else {
if (!mycircuit.fido_scoperto_default_grp)
mycircuit.fido_scoperto_default_grp = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MIN_GRP;
if (!mycircuit.qta_max_default_grp)
mycircuit.qta_max_default_grp = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MAX_GRP;
if (groupname) {
myaccount.fidoConcesso = mycircuit.fido_scoperto_default_grp;
myaccount.qta_maxConcessa = mycircuit.qta_max_default_grp;
} else {
myaccount.fidoConcesso = mycircuit.fido_scoperto_default;
myaccount.qta_maxConcessa = mycircuit.qta_max_default;
}
}
if (!confido) {
myaccount.fidoConcesso = 0;
}
return await myaccount.save(); return await myaccount.save();
} }
@@ -239,14 +346,52 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp,
}; };
AccountSchema.statics.createAccount = async function (idapp, username, circuitName) { AccountSchema.statics.isExistAccountByUsernameAndCircuitId = async function (idapp, username, circuitId, groupname = '', contocom = "") {
const Account = this;
try {
const { Circuit } = require('../models/circuit');
if (username === undefined)
return false;
let myquery = {
idapp,
circuitId,
};
if (groupname) {
myquery.groupname = groupname;
} else if (contocom) {
myquery.contocom = contocom;
} else {
myquery.username = username;
}
let mycircuit = await Circuit.getCircuitById(circuitId);
if (mycircuit) {
let myaccount = await Account.findOne(myquery);
return !!myaccount
}
return false;
} catch (e) {
console.error('error', e);
}
};
AccountSchema.statics.createAccount = async function (idapp, username, circuitName, confido, groupname = '', contocom = '') {
const { Circuit } = require('../models/circuit'); const { Circuit } = require('../models/circuit');
try { try {
mycircuit = await Circuit.findOne({ name: circuitName }, {_id: 1}); mycircuit = await Circuit.findOne({ name: circuitName }, { _id: 1 });
if (mycircuit) { if (mycircuit) {
return await Account.getAccountByUsernameAndCircuitId(idapp, username, mycircuit._id, true); return await Account.getAccountByUsernameAndCircuitId(idapp, username, mycircuit._id, true, confido, groupname, contocom);
} else { } else {
return null; return null;
} }
@@ -258,6 +403,7 @@ AccountSchema.statics.createAccount = async function (idapp, username, circuitNa
}; };
AccountSchema.statics.getUserAccounts = async function (idapp, username) { AccountSchema.statics.getUserAccounts = async function (idapp, username) {
const { SendNotif } = require('../models/sendnotif');
try { try {
let aggr1 = [ let aggr1 = [
@@ -289,32 +435,114 @@ AccountSchema.statics.getUserAccounts = async function (idapp, username) {
$match: { $match: {
$expr: { $expr: {
$and: [ $and: [
{ $eq: ['$idapp', '$$idapp'] },
{ $eq: ['$typedir', '$$typedir'] }, { $eq: ['$typedir', '$$typedir'] },
{ $eq: ['$typeid', '$$typeid'] }, { $eq: ['$typeid', '$$typeid'] },
{ $eq: ['$status', 0] }, { $eq: ['$status', 0] },
{ $eq: ['$sender', '$$username'] }, { $eq: ['$sender', '$$username'] },
{ $eq: ['$extrarec.circuitname', '$$circuitname'] },
],
},
},
},
{
$group:
{ _id: "$extrarec.notifIdToUpdate", result: { $first: "$$ROOT" } }
},
],
},
},
];
const ris = await this.aggregate(aggr1);
// console.log('1 - INIZIA getUserAccounts ')
// console.log(aggr1);
/* if (ris) {
for (const account of ris) {
try {
//++OTTIMIZZARE QUESTA PARTE ! (CON UNA QUERY...)
// console.log(' 1B - PENDIND... ')
let pendingtransactions = await SendNotif.getSumPendingTransactions(idapp, username, account.circuit.name);
let saldopending = pendingtransactions.reduce((sum, rec) => sum + rec.extrarec.qty, 0);
if (saldopending !== 0) {
account.saldo -= saldopending;
account.totTransato = account.totTransato || 0;
}
} catch (e) {
console.error('getUserAccounts 1) ', e);
}
}
} */
return ris;
} catch (e) {
console.error('getUserAccounts', e);
}
};
AccountSchema.statics.getGroupAccounts = async function (idapp, groupname) {
if (!groupname) {
return [];
}
try {
let aggr1 = [
{
$match: { idapp, groupname },
},
{
$lookup: {
from: 'circuits',
localField: 'circuitId',
foreignField: '_id',
as: 'circuit',
},
},
{ $unwind: '$circuit' },
{
$lookup: {
from: 'sendnotifs',
as: 'notifspending',
let: {
circuitname: '$circuit.name',
groupname: '$groupname',
idapp: '$idapp',
typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$typedir', '$$typedir'] },
{ $eq: ['$typeid', '$$typeid'] },
{ $eq: ['$status', 0] },
{ $eq: ['$sendergroup', '$$groupname'] },
{ $eq: ['$idapp', '$$idapp'] }, { $eq: ['$idapp', '$$idapp'] },
{ $eq: ['$extrarec.circuitname', '$$circuitname'] }, { $eq: ['$extrarec.circuitname', '$$circuitname'] },
], ],
}, },
}, },
}, },
{
$group:
{ _id: "$extrarec.notifIdToUpdate", result: { $first: "$$ROOT" } }
},
], ],
}, },
}, },
]; ];
ris = await this.aggregate(aggr1); const ris = await this.aggregate(aggr1);
const { SendNotif } = require('../models/sendnotif');
if (ris) {
for (const account of ris) {
const pendingtransactions = await SendNotif.getSumPendingTransactions(idapp, username, account.circuit.name);
const saldopending = pendingtransactions.reduce((sum, rec) => sum + rec.extrarec.qty, 0);
account.saldo -= saldopending;
}
}
return ris; return ris;
} catch (e) { } catch (e) {
@@ -323,6 +551,195 @@ AccountSchema.statics.getUserAccounts = async function (idapp, username) {
}; };
// Imposta a tutti i Conti Collettivi, i seguenti minimi e massimi
AccountSchema.statics.SetMinMaxCollettivi = async function (idapp, valmin, valmax) {
const Account = this;
const ris = await Account.updateMany({ idapp, groupname: { "$nin": [null, ""] } },
{
$set:
{
fidoConcesso: valmin,
qta_maxConcessa: valmax,
}
});
};
// Imposta a tutti i Conti Comunitari, i seguenti minimi e massimi
AccountSchema.statics.SetMinMaxComunitari = async function (idapp, valmin, valmax) {
const Account = this;
const ris = await Account.updateMany({ idapp, contocom: { "$nin": [null, ""] } },
{
$set:
{
fidoConcesso: valmin,
qta_maxConcessa: valmax,
}
});
};
// Imposta a tutti i Conti Personali, i seguenti minimi e massimi
AccountSchema.statics.SetMinMaxPersonali = async function (idapp, fidoConcesso, qta_maxConcessa, circuitId) {
const Account = this;
if (circuitId) {
const ris = await Account.updateMany({ idapp, circuitId, fidoConcesso: { $gt: 0 }, username: { "$nin": [null, ""] } },
{
$set:
{
fidoConcesso,
qta_maxConcessa,
}
});
// Se aggiorno questi dati, allora devo aggiornare anche gli account del RIS Nazionale
await Account.updateAccountCircuitoNazionaleByLimiti(idapp, circuitId, fidoConcesso, qta_maxConcessa);
} else {
const ris = await Account.updateMany({ idapp, fidoConcesso: { $gt: 0 }, username: { "$nin": [null, ""] } },
{
$set:
{
fidoConcesso,
qta_maxConcessa,
}
});
}
};
AccountSchema.statics.updateFido = async function (idapp, username, groupname, circuitId, fido) {
let paramstoupdate = {
fidoConcesso: fido,
};
let risult = null;
if (groupname)
risult = await Account.updateOne({ idapp, circuitId, groupname }, { $set: paramstoupdate });
else
risult = await Account.updateOne({ idapp, username, circuitId }, { $set: paramstoupdate });
return risult;
};
AccountSchema.statics.updateQtaMax = async function (idapp, username, groupname, circuitId, qtamax) {
let paramstoupdate = {
qta_maxConcessa: qtamax,
};
let risult = null;
if (groupname)
risult = await Account.updateOne({ idapp, circuitId, groupname }, { $set: paramstoupdate });
else
risult = await Account.updateOne({ idapp, username, circuitId }, { $set: paramstoupdate });
return risult;
};
AccountSchema.statics.getAccountsCircuitiNazionali = async function (idapp) {
const { Circuit } = require('../models/circuit');
const circuit = await Circuit.find({ idapp, showAlways: true });
return Account.find({ idapp, circuitId: circuit.id });
};
AccountSchema.statics.updateAccountCircuitoNazionaleByLimiti = async function (idapp, circuitId, fidoConcesso, qta_maxConcessa) {
const { Circuit } = require('../models/circuit');
try {
const accounts = await this.getAccountsCircuitiNazionali(idapp);
for (const account of accounts) {
const circuitId = account.circuitId;
const circuit = await Circuit.findOne({ _id: circuitId });
if (circuit) {
let fido = 0;
let qtamax = 0;
if (account.groupname) {
fido = circuit.fido_scoperto_default_grp * shared_consts.CIRCUIT_CFG.MULT_FIDO_GROUP;
qtamax = circuit.qta_max_default_grp * shared_consts.CIRCUIT_CFG.MULT_FIDO_GROUP;
} else {
fido = circuit.fido_scoperto_default * shared_consts.CIRCUIT_CFG.MULT_FIDO_USER;
qtamax = circuit.qta_max_default * shared_consts.CIRCUIT_CFG.MULT_FIDO_USER;
}
let paramstoupdate = {
fidoConcesso: fido,
qta_maxConcessa: qtamax,
};
risult = await Account.updateOne({ _id: account.id }, { $set: paramstoupdate });
}
}
return risult;
} catch (e) {
console.error('updateAccountCircuitoNazionaleByLimiti', e);
}
return false;
};
AccountSchema.statics.canEditAccountAdmins = async function (username, id) {
const account = await Account.findOne({ _id: id }).lean();
const { Circuit } = require('../models/circuit');
if (account) {
const circuit = await Circuit.findOne({ _id: account.circuitId }).lean();
if (circuit) {
return circuit.admins.findIndex((admin) => admin.username === username) >= 0;
}
}
return false;
};
AccountSchema.statics.addToPeopleOfMyAccount = async function (idapp, username, circuitId, person_username, perm) {
return await Account.updateOne({ idapp, username, circuitId },
{
$push:
{
people: {
username: person_username,
perm,
date: new Date(),
},
},
});
};
// Rimuovi dagli Admin del Account
AccountSchema.statics.removeAdminOfAccount = async function (idapp, username, circuitId, person_username, perm) {
const { Circuit } = require('../models/circuit');
return await Circuit.updateOne({ idapp, username, circuitId },
{ $pull: { people: { username: { $in: [person_username] } } } });
};
// Rimuovi l'account
AccountSchema.statics.removeAccount = async function (accountId) {
const { Circuit } = require('../models/circuit');
return await Circuit.deleteOne({ _id: accountId});
};
AccountSchema.statics.updateSaldoAndTransato_AllAccounts = async function (idapp) {
const recaccounts = await Account.find({ idapp });
for (const account of recaccounts) {
await account.calcPending();
}
};
const Account = mongoose.model('Account', AccountSchema); const Account = mongoose.model('Account', AccountSchema);
module.exports = { Account }; module.exports = { Account };

View File

@@ -20,6 +20,12 @@ const bookingSchema = new Schema({
userId: { userId: {
type: String, type: String,
}, },
username: {
type: String,
},
tableType: {
type: Number,
},
id_bookedevent: { id_bookedevent: {
type: String, type: String,
}, },

View File

@@ -11,6 +11,9 @@ const { ObjectID } = require('mongodb');
const { Movement } = require('../models/movement'); const { Movement } = require('../models/movement');
const { Account } = require('../models/account'); const { Account } = require('../models/account');
const { Province } = require('../models/province');
const shared_consts = require('../tools/shared_nodejs');
const i18n = require('i18n'); const i18n = require('i18n');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
@@ -40,6 +43,9 @@ const CircuitSchema = new Schema({
type: String, type: String,
unique: true, unique: true,
}, },
link_group: {
type: String,
},
subname: { subname: {
type: String, type: String,
}, },
@@ -47,6 +53,14 @@ const CircuitSchema = new Schema({
{ {
type: Number, type: Number,
}], }],
strProv:
{
type: String,
},
card: // Punti cardinali
{
type: String,
},
pub_to_share: { pub_to_share: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
}, },
@@ -70,6 +84,9 @@ const CircuitSchema = new Schema({
totCircolante: { totCircolante: {
type: Number, type: Number,
}, },
showAlways: {
type: Boolean,
},
totTransato: { totTransato: {
type: Number, type: Number,
}, },
@@ -106,6 +123,12 @@ const CircuitSchema = new Schema({
qta_max_default: { qta_max_default: {
type: Number, type: Number,
}, },
fido_scoperto_default_grp: {
type: Number,
},
qta_max_default_grp: {
type: Number,
},
data_costituz: { data_costituz: {
type: Date, type: Date,
}, },
@@ -173,6 +196,18 @@ const CircuitSchema = new Schema({
username: { type: String }, username: { type: String },
date: { type: Date }, date: { type: Date },
}], // username }], // username
req_groups: [
{
_id: false,
groupname: { type: String },
date: { type: Date },
}], // username
refused_groups: [
{
_id: false,
groupname: { type: String },
date: { type: Date },
}], // username
deleted: { deleted: {
type: Boolean, type: Boolean,
default: false, default: false,
@@ -184,6 +219,10 @@ const CircuitSchema = new Schema({
type: Number, type: Number,
default: 0, default: 0,
}, },
showAlways: {
type: Boolean,
default: false,
},
status: { status: {
type: Number, type: Number,
default: 0, default: 0,
@@ -207,15 +246,14 @@ CircuitSchema.statics.findAllIdApp = async function (idapp) {
const whatToShow = this.getWhatToShow(idapp, ''); const whatToShow = this.getWhatToShow(idapp, '');
return await Circuit.find(myfind, whatToShow, (err, arrrec) => { return await Circuit.find(myfind, whatToShow).sort({ status: -1, numMembers: -1, name: 1 });
return arrrec;
});
}; };
CircuitSchema.statics.getFieldsForSearch = function () { CircuitSchema.statics.getFieldsForSearch = function () {
return [ return [
{ field: 'nome_circuito', type: tools.FieldType.string }, { field: 'name', type: tools.FieldType.string },
{ field: 'sotto_nome', type: tools.FieldType.string }, { field: 'subname', type: tools.FieldType.string },
{ field: 'path', type: tools.FieldType.string },
{ field: 'nome_valuta', type: tools.FieldType.string }, { field: 'nome_valuta', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string }, { field: 'descr', type: tools.FieldType.string },
]; ];
@@ -245,13 +283,19 @@ CircuitSchema.statics.getWhatToShow = function (idapp, username) {
date_updated: 1, date_updated: 1,
nome_valuta: 1, nome_valuta: 1,
fido_scoperto_default: 1, fido_scoperto_default: 1,
qta_max_default: 1,
fido_scoperto_default_grp: 1,
qta_max_default_grp: 1,
deperimento: 1, deperimento: 1,
showAlways: 1,
transactionsEnabled: 1, transactionsEnabled: 1,
status: 1, status: 1,
qta_max_default: 1,
valuta_per_euro: 1, valuta_per_euro: 1,
symbol: 1, symbol: 1,
idCity: 1, idCity: 1,
strProv: 1,
card: 1,
link_group: 1,
pub_to_share: 1, pub_to_share: 1,
visibility: 1, visibility: 1,
color: 1, color: 1,
@@ -261,6 +305,8 @@ CircuitSchema.statics.getWhatToShow = function (idapp, username) {
admins: 1, admins: 1,
req_users: 1, req_users: 1,
refused_users: 1, refused_users: 1,
req_groups: 1,
refused_groups: 1,
'mycities': 1, 'mycities': 1,
}; };
@@ -298,17 +344,23 @@ CircuitSchema.statics.getWhatToShow_Unknown = function (idapp, username) {
longdescr: 1, longdescr: 1,
regulation: 1, regulation: 1,
numMembers: 1, numMembers: 1,
showAlways: 1,
systemUserId: 1, systemUserId: 1,
founderUserId: 1, founderUserId: 1,
nome_valuta: 1, nome_valuta: 1,
totCircolante: 1, totCircolante: 1,
totTransato: 1, totTransato: 1,
fido_scoperto_default: 1, fido_scoperto_default: 1,
fido_scoperto_default_grp: 1,
qta_max_default_grp: 1,
qta_max_default: 1, qta_max_default: 1,
valuta_per_euro: 1, valuta_per_euro: 1,
symbol: 1, symbol: 1,
color: 1, color: 1,
idCity: 1, idCity: 1,
strProv: 1,
card: 1,
link_group: 1,
pub_to_share: 1, pub_to_share: 1,
visibility: 1, visibility: 1,
abbrev: 1, abbrev: 1,
@@ -320,6 +372,8 @@ CircuitSchema.statics.getWhatToShow_Unknown = function (idapp, username) {
date_updated: 1, date_updated: 1,
req_users: 1, req_users: 1,
refused_users: 1, refused_users: 1,
req_groups: 1,
refused_groups: 1,
transactionsEnabled: 1, transactionsEnabled: 1,
status: 1, status: 1,
'mycities': 1, 'mycities': 1,
@@ -345,14 +399,14 @@ CircuitSchema.statics.getCircuitsByUsername = async function (idapp, username, u
$or: [ $or: [
{ deleted: { $exists: false } }, { deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }], { deleted: { $exists: true, $eq: false } }],
}).lean(); }).sort({ status: -1, numMembers: -1, name: 1 }).lean();
let listcircuits = await Circuit.find({ let listcircuits = await Circuit.find({
idapp, idapp,
$or: [ $or: [
{ deleted: { $exists: false } }, { deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }], { deleted: { $exists: true, $eq: false } }],
}, whatToShow_Unknown).lean(); }, whatToShow_Unknown).sort({ status: -1, numMembers: -1, name: 1 }).lean();
let asked_circuits = await Circuit.find({ let asked_circuits = await Circuit.find({
idapp, idapp,
@@ -362,7 +416,7 @@ CircuitSchema.statics.getCircuitsByUsername = async function (idapp, username, u
$or: [ $or: [
{ deleted: { $exists: false } }, { deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }], { deleted: { $exists: true, $eq: false } }],
}, whatToShow_Unknown).lean(); }, whatToShow_Unknown).sort({ status: -1 }).lean();
let refused_circuits = await Circuit.find({ let refused_circuits = await Circuit.find({
idapp, idapp,
@@ -372,7 +426,7 @@ CircuitSchema.statics.getCircuitsByUsername = async function (idapp, username, u
$or: [ $or: [
{ deleted: { $exists: false } }, { deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }], { deleted: { $exists: true, $eq: false } }],
}, whatToShow_Unknown).lean(); }, whatToShow_Unknown).sort({ status: -1 }).lean();
return { return {
listcircuits, listcircuits,
@@ -430,6 +484,49 @@ CircuitSchema.statics.getCircuitByName = async function (idapp, name) {
}; };
CircuitSchema.statics.getCircuitIdByName = async function (idapp, name) {
const myfind = {
idapp,
name,
};
try {
const circuit = await Circuit.findOne(myfind);
return (!!circuit ? circuit._id : 0);
} catch (e) {
return null;
}
};
CircuitSchema.statics.getCircuitByProvinceAndCard = async function (idapp, strProv, card) {
let myfind = {};
if (card) {
myfind = {
idapp,
strProv,
card
};
} else {
myfind = {
idapp,
strProv,
};
}
try {
return await Circuit.findOne(myfind);
} catch (e) {
return null;
}
};
CircuitSchema.statics.getCircuitById = async function (circuitId) { CircuitSchema.statics.getCircuitById = async function (circuitId) {
const myfind = { const myfind = {
@@ -450,59 +547,6 @@ CircuitSchema.statics.deleteCircuit = async function (idapp, usernameOrig, name)
return await Circuit.findOneAndRemove({ idapp, name }); return await Circuit.findOneAndRemove({ idapp, name });
}; };
CircuitSchema.statics.getUserCircuits = async function (idapp, username) {
try {
let aggr1 = [
{
$match: {
idapp, username,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
},
},
{
$lookup: {
from: 'circuits',
localField: 'circuitId',
foreignField: '_id',
as: 'circuit',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$circuit',
0,
],
},
'$$ROOT',
],
},
},
},
/*
{
$project: {
"circuit.name": 1,
},
},
*/
];
ris = await this.aggregate(aggr1);
return ris;
} catch (e) {
console.error('e', e);
}
};
CircuitSchema.statics.getUsersSingleCircuit = async function (idapp, username, circuitname, circuitId) { CircuitSchema.statics.getUsersSingleCircuit = async function (idapp, username, circuitname, circuitId) {
@@ -550,7 +594,8 @@ CircuitSchema.statics.getUsersSingleCircuit = async function (idapp, username, c
username: 1, username: 1,
name: 1, name: 1,
surname: 1, surname: 1,
profile: 1, idapp: 1 /*, 'circuit.name': 1, 'circuit._id': 1*/ profile: 1,
idapp: 1 /*, 'circuit.name': 1, 'circuit._id': 1*/
}, },
}, },
@@ -602,6 +647,8 @@ CircuitSchema.statics.getCircolanteSingolaTransaz = function (accountorigTable,
CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig, extrarec) { CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig, extrarec) {
const { User } = require('../models/user');
let ris = { let ris = {
result: false, result: false,
cansend: true, cansend: true,
@@ -620,8 +667,30 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
if (circuittable) { if (circuittable) {
const myqty = Math.abs(extrarec.qty); const myqty = Math.abs(extrarec.qty);
const accountdestTable = await Account.getAccountByUsernameAndCircuitId(idapp, extrarec.dest, circuittable._id, true); const esisteDest = await Account.isExistAccountByUsernameAndCircuitId(idapp, extrarec.dest, circuittable._id, extrarec.groupdest, extrarec.contoComDest);
const accountorigTable = await Account.getAccountByUsernameAndCircuitId(idapp, usernameOrig, circuittable._id, true);
if (!esisteDest) {
// Fallo entrare anche sul Circuito (oltre ad aver creato l'Account).
await User.addCircuitToUser(idapp, usernameOrig, extrarec.circuitname, false, extrarec.groupdest, extrarec.contoComDest);
}
if (extrarec.dest) {
const foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(idapp, extrarec.dest, extrarec.circuitname);
if (!foundIfAlreadyCircuit) {
update = {
$push: {
'profile.mycircuits': {
circuitname: extrarec.circuitname,
date: new Date(),
},
},
};
const ris = await User.updateOne({ idapp, username: extrarec.dest }, update);
}
}
const accountdestTable = await Account.getAccountByUsernameAndCircuitId(idapp, extrarec.dest, circuittable._id, true, false, extrarec.groupdest, extrarec.contoComDest);
const accountorigTable = await Account.getAccountByUsernameAndCircuitId(idapp, usernameOrig, circuittable._id, true, true, extrarec.grouporig, extrarec.contoComOrig);
const circolantePrec = this.getCircolanteSingolaTransaz(accountorigTable, accountdestTable); const circolantePrec = this.getCircolanteSingolaTransaz(accountorigTable, accountdestTable);
@@ -631,7 +700,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_FIDO', usernameOrig); ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_FIDO', usernameOrig);
} }
if (accountdestTable.saldo + myqty > accountorigTable.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);
} }
@@ -657,16 +726,31 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
}; };
await Circuit.updateOne({ _id: circuittable }, { $set: paramstoupdate }); await Circuit.updateOne({ _id: circuittable }, { $set: paramstoupdate });
ris.result = true;
console.log('Inviate Monete da', usernameOrig, extrarec.dest, myqty, extrarec.causal);
ris.useraccounts = await Account.getUserAccounts(idapp, usernameOrig);
extrarec.saldoOrig = accountorigTable.saldo; extrarec.saldoOrig = accountorigTable.saldo;
extrarec.saldoDest = accountdestTable.saldo; extrarec.saldoDest = accountdestTable.saldo;
let orig = usernameOrig;
if (extrarec.grouporig) {
orig = extrarec.grouporig + ' (' + usernameOrig + ')'
}
if (extrarec.contoComOrig) {
orig = extrarec.contoComOrig + ' (' + usernameOrig + ')'
}
let dest = (extrarec.dest ? extrarec.dest : '') + (extrarec.groupdest ? extrarec.groupdest : '') + (extrarec.contoComDest ? extrarec.contoComDest : '');
ris.result = true;
let msg = '[<b>' + circuittable.name + '</b>]: Inviate Monete da ' + orig + ' a ' + dest + ' ' + myqty + ' ' + circuittable.symbol + ' [causale: ' + extrarec.causal +
`]\nSaldi:\n${orig}: ` + extrarec.saldoOrig + ' ' + circuittable.symbol + '] ' + `\n${dest}: ` + extrarec.saldoDest + ' ' + circuittable.symbol + ']';
console.log(msg);
ris.useraccounts = await Account.getUserAccounts(idapp, usernameOrig);
tools.writeTransactionLog(msg);
tools.sendMsgTelegramToAdmin(idapp, msg);
} else { } else {
console.log('NON Inviate Monete da', usernameOrig, extrarec.dest, myqty, extrarec.causal); // console.log('NON Inviate Monete da', usernameOrig, extrarec.grouporig, extrarec.dest, extrarec.groupdest, myqty, extrarec.causal);
} }
} }
@@ -688,6 +772,13 @@ CircuitSchema.statics.removeReqCircuit = async function (idapp, username, name)
{ $pull: { req_users: { username: { $in: [username] } } } }); { $pull: { req_users: { username: { $in: [username] } } } });
}; };
// Rimuovo la Richiesta del Gruppo sul Circuito
CircuitSchema.statics.removeReqGroupCircuit = async function (idapp, groupname, name) {
return await Circuit.updateOne({ idapp, name },
{ $pull: { req_groups: { groupname: { $in: [groupname] } } } });
};
// Aggiungi agli utenti Rifiutati del Circuito // Aggiungi agli utenti Rifiutati del Circuito
CircuitSchema.statics.refuseReqCircuit = async function (idapp, username, name) { CircuitSchema.statics.refuseReqCircuit = async function (idapp, username, name) {
@@ -705,6 +796,21 @@ CircuitSchema.statics.refuseReqCircuit = async function (idapp, username, name)
}; };
CircuitSchema.statics.refuseReqGroupCircuit = async function (idapp, groupname, name) {
return await Circuit.updateOne({ idapp, name },
{
$push:
{
refused_groups: {
groupname,
date: new Date(),
},
},
});
};
CircuitSchema.statics.updateData = async function (idapp, circuitname) { CircuitSchema.statics.updateData = async function (idapp, circuitname) {
try { try {
@@ -725,7 +831,13 @@ CircuitSchema.statics.updateData = async function (idapp, circuitname) {
const ris = await User.aggregate(aggr1); const ris = await User.aggregate(aggr1);
let numMembers = ris ? ris[0].count : 0; let numMembers = 0;
try {
numMembers = ris && tools.isArray(ris) ? ris[0].count : 0;
} catch (e) {
};
let paramstoupdate = { let paramstoupdate = {
numMembers: numMembers, numMembers: numMembers,
@@ -747,6 +859,366 @@ CircuitSchema.statics.setDeperimentoOff = async function () {
}; };
CircuitSchema.statics.getNameByCircuitId = async function (circuitId) {
let circuit = await Circuit.findOne({ _id: circuitId });
if (circuit)
return circuit.name;
return '';
};
CircuitSchema.statics.getCircuitByCircuitId = async function (circuitId) {
return await Circuit.findOne({ _id: circuitId });
};
CircuitSchema.statics.getListAdminsByCircuitPath = async function (idapp, circuitPath) {
let arr = await Circuit.findOne({
idapp,
path: circuitPath,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
}, { admins: 1 }).lean();
return arr && arr.admins ? arr.admins : [];
};
// Imposta a tutti i Conti Collettivi, i seguenti minimi e massimi
CircuitSchema.statics.setstrProvByIdCityCircuits = async function (idapp) {
const { City } = require('../models/city');
const arrcircuits = await Circuit.find({ idapp }).lean();
try {
for (const rec of arrcircuits) {
let recstrProv = await City.findOne({ _id: rec.idCity[0] });
if (recstrProv) {
let objProv = {}
objProv['strProv'] = recstrProv.prov;
await Circuit.updateOne({ _id: rec._id }, { $set: objProv });
}
}
} catch (e) {
}
};
CircuitSchema.statics.AbilitaTuttiCircuiti = async function (idapp) {
const ris = await Circuit.updateMany({ idapp },
{
$set:
{
transactionsEnabled: true
}
});
return ris;
};
CircuitSchema.statics.AzzeraRegolamentiTuttiCircuiti = async function (idapp) {
const ris = await Circuit.updateMany({ idapp },
{
$set:
{
regulation: '',
}
});
return ris;
};
// Imposta a tutti i Conti Personali, i seguenti minimi e massimi
CircuitSchema.statics.SetDefMinMaxPersonali = async function (idapp, valmin, valmax, circuitId) {
if (circuitId) {
const ris = await Circuit.updateOne({ _id: circuitId },
{
$set:
{
fido_scoperto_default: valmin,
qta_max_default: valmax,
}
});
} else {
const ris = await Circuit.updateMany({ idapp },
{
$set:
{
fido_scoperto_default: valmin,
qta_max_default: valmax,
}
});
}
};
// Imposta a tutti i Conti Collettivi, i seguenti minimi e massimi
CircuitSchema.statics.getCircuitMyProvince = async function (idapp, username) {
const { User } = require('../models/user');
const myuser = await User.getUserByUsername(idapp, username);
try {
const circuit = await this.getCircuitByProvinceAndCard(idapp, myuser.profile.resid_province, myuser.profile.resid_card);
if (circuit) {
if (await User.ifAlreadyInCircuit(idapp, username, circuit.name)) {
return circuit.name;
}
}
return '[nessun Circuito]';
} catch (e) {
console.error('Error', e);
}
};
// Imposta a tutti i Conti Collettivi, i seguenti minimi e massimi
CircuitSchema.statics.createCircuitIfNotExist = async function (req, idapp, province, card) {
const { User } = require('../models/user');
const useradmin = tools.USER_ADMIN_CIRCUITS;
let myrec = null;
try {
const circuit = await this.getCircuitByProvinceAndCard(idapp, province, card);
const nomeprovincia = await Province.getStrProvinceByProv(province);
if (!circuit && nomeprovincia) {
const circ = new Circuit({
idapp,
name: 'Circuito RIS ' + nomeprovincia,
path: 'ris' + tools.convertSpaces_ToUScore(nomeprovincia.toLowerCase()),
strProv: province,
card,
photos: [],
color: '#ff5500',
deperimento: false,
showAlways: false,
transactionsEnabled: true, // Abilita cmq il circuito dall'inizio
status: shared_consts.CIRCUIT_STATUS.FASE1_CREAZIONE_GRUPPO,
symbol: 'RIS',
fido_scoperto_default: 100,
qta_max_default: 200,
fido_scoperto_default_grp: shared_consts.CIRCUIT_PARAMS.SCOPERTO_MIN_GRP,
qta_max_default_grp: shared_consts.CIRCUIT_PARAMS.SCOPERTO_MAX_GRP,
valuta_per_euro: 1,
totTransato: 0,
totCircolante: 0,
date_created: new Date(),
admins: [{ username: useradmin }],
});
myrec = await circ.save();
if (myrec) {
// nuovo Circuito:
await User.setCircuitCmd(idapp, useradmin, myrec.name,
shared_consts.CIRCUITCMD.CREATE, true, useradmin, myrec).then((ris) => {
});
// aggiungi il creatore al Circuito stesso
await User.setCircuitCmd(idapp, useradmin, myrec.name,
shared_consts.CIRCUITCMD.SET, true, useradmin, myrec).then((ris) => {
});
}
msg = 'Nuovo Circuito Creato in Automatico: ' + myrec.name + ' (da ' + req.user.username + ')';
tools.sendMsgTelegramToAdmin(idapp, msg);
}
} catch (e) {
console.error('Error', e);
}
return myrec;
};
CircuitSchema.statics.getListAdmins = async function (idapp, circuitname) {
let arr = await Circuit.findOne({
idapp,
name: circuitname,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
}, { admins: 1 }).lean();
let mystr = '';
if (arr) {
for (const admin of arr.admins) {
mystr += await tools.getAhref(admin.username, await tools.getLinkUserTelegram(idapp, admin.username)) + ', ';
}
}
return { str: mystr, num: arr ? arr.admins.length : 0 };
};
CircuitSchema.statics.isAdminCircuit = async function (idapp, circuitname, username) {
let arr = await Circuit.findOne({
idapp,
name: circuitname,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
}, { admins: 1 }).lean();
if (arr) {
for (const admin of arr.admins) {
if (admin.username === username)
return true;
}
}
return false;
};
CircuitSchema.statics.getListCircuitsByUsername = async function (idapp, username, groupname) {
let mystr = '';
const { User } = require('../models/user');
const myuser = await User.getUserByUsername(idapp, username);
const useraccounts = await Account.getUserAccounts(idapp, username);
const groupsaccounts = await Account.getGroupAccounts(idapp, groupname);
for (let account of useraccounts) {
if (myuser.profile.mycircuits.find((rec) => (rec.circuitname === account.circuit.name))) {
if (account.groupname === '') {
mystr += '\n👉🏻 ' + account.circuit.name + '\n';
mystr += ' [Saldo: ' + account.saldo + ' RIS, ';
mystr += ' Fido: ' + account.fidoConcesso + ' RIS, ';
mystr += ' Transato: ' + account.totTransato + ' RIS]';
}
}
}
for (let account of groupsaccounts) {
if (myuser.profile.mycircuits.find((rec) => (rec.circuitname === account.circuit.name))) {
mystr += '\n GRUPPO: 👉🏻 <b>' + account.groupname + '</b> in ' + account.circuit.name + '\n';
mystr += ' [Saldo: ' + account.saldo + ' RIS, ';
mystr += ' Fido: ' + account.fidoConcesso + ' RIS, ';
mystr += ' Transato: ' + account.totTransato + ' RIS]';
}
}
if (!mystr) {
mystr = '[Nessun Circuito]';
}
return mystr;
};
CircuitSchema.statics.SetDefMinMaxCollettivi = async function (idapp, valmin, valmax, circuitId) {
if (circuitId) {
const ris = await Circuit.updateOne({ _id: circuitId },
{
$set:
{
fido_scoperto_default_grp: valmin,
qta_max_default_grp: valmax,
}
});
} else {
const ris = await Circuit.updateMany({ idapp },
{
$set:
{
fido_scoperto_default_grp: valmin,
qta_max_default_grp: valmax,
}
});
}
};
CircuitSchema.statics.setFido = async function (idapp, username, circuitName, groupname) {
mycircuit = await Circuit.findOne({ idapp, name: circuitName });
if (mycircuit) {
const circuitId = mycircuit._id;
let account = null;
let fido = 0;
let qtamax = 0;
if (mycircuit.showAlways) {
const { User } = require('../models/user');
const myuser = await User.getUserByUsername(idapp, username);
// Se è il circuito Nazionale, allora prende i valori dal proprio Circuito Locale:
const accountsuser = await Account.getUserAccounts(idapp, username);
if (accountsuser) {
// Se lo trovo della mia provincia, prendo quello
account = accountsuser.find((account) => account.circuit.strProv === myuser.profile.resid_province && account.circuit.card === myuser.profile.resid_card)
if (!account && accountsuser.length > 0) {
// Se non lo trovo, prendo il primo in cui sono entrato !
account = accountsuser[0];
}
if (account && account.circuit) {
if (groupname) {
qtamax = account.circuit.qta_max_default_grp * shared_consts.CIRCUIT_CFG.MULT_FIDO_GROUP;
fido = account.circuit.fido_scoperto_default_grp * shared_consts.CIRCUIT_CFG.MULT_FIDO_GROUP;
} else {
qtamax = account.circuit.qta_max_default * shared_consts.CIRCUIT_CFG.MULT_FIDO_USER;
fido = account.circuit.fido_scoperto_default * shared_consts.CIRCUIT_CFG.MULT_FIDO_USER;
}
}
} else {
// Se non ho Circuiti locali, non applico il Fido !
return false;
}
} else {
account = await Account.getAccountByUsernameAndCircuitId(idapp, username, circuitId, true, true, groupname, '');
if (groupname)
fido = mycircuit.fido_scoperto_default_grp;
else
fido = mycircuit.fido_scoperto_default;
}
if (account) {
if (qtamax > 0) {
await Account.updateQtaMax(idapp, username, groupname, circuitId, qtamax);
}
const ris = await Account.updateFido(idapp, username, groupname, circuitId, fido);
if (ris) {
return { qta_maxConcessa: qtamax, fidoConcesso: fido };
}
}
}
return false;
};
const Circuit = mongoose.model('Circuit', CircuitSchema); const Circuit = mongoose.model('Circuit', CircuitSchema);
module.exports = { Circuit }; module.exports = { Circuit };

View File

@@ -77,6 +77,17 @@ CitySchema.statics.getProvinceByIdCity = async function(idcity) {
return ''; return '';
} }
CitySchema.statics.getCircuitNameBystrProv = async function(strProv) {
const { Circuit } = require('../models/circuit');
const myrec = await Circuit.findOne({strProv}).lean();
if (myrec) {
return myrec.name;
}
return '';
}
CitySchema.statics.getRegionByIdCity = async function(idcity) { CitySchema.statics.getRegionByIdCity = async function(idcity) {
const myrec = await City.findOne({_id: idcity}).lean(); const myrec = await City.findOne({_id: idcity}).lean();
if (myrec) { if (myrec) {

View File

@@ -114,7 +114,7 @@ ExtraListSchema.statics.getTotInLista = async function (idapp) {
const myfind = { idapp }; const myfind = { idapp };
return await ExtraList.count(myfind); return await ExtraList.countDocuments(myfind);
}; };
ExtraListSchema.statics.getRegDellaLista = async function (idapp) { ExtraListSchema.statics.getRegDellaLista = async function (idapp) {
@@ -122,7 +122,7 @@ ExtraListSchema.statics.getRegDellaLista = async function (idapp) {
const myfind = { idapp, registered: true }; const myfind = { idapp, registered: true };
return await ExtraList.count(myfind); return await ExtraList.countDocuments(myfind);
}; };
ExtraListSchema.statics.getLastUser = function (idapp) { ExtraListSchema.statics.getLastUser = function (idapp) {

View File

@@ -138,7 +138,7 @@ GraduatoriaSchema.statics.findByAllRecByUsername = function (idapp, username) {
GraduatoriaSchema.statics.getNumDaImbarcare = async function (idapp) { GraduatoriaSchema.statics.getNumDaImbarcare = async function (idapp) {
const Graduatoria = this; const Graduatoria = this;
return await Graduatoria.count({ idapp }) return await Graduatoria. countDocuments({ idapp })
}; };

View File

@@ -74,7 +74,7 @@ MailingListSchema.statics.getnumSent = async function (idapp, idmailinglist) {
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit. // Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return await MailingList.count(myfind); return await MailingList.countDocuments(myfind);
}; };
MailingListSchema.statics.isOk = async function (idapp, iduser, idmailinglist) { MailingListSchema.statics.isOk = async function (idapp, iduser, idmailinglist) {
@@ -84,7 +84,7 @@ MailingListSchema.statics.isOk = async function (idapp, iduser, idmailinglist) {
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit. // Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return await MailingList.count(myfind) > 0; return await MailingList.countDocuments(myfind) > 0;
}; };
MailingListSchema.statics.findAllIdApp = async function (idapp) { MailingListSchema.statics.findAllIdApp = async function (idapp) {

View File

@@ -6,8 +6,8 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const {ObjectID} = require('mongodb'); const { ObjectID } = require('mongodb');
const {Account} = require('../models/account'); const { Account } = require('../models/account');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => { mongoose.plugin(schema => {
@@ -17,7 +17,7 @@ mongoose.plugin(schema => {
const MovementSchema = new Schema({ const MovementSchema = new Schema({
_id: { _id: {
type: String, type: String,
default: function() { default: function () {
return new ObjectID().toString(); return new ObjectID().toString();
}, },
}, },
@@ -47,26 +47,28 @@ const MovementSchema = new Schema({
}, },
causal: { causal: {
type: String, type: String,
default: '',
}, },
residual: { residual: {
type: Number, type: Number,
default: 0,
}, },
expiringDate: { expiringDate: {
type: Date, type: Date,
}, },
}); });
MovementSchema.statics.findAllIdApp = async function(idapp) { MovementSchema.statics.findAllIdApp = async function (idapp) {
const MyMovement = this; const MyMovement = this;
const myfind = {idapp}; const myfind = { idapp };
return await MyMovement.find(myfind, (err, arrrec) => { return await MyMovement.find(myfind, (err, arrrec) => {
return arrrec; return arrrec;
}); });
}; };
MovementSchema.pre('save', async function(next) { MovementSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
this.transactionDate = new Date(); this.transactionDate = new Date();
@@ -75,45 +77,45 @@ MovementSchema.pre('save', async function(next) {
next(); next();
}); });
MovementSchema.statics.getFieldsForSearch = function() { MovementSchema.statics.getFieldsForSearch = function () {
return [ return [
{field: 'causal', type: tools.FieldType.string}, { field: 'causal', type: tools.FieldType.string },
{field: 'amount', type: tools.FieldType.number}, { field: 'amount', type: tools.FieldType.number },
]; ];
}; };
MovementSchema.statics.executeQueryTable = function(idapp, params) { MovementSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch(); params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params); return tools.executeQueryTable(this, 0, params);
}; };
MovementSchema.statics.addMov = async function(idapp, accountFromIdTable, accountToIdTable, amount, causal, notifId) { MovementSchema.statics.addMov = async function (idapp, accountFromIdTable, accountToIdTable, amount, causal, notifId) {
try { try {
// Only positive values // Only positive values
amount = Math.abs(amount); amount = Math.abs(amount);
let mymov = await Movement.create( let mymov = await Movement.create(
{ {
_id: new ObjectID().toString(), _id: new ObjectID().toString(),
idapp, idapp,
transactionDate: new Date(), transactionDate: new Date(),
accountFromId: accountFromIdTable._id, accountFromId: accountFromIdTable._id,
accountToId: accountToIdTable._id, accountToId: accountToIdTable._id,
amount, amount,
causal, causal,
residual: 0, residual: 0,
notifId, notifId,
// expiringDate: // expiringDate:
}, },
); );
if (mymov) { if (mymov) {
// Update saldo dell'Account // Update saldo dell'Account
await Account.addtoSaldo(accountToIdTable, amount); await Account.addtoSaldo(accountToIdTable, amount, true);
await Account.addtoSaldo(accountFromIdTable, -amount); await Account.addtoSaldo(accountFromIdTable, -amount, false);
return mymov; return mymov;
} }
@@ -122,13 +124,13 @@ MovementSchema.statics.addMov = async function(idapp, accountFromIdTable, accoun
} }
}; };
MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username, circuitId) { MovementSchema.statics.getQueryMovsByCircuitId = async function (idapp, username, groupname, contocom, circuitId) {
try { try {
if (!circuitId) { if (!circuitId) {
return []; return [];
} }
const myaccount = await Account.getAccountByUsernameAndCircuitId(idapp, username, circuitId, false); const myaccount = await Account.getAccountByUsernameAndCircuitId(idapp, username, circuitId, false, true, groupname, contocom);
if (myaccount) { if (myaccount) {
@@ -137,8 +139,8 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
$match: { $match: {
idapp, idapp,
$or: [ $or: [
{accountFromId: myaccount._id}, { accountFromId: myaccount._id },
{accountToId: myaccount._id}], { accountToId: myaccount._id }],
}, },
}, },
{ {
@@ -149,30 +151,92 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
as: 'accfrom', as: 'accfrom',
}, },
}, },
{$unwind: '$accfrom'}, { $unwind: '$accfrom' },
{ {
$lookup: { $lookup: {
from: 'users', from: 'users',
let: {username: '$accfrom.username', idapp: '$accfrom.idapp'}, let: { username: '$accfrom.username', idapp: '$accfrom.idapp' },
pipeline: [ pipeline: [
{ {
$match: $match:
{ {
$expr: $expr:
{ {
$and: $and:
[ [
{$eq: ['$$username', '$username']}, { $eq: ['$$username', '$username'] },
{$eq: ['$$idapp', '$idapp']}, { $eq: ['$$idapp', '$idapp'] },
], ],
}, },
}, },
}, },
], ],
as: 'userfrom', as: 'userfrom',
}, },
}, },
{$unwind: '$userfrom'}, {
$unwind: {
path: '$userfrom',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'mygroups',
let: { groupname: '$accfrom.groupname', idapp: '$accfrom.idapp' },
pipeline: [
{
$match:
{
$expr:
{
$and:
[
{ $eq: ['$$groupname', '$groupname'] },
{ $eq: ['$$idapp', '$idapp'] },
],
},
},
},
],
as: 'groupfrom',
},
},
{
$unwind: {
path: '$groupfrom',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'circuits',
let: { contocom: '$accfrom.contocom', idapp: '$accfrom.idapp' },
pipeline: [
{
$match:
{
$expr:
{
$and:
[
{ $eq: ['$$contocom', '$path'] },
{ $eq: ['$$idapp', '$idapp'] },
],
},
},
},
],
as: 'contocomfrom',
},
},
{
$unwind: {
path: '$contocomfrom',
preserveNullAndEmptyArrays: true,
},
},
{ {
$lookup: { $lookup: {
from: 'accounts', from: 'accounts',
@@ -181,66 +245,137 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
as: 'accto', as: 'accto',
}, },
}, },
{$unwind: '$accto'}, { $unwind: '$accto' },
{ {
'$lookup': { $lookup: {
'from': 'circuits', from: 'circuits',
'localField': 'accfrom.circuitId', localField: 'accfrom.circuitId',
'foreignField': '_id', foreignField: '_id',
'as': 'circuitfrom', as: 'circuitfrom',
}, },
}, },
{ {
'$unwind': '$circuitfrom', $unwind: '$circuitfrom',
}, },
{ {
'$lookup': { $lookup: {
'from': 'circuits', from: 'circuits',
'localField': 'accto.circuitId', localField: 'accto.circuitId',
'foreignField': '_id', foreignField: '_id',
'as': 'circuitto', as: 'circuitto',
}, },
}, },
{ {
'$unwind': '$circuitto', $unwind: '$circuitto',
}, },
{ {
$lookup: { $lookup: {
from: 'users', from: 'users',
let: {username: '$accto.username', idapp: '$accto.idapp'}, let: { username: '$accto.username', idapp: '$accto.idapp' },
pipeline: [ pipeline: [
{ {
$match: $match:
{ {
$expr: $expr:
{ {
$and: $and:
[ [
{$eq: ['$$username', '$username']}, { $eq: ['$$username', '$username'] },
{$eq: ['$$idapp', '$idapp']}, { $eq: ['$$idapp', '$idapp'] },
], ],
}, },
}, },
}, },
], ],
as: 'userto', as: 'userto',
}, },
}, },
{$unwind: '$userto'}, {
$unwind: {
path: '$userto',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'mygroups',
let: { groupname: '$accto.groupname', idapp: '$accto.idapp' },
pipeline: [
{
$match:
{
$expr:
{
$and:
[
{ $eq: ['$$groupname', '$groupname'] },
{ $eq: ['$$idapp', '$idapp'] },
],
},
},
},
],
as: 'groupto',
},
},
{
$unwind: {
path: '$groupto',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'circuits',
let: { contocom: '$accto.contocom', idapp: '$accto.idapp' },
pipeline: [
{
$match:
{
$expr:
{
$and:
[
{ $eq: ['$$contocom', '$path'] },
{ $eq: ['$$idapp', '$idapp'] },
],
},
},
},
],
as: 'contocomto',
},
},
{
$unwind: {
path: '$contocomto',
preserveNullAndEmptyArrays: true,
},
},
{ {
$project: $project:
{ {
transactionDate: 1, transactionDate: 1,
amount: 1, amount: 1,
causal: 1, causal: 1,
notifId: 1, notifId: 1,
'circuitfrom.symbol': 1, 'circuitfrom.symbol': 1,
'circuitto.symbol': 1, 'circuitto.symbol': 1,
'userfrom.username': 1, 'userfrom.username': 1,
'userfrom.profile.img': 1, 'userfrom.profile.img': 1,
'userto.username': 1, 'userto.username': 1,
'userto.profile.img': 1, 'userto.profile.img': 1,
}, 'groupfrom.groupname': 1,
'groupfrom.title': 1,
'groupfrom.photos': 1,
'groupto.groupname': 1,
'groupto.title': 1,
'groupto.photos': 1,
'contocomfrom.path': 1,
'contocomfrom.name': 1,
'contocomto.path': 1,
'contocomto.name': 1,
},
}, },
]; ];
@@ -255,7 +390,8 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
return []; return [];
}; };
MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, circuitId) {
MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function (idapp, circuitId) {
try { try {
if (!circuitId) { if (!circuitId) {
@@ -275,24 +411,24 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
as: 'accfrom', as: 'accfrom',
}, },
}, },
{$unwind: '$accfrom'}, { $unwind: '$accfrom' },
{ {
$lookup: { $lookup: {
from: 'users', from: 'users',
let: {username: '$accfrom.username', idapp: '$accfrom.idapp'}, let: { username: '$accfrom.username', idapp: '$accfrom.idapp' },
pipeline: [ pipeline: [
{ {
$match: $match:
{ {
$expr: $expr:
{ {
$and: $and:
[ [
{$eq: ['$$username', '$username']}, { $eq: ['$$username', '$username'] },
{$eq: ['$$idapp', '$idapp']}, { $eq: ['$$idapp', '$idapp'] },
], ],
}, },
}, },
}, },
], ],
as: 'userfrom', as: 'userfrom',
@@ -304,6 +440,62 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
preserveNullAndEmptyArrays: true, preserveNullAndEmptyArrays: true,
}, },
}, },
{
$lookup: {
from: 'mygroups',
let: { groupname: '$accfrom.groupname', idapp: '$accfrom.idapp' },
pipeline: [
{
$match:
{
$expr:
{
$and:
[
{ $eq: ['$$groupname', '$groupname'] },
{ $eq: ['$$idapp', '$idapp'] },
],
},
},
},
],
as: 'groupfrom',
},
},
{
$unwind: {
path: '$groupfrom',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'circuits',
let: { contocom: '$accfrom.contocom', idapp: '$accfrom.idapp' },
pipeline: [
{
$match:
{
$expr:
{
$and:
[
{ $eq: ['$$contocom', '$path'] },
{ $eq: ['$$idapp', '$idapp'] },
],
},
},
},
],
as: 'contocomfrom',
},
},
{
$unwind: {
path: '$contocomfrom',
preserveNullAndEmptyArrays: true,
},
},
{ {
$lookup: { $lookup: {
from: 'accounts', from: 'accounts',
@@ -319,7 +511,7 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
}, },
}, },
{ {
$match: {'accto.circuitId': circuitId}, $match: { 'accto.circuitId': circuitId },
}, },
{ {
'$lookup': { '$lookup': {
@@ -352,20 +544,20 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
{ {
$lookup: { $lookup: {
from: 'users', from: 'users',
let: {username: '$accto.username', idapp: '$accto.idapp'}, let: { username: '$accto.username', idapp: '$accto.idapp' },
pipeline: [ pipeline: [
{ {
$match: $match:
{ {
$expr: $expr:
{ {
$and: $and:
[ [
{$eq: ['$$username', '$username']}, { $eq: ['$$username', '$username'] },
{$eq: ['$$idapp', '$idapp']}, { $eq: ['$$idapp', '$idapp'] },
], ],
}, },
}, },
}, },
], ],
as: 'userto', as: 'userto',
@@ -378,19 +570,85 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
}, },
}, },
{ {
$project: $lookup: {
from: 'mygroups',
let: { groupname: '$accto.groupname', idapp: '$accto.idapp' },
pipeline: [
{ {
transactionDate: 1, $match:
amount: 1, {
causal: 1, $expr:
notifId: 1, {
'circuitfrom.symbol': 1, $and:
'circuitto.symbol': 1, [
'userfrom.username': 1, { $eq: ['$$groupname', '$groupname'] },
'userfrom.profile.img': 1, { $eq: ['$$idapp', '$idapp'] },
'userto.username': 1, ],
'userto.profile.img': 1, },
},
}, },
],
as: 'groupto',
},
},
{
$unwind: {
path: '$groupto',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'circuits',
let: { contocom: '$accto.contocom', idapp: '$accto.idapp' },
pipeline: [
{
$match:
{
$expr:
{
$and:
[
{ $eq: ['$$contocom', '$path'] },
{ $eq: ['$$idapp', '$idapp'] },
],
},
},
},
],
as: 'contocomto',
},
},
{
$unwind: {
path: '$contocomto',
preserveNullAndEmptyArrays: true,
},
},
{
$project:
{
transactionDate: 1,
amount: 1,
causal: 1,
notifId: 1,
'circuitfrom.symbol': 1,
'circuitto.symbol': 1,
'userfrom.username': 1,
'userfrom.profile.img': 1,
'userto.username': 1,
'userto.profile.img': 1,
'groupfrom.groupname': 1,
'groupfrom.title': 1,
'groupto.groupname': 1,
'groupto.title': 1,
'contocomfrom.path': 1,
'contocomfrom.name': 1,
'contocomfrom.title': 1,
'contocomto.path': 1,
'contocomto.name': 1,
'contocomto.title': 1,
},
}, },
]; ];
@@ -404,10 +662,10 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
return []; return [];
}; };
MovementSchema.statics.getMovsByCircuitId = async function(idapp, username, circuitId) { MovementSchema.statics.getMovsByCircuitId = async function (idapp, username, circuitId) {
const MyMovement = this; const MyMovement = this;
const myquery = await MyMovement.getQueryMovsByCircuitId(idapp, username, circuitId); const myquery = await MyMovement.getQueryMovsByCircuitId(idapp, username, '', '', circuitId);
if (myquery && myquery.length > 0) { if (myquery && myquery.length > 0) {
ris = await MyMovement.aggregate(myquery); ris = await MyMovement.aggregate(myquery);
@@ -418,12 +676,11 @@ MovementSchema.statics.getMovsByCircuitId = async function(idapp, username, circ
return []; return [];
}; };
MovementSchema.statics.checkIfCoinsAlreadySent = async function(notifId) { MovementSchema.statics.checkIfCoinsAlreadySent = async function (notifId) {
const MyMovement = this; const MyMovement = this;
try { try {
const rec = await MyMovement.findOne({notifId}, {_id: 1}); const rec = await MyMovement.findOne({ notifId }, { _id: 1 });
return !!rec; return !!rec;
} catch (e) { } catch (e) {
@@ -436,4 +693,4 @@ MovementSchema.statics.checkIfCoinsAlreadySent = async function(notifId) {
const Movement = mongoose.model('Movement', MovementSchema); const Movement = mongoose.model('Movement', MovementSchema);
module.exports = {Movement}; module.exports = { Movement };

View File

@@ -7,6 +7,11 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const { ObjectID } = require('mongodb'); const { ObjectID } = require('mongodb');
const shared_consts = require('../tools/shared_nodejs');
const { Reaction } = require('./reaction');
const tableModel = shared_consts.TABLES_MYBACHECAS;
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => { mongoose.plugin(schema => {
@@ -14,92 +19,112 @@ mongoose.plugin(schema => {
}); });
const MyBachecaSchema = new Schema({ const MyBachecaSchema = new Schema({
_id: { ...{
type: Number, _id: {
},
idapp: {
type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
idSector: {
type: Number,
},
idSkill: {
type: Number,
default: 0,
},
idStatusSkill: [
{
type: Number,
}],
idContribType: [
{
type: String, type: String,
}], default: function () {
idCity: [ return new ObjectID().toString();
{ },
},
idapp: {
type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
groupname: { type: String },
idSector: {
type: Number, type: Number,
}], },
dateTimeStart: { idSkill: {
type: Date, type: Number,
}, default: 0,
dateTimeEnd: { },
type: Date, idStatusSkill: [
}, {
numLevel: { type: Number,
type: Number, }],
default: 0, idContribType: [
}, {
adType: {
type: Number,
},
photos: [
{
imagefile: {
type: String, type: String,
}, }],
alt: { idCity: [
type: String, {
}, type: Number,
description: { }],
type: String, dateTimeStart: {
}, type: Date,
}], },
note: { dateTimeEnd: {
type: String, type: Date,
default: '', },
}, organisedBy: {
descr: { type: String
type: String, },
}, contact_phone: {
//**ADDFIELD_MYBACHECAS type: String
website: { },
type: String, contact_telegram: {
}, type: String
date_created: { },
type: Date, address: {
default: Date.now, type: String,
}, },
date_updated: { min_partecip: {
type: Date, type: Number,
},
max_partecip: {
type: Number,
},
link_maplocation: {
type: String,
},
contribstr: {
type: String,
},
numLevel: {
type: Number,
default: 0,
},
adType: {
type: Number,
},
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
note: {
type: String,
default: '',
},
descr: {
type: String,
},
//**ADDFIELD_MYBACHECAS
website: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
}, },
...Reaction.getFieldsForReactions()
}); });
MyBachecaSchema.pre('save', async function (next) { MyBachecaSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
const myrec = await MyBacheca.findOne().limit(1).sort({ _id: -1 }); if (!this.date_created)
if (!!myrec) { this.date_created = new Date();
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date();
} }
next(); next();
@@ -144,37 +169,7 @@ MyBachecaSchema.statics.executeQueryTable = function (idapp, params, user) {
lk_FF: '_id', lk_FF: '_id',
lk_as: 'user', lk_as: 'user',
af_objId_tab: 'myId', af_objId_tab: 'myId',
lk_proj: { lk_proj: shared_consts.getProjectForAll({}, tableModel),
idSkill: 1,
idSubSkill: 1,
MyBacheca: 1,
idStatusSkill: 1,
idContribType: 1,
dateTimeStart: 1,
dateTimeEnd: 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
//**ADDFIELD_MYBACHECAS
website: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
'profile.img': 1,
"profile.mygroups": 1,
'profile.qualifica': 1,
reported: 1,
date_report: 1,
username_who_report: 1,
},
}, },
}; };
@@ -186,28 +181,24 @@ MyBachecaSchema.statics.executeQueryTable = function (idapp, params, user) {
MyBachecaSchema.statics.getMyRecById = function (idapp, id) { MyBachecaSchema.statics.getMyRecById = function (idapp, id) {
const MyBacheca = this; const MyBacheca = this;
const query = [
let myparsid = {
'_id': id,
idapp,
};
let query = [
{ {
'$match': { $match:
'$and': [ myparsid,
{ },
'_id': parseInt(id), {
}, $sort: {
], desc: 1,
}, },
}, },
{ {
'$match': { $addFields: {
'idapp': idapp,
},
},
{
'$sort': {
'desc': 1,
},
},
{
'$addFields': {
'myId1': { 'myId1': {
'$toObjectId': '$userId', '$toObjectId': '$userId',
}, },
@@ -237,39 +228,7 @@ MyBachecaSchema.statics.getMyRecById = function (idapp, id) {
}, },
}, },
{ {
'$project': { '$project': shared_consts.getProjectForAll({}, tableModel),
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
dateTimeStart: 1,
dateTimeEnd: 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYBACHECAS
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -295,39 +254,7 @@ MyBachecaSchema.statics.getMyRecById = function (idapp, id) {
}, },
}, },
{ {
'$project': { '$project': shared_consts.getProjectForAll({}, tableModel),
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
dateTimeStart: 1,
dateTimeEnd: 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYBACHECAS
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -353,40 +280,22 @@ MyBachecaSchema.statics.getMyRecById = function (idapp, id) {
}, },
}, },
{ {
'$project': { $lookup: {
'recSkill': 1, 'from': 'mygroups',
'sector': 1, 'localField': 'groupname',
'idSector': 1, 'foreignField': 'groupname',
'idSkill': 1, 'as': 'mygrp',
'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
dateTimeStart: 1,
dateTimeEnd: 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYBACHECAS
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
}, },
}, },
{
$unwind: {
path: '$mygrp',
preserveNullAndEmptyArrays: true,
},
},
{
'$project': shared_consts.getProjectForAll({}, tableModel),
},
/*{ /*{
'$lookup': { '$lookup': {
'from': 'subskills', 'from': 'subskills',
@@ -411,39 +320,7 @@ MyBachecaSchema.statics.getMyRecById = function (idapp, id) {
}, },
}, },
{ {
'$project': { '$project': shared_consts.getProjectForAll({}, tableModel),
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
// 'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
dateTimeStart: 1,
dateTimeEnd: 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYBACHECAS
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -468,48 +345,29 @@ MyBachecaSchema.statics.getMyRecById = function (idapp, id) {
}, },
}, },
}, },
{
'$project': {
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
// 'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
dateTimeStart: 1,
dateTimeEnd: 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYBACHECAS
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
},
]; ];
try {
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYBACHECAS);
let objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: shared_consts.getProjectForAll(objadd.proj, tableModel),
};
query = [...query, { ...toadd }];
} catch (e) {
console.error('e', e);
}
return MyBacheca.aggregate(query).then((rec) => { return MyBacheca.aggregate(query).then((rec) => {
return rec ? rec[0] : null; return rec ? rec[0] : null;
}); });
}; };
MyBachecaSchema.statics.getCompleteRecord = function (idapp, id) { MyBachecaSchema.statics.getCompleteRecord = function (idapp, id) {
const MyBacheca = this; const MyBacheca = this;

View File

@@ -143,6 +143,7 @@ const MyElemSchema = new Schema({
anim: animation, anim: animation,
active: { active: {
type: Boolean, type: Boolean,
default: false,
}, },
class: { class: {
type: String, type: String,

View File

@@ -6,7 +6,11 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const {ObjectID} = require('mongodb'); const { Reaction } = require('./reaction');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => { mongoose.plugin(schema => {
@@ -14,104 +18,96 @@ mongoose.plugin(schema => {
}); });
const MyGoodSchema = new Schema({ const MyGoodSchema = new Schema({
_id: { ...{
type: Number, _id: {
},
idapp: {
type: String,
required: true,
},
userId: {type: Schema.Types.ObjectId, ref: 'User'},
idSectorGood: {
type: Number,
},
idGood: {
type: Number,
default: 0,
},
idShipping: [
{
type: Number,
}],
idContribType: [
{
type: String, type: String,
}], },
idCity: [ idapp: {
{ type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
idSectorGood: {
type: Number,
},
idGood: {
type: Number,
default: 0,
},
idShipping: [
{
type: Number,
}],
idContribType: [
{
type: String,
}],
idCity: [
{
type: Number,
}],
pub_to_share: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
},
numLevel: {
type: Number,
default: 0,
},
adType: {
type: Number,
},
otherfilters: [{
type: Number, type: Number,
}], }],
pub_to_share: { photos: [
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW {
}, imagefile: {
numLevel: { type: String,
type: Number, },
default: 0, alt: {
}, type: String,
adType: { },
type: Number, description: {
}, type: String,
otherfilters: [{ },
type: Number, }],
}], note: {
photos: [ type: String,
{ default: '',
imagefile: { },
type: String, descr: {
}, type: String,
alt: { },
type: String, //**ADDFIELD_MyGood
}, website: {
description: { type: String,
type: String, },
}, date_created: {
}], type: Date,
note: { },
type: String, date_updated: {
default: '', type: Date,
}, },
descr: {
type: String,
},
//**ADDFIELD_MyGood
website: {
type: String,
},
date_created: {
type: Date,
default: Date.now,
},
date_updated: {
type: Date,
}, },
...Reaction.getFieldsForReactions()
}); });
MyGoodSchema.pre('save', async function(next) { MyGoodSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
const myrec = await MyGood.findOne().limit(1).sort({_id: -1}); if (!this.date_created)
if (!!myrec) { this.date_created = new Date();
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date();
} }
next(); next();
}); });
MyGoodSchema.statics.findAllIdApp = async function(idapp) { MyGoodSchema.statics.findAllIdApp = async function (idapp) {
const MyGood = this; const MyGood = this;
const query = [ const query = [
{$match: {idapp}}, { $match: { idapp } },
{$sort: {descr: 1}}, { $sort: { descr: 1 } },
]; ];
return await MyGood.aggregate(query).then((arrrec) => { return await MyGood.aggregate(query).then((arrrec) => {
@@ -120,21 +116,21 @@ MyGoodSchema.statics.findAllIdApp = async function(idapp) {
}; };
MyGoodSchema.statics.getFieldsForSearch = function() { MyGoodSchema.statics.getFieldsForSearch = function () {
return []; return [];
}; };
MyGoodSchema.statics.getFieldsLastForSearch = function() { MyGoodSchema.statics.getFieldsLastForSearch = function () {
return [ return [
{field: 'note', type: tools.FieldType.string}, { field: 'note', type: tools.FieldType.string },
{field: 'descr', type: tools.FieldType.string}, { field: 'descr', type: tools.FieldType.string },
{field: 'recGood.descr', type: tools.FieldType.string}, { field: 'recGood.descr', type: tools.FieldType.string },
{field: 'MyGood.descr', type: tools.FieldType.string}, { field: 'MyGood.descr', type: tools.FieldType.string },
]; ];
}; };
MyGoodSchema.statics.executeQueryTable = function(idapp, params, user) { MyGoodSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch(); params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch(); params.fieldsearch_last = this.getFieldsLastForSearch();
@@ -145,60 +141,27 @@ MyGoodSchema.statics.executeQueryTable = function(idapp, params, user) {
lk_FF: '_id', lk_FF: '_id',
lk_as: 'user', lk_as: 'user',
af_objId_tab: 'myId', af_objId_tab: 'myId',
lk_proj: { lk_proj: this.getProject(),
idGood: 1,
idShipping: 1,
MyGood: 1,
idStatusGood: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
otherfilters: 1,
photos: 1,
note: 1,
website: 1,
//**ADDFIELD_MyGood
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
}; };
params = {...params, ...otherparams}; params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user); return tools.executeQueryTable(this, idapp, params, user);
}; };
MyGoodSchema.statics.getMyRecById = function(idapp, idGood) { MyGoodSchema.statics.getMyRecById = function (idapp, idGood) {
const MyGood = this; const MyGood = this;
const query = [ let myparsid = {
'_id': idGood,
idapp,
};
let query = [
{ {
'$match': { '$match':
'$and': [ myparsid,
{
'_id': parseInt(idGood),
},
],
},
},
{
'$match': {
'idapp': idapp,
},
}, },
{ {
'$sort': { '$sort': {
@@ -236,38 +199,7 @@ MyGoodSchema.statics.getMyRecById = function(idapp, idGood) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
otherfilters: 1,
'photos': 1,
note: 1,
website: 1,
//**ADDFIELD_MyGood
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -293,38 +225,7 @@ MyGoodSchema.statics.getMyRecById = function(idapp, idGood) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
otherfilters: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MyGood
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -351,38 +252,7 @@ MyGoodSchema.statics.getMyRecById = function(idapp, idGood) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
otherfilters: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MyGood
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -408,38 +278,7 @@ MyGoodSchema.statics.getMyRecById = function(idapp, idGood) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
otherfilters: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MyGood
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -464,55 +303,49 @@ MyGoodSchema.statics.getMyRecById = function(idapp, idGood) {
}, },
}, },
}, },
{
'$project': {
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
otherfilters: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MyGood
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
},
]; ];
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYGOODS);
const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: this.getProject(objadd.proj),
};
query = [...query, { ...toadd }];
return MyGood.aggregate(query).then((rec) => { return MyGood.aggregate(query).then((rec) => {
return rec ? rec[0] : null; return rec ? rec[0] : null;
}); });
}; };
MyGoodSchema.statics.getCompleteRecord = function(idapp, id) { MyGoodSchema.statics.getCompleteRecord = function (idapp, id) {
const MyGood = this; const MyGood = this;
return MyGood.getMyRecById(idapp, id); return MyGood.getMyRecById(idapp, id);
}; };
MyGoodSchema.statics.getProject = function () {
let proj = {
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
//**ADDFIELD_MYGOOD
};
const proj_add = shared_consts.getProjectForAll()
return Object.assign({}, proj, proj_add);
}
const MyGood = mongoose.model('MyGood', MyGoodSchema); const MyGood = mongoose.model('MyGood', MyGoodSchema);
module.exports = {MyGood}; module.exports = { MyGood };

View File

@@ -15,7 +15,10 @@ mongoose.plugin(schema => {
const MyGroupSchema = new Schema({ const MyGroupSchema = new Schema({
_id: { _id: {
type: Number, type: String,
default: function () {
return new ObjectID().toString();
},
}, },
idapp: { idapp: {
type: String, type: String,
@@ -75,8 +78,9 @@ const MyGroupSchema = new Schema({
}, },
admins: [ admins: [
{ {
username: {type: String}, username: { type: String },
date: {type: Date}, perm: { type: Number },
date: { type: Date },
}, },
], ],
blocked: { blocked: {
@@ -97,34 +101,38 @@ const MyGroupSchema = new Schema({
req_users: [ req_users: [
{ {
_id: false, _id: false,
username: {type: String}, username: { type: String },
date: {type: Date}, date: { type: Date },
}], // username }], // username
refused_users: [ refused_users: [
{ {
_id: false, _id: false,
username: {type: String}, username: { type: String },
date: {type: Date}, date: { type: Date },
}], // username }], // username
deleted: { deleted: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
circuits_list: [ mycircuits: [
{ {
Num: { type: Number }, _id: false,
inscription_date: {type: Date}, circuitname: { type: String },
date: { type: Date },
}], }],
lastdate_reqRisGroup: {
type: Date,
},
}); });
MyGroupSchema.statics.getFieldsForSearch = function() { MyGroupSchema.statics.getFieldsForSearch = function () {
return [{field: 'descr', type: tools.FieldType.string}]; return [{ field: 'descr', type: tools.FieldType.string }];
}; };
MyGroupSchema.statics.executeQueryTable = function(idapp, params, user) { MyGroupSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch(); params.fieldsearch = this.getFieldsForSearch();
const {User} = require('./user'); const { User } = require('./user');
if (params.options) { if (params.options) {
if (tools.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_USER_ONLY_FULL_WORDS)) { if (tools.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_USER_ONLY_FULL_WORDS)) {
@@ -137,90 +145,94 @@ MyGroupSchema.statics.executeQueryTable = function(idapp, params, user) {
return tools.executeQueryTable(this, idapp, params, user); return tools.executeQueryTable(this, idapp, params, user);
}; };
MyGroupSchema.pre('save', async function(next) { MyGroupSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
const myrec = await MyGroup.findOne().limit(1).sort({_id: -1}); if (!this.date_created)
if (!!myrec) { this.date_created = new Date();
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date();
} }
next(); next();
}); });
MyGroupSchema.statics.findAllIdApp = async function(idapp) { MyGroupSchema.statics.findAllIdApp = async function (idapp) {
const myfind = {idapp}; const myfind = { idapp };
return await MyGroup.find(myfind); return await MyGroup.find(myfind);
}; };
MyGroupSchema.statics.findAllGroups = async function(idapp) { MyGroupSchema.statics.findAllGroups = async function (idapp) {
const whatToShow = this.getWhatToShow(idapp, ''); const whatToShow = this.getWhatToShow(idapp, '');
return await MyGroup.find({ return await MyGroup.find({
idapp, idapp,
$or: [ $or: [
{deleted: {$exists: false}}, { deleted: { $exists: false } },
{deleted: {$exists: true, $eq: false}}], { deleted: { $exists: true, $eq: false } }],
}, whatToShow); }, whatToShow);
}; };
// Rimuovo la Richiesta del Gruppo // Rimuovo la Richiesta del Gruppo
MyGroupSchema.statics.removeReqGroup = async function(idapp, username, groupnameDest) { MyGroupSchema.statics.removeReqGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne({idapp, groupname: groupnameDest}, return await MyGroup.updateOne({ idapp, groupname: groupnameDest },
{$pull: {req_users: {username: {$in: [username]}}}}); { $pull: { req_users: { username: { $in: [username] } } } });
}; };
// Aggiungi agli utenti Rifiutati del Gruppo // Aggiungi agli utenti Rifiutati del Gruppo
MyGroupSchema.statics.refuseReqGroup = async function(idapp, username, groupnameDest) { MyGroupSchema.statics.refuseReqGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne({idapp, groupname: groupnameDest}, return await MyGroup.updateOne({ idapp, groupname: groupnameDest },
{
$push:
{ {
$push: refused_users: {
{ username,
refused_users: { date: new Date(),
username, },
date: new Date(), },
}, });
},
});
}; };
// Aggiungi agli Admin del Gruppo // Aggiungi agli Admin del Gruppo
MyGroupSchema.statics.addToAdminOfMyGroup = async function(idapp, username, groupnameDest) { MyGroupSchema.statics.addToAdminOfMyGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne({idapp, groupname: groupnameDest}, return await MyGroup.updateOne({ idapp, groupname: groupnameDest },
{
$push:
{ {
$push: admins: {
{ username,
admins: { date: new Date(),
username, },
date: new Date(), },
}, });
},
});
}; };
// Rimuovi dagli Admin del Gruppo // Rimuovi dagli Admin del Gruppo
MyGroupSchema.statics.removeAdminOfMyGroup = async function(idapp, username, groupnameDest) { MyGroupSchema.statics.removeAdminOfMyGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne({idapp, groupname: groupnameDest}, return await MyGroup.updateOne({ idapp, groupname: groupnameDest },
{$pull: {admins: {username: {$in: [username]}}}}); { $pull: { admins: { username: { $in: [username] } } } });
}; };
MyGroupSchema.statics.getWhatToShow = function(idapp, username) { MyGroupSchema.statics.getListAdminsByGroupName = async function (idapp, groupname) {
let arr = await MyGroup.findOne({
idapp,
groupname,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
}, { admins: 1 }).lean();
return arr && arr.admins ? arr.admins : [];
};
MyGroupSchema.statics.getWhatToShow = function (idapp, username) {
// FOR ME, PERMIT ALL // FOR ME, PERMIT ALL
return { return {
groupname: 1, groupname: 1,
@@ -242,12 +254,13 @@ MyGroupSchema.statics.getWhatToShow = function(idapp, username) {
createdBy: 1, createdBy: 1,
date_created: 1, date_created: 1,
date_updated: 1, date_updated: 1,
circuits_list: 1, mycircuits: 1,
lastdate_reqRisGroup: 1,
}; };
}; };
MyGroupSchema.statics.getWhatToShow_Unknown = function(idapp, username) { MyGroupSchema.statics.getWhatToShow_Unknown = function (idapp, username) {
return { return {
groupname: 1, groupname: 1,
title: 1, title: 1,
@@ -259,14 +272,15 @@ MyGroupSchema.statics.getWhatToShow_Unknown = function(idapp, username) {
note: 1, note: 1,
date_created: 1, date_created: 1,
date_updated: 1, date_updated: 1,
circuits_list: 1, mycircuits: 1,
lastdate_reqRisGroup: 1,
}; };
}; };
MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function( MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function (
idapp, groupname, field) { idapp, groupname, field) {
const {User} = require('../models/user'); const { User } = require('../models/user');
const myobj = {}; const myobj = {};
myobj[field + '.' + subfield] = 1; myobj[field + '.' + subfield] = 1;
@@ -274,7 +288,7 @@ MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function(
let arrrec = await User.findOne({ let arrrec = 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).then((ris) => ris ? ris._doc[field] : []);
if (arrrec.length > 0) { if (arrrec.length > 0) {
@@ -284,7 +298,7 @@ MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function(
}; };
MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname) { MyGroupSchema.statics.getInfoGroupByGroupname = async function (idapp, groupname) {
const whatToShow = this.getWhatToShow(idapp, groupname); const whatToShow = this.getWhatToShow(idapp, groupname);
@@ -294,13 +308,13 @@ MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname)
}; };
const query = [ const query = [
{$match: myfind}, { $match: myfind },
{ $unwind: '$circuits_list' }, { $unwind: '$mycircuits' },
{ {
$lookup: { $lookup: {
from: 'circuits', from: 'circuits',
localField: 'circuits_list.Num', localField: 'mycircuits.circuitname',
foreignField: 'Num', foreignField: 'name',
as: 'mycircuits', as: 'mycircuits',
}, },
}, },
@@ -319,7 +333,7 @@ MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname)
}, },
}, },
}, },
{$project: whatToShow}, { $project: whatToShow },
]; ];
@@ -336,15 +350,15 @@ MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname)
}; };
MyGroupSchema.statics.deleteGroup = async function(idapp, usernameOrig, groupname) { MyGroupSchema.statics.deleteGroup = async function (idapp, usernameOrig, groupname) {
console.log('Gruppo ' + groupname + ' rimosso da ' + usernameOrig); console.log('Gruppo ' + groupname + ' rimosso da ' + usernameOrig);
return await MyGroup.findOneAndRemove({idapp, groupname}); return await MyGroup.findOneAndRemove({ idapp, groupname });
}; };
MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req) { MyGroupSchema.statics.getGroupsByUsername = async function (idapp, username, req) {
try { try {
const {User} = require('../models/user'); const { User } = require('../models/user');
const whatToShow = this.getWhatToShow(idapp, username); const whatToShow = this.getWhatToShow(idapp, username);
const whatToShow_Unknown = this.getWhatToShow_Unknown(idapp, username); const whatToShow_Unknown = this.getWhatToShow_Unknown(idapp, username);
@@ -353,17 +367,17 @@ MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req)
let listUsersGroup = await User.find({ let listUsersGroup = await User.find({
idapp, idapp,
username: {$in: arrUsernameGroups}, username: { $in: arrUsernameGroups },
$or: [ $or: [
{deleted: {$exists: false}}, { deleted: { $exists: false } },
{deleted: {$exists: true, $eq: false}}], { deleted: { $exists: true, $eq: false } }],
}, whatToShow); }, whatToShow);
let listgroups = await MyGroup.find({ let listgroups = await MyGroup.find({
idapp, idapp,
$or: [ $or: [
{deleted: {$exists: false}}, { deleted: { $exists: false } },
{deleted: {$exists: true, $eq: false}}], { deleted: { $exists: true, $eq: false } }],
}, whatToShow_Unknown); }, whatToShow_Unknown);
/*let listRequestUsersGroup = await User.find({ /*let listRequestUsersGroup = await User.find({
@@ -379,21 +393,21 @@ MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req)
let listSentRequestGroups = await MyGroup.find({ let listSentRequestGroups = await MyGroup.find({
idapp, idapp,
'req_users': { 'req_users': {
$elemMatch: {username: {$eq: username}}, $elemMatch: { username: { $eq: username } },
}, },
$or: [ $or: [
{deleted: {$exists: false}}, { deleted: { $exists: false } },
{deleted: {$exists: true, $eq: false}}], { deleted: { $exists: true, $eq: false } }],
}, whatToShow_Unknown); }, whatToShow_Unknown);
let listRefusedGroups = await MyGroup.find({ let listRefusedGroups = await MyGroup.find({
idapp, idapp,
'refused_users': { 'refused_users': {
$elemMatch: {username: {$eq: username}}, $elemMatch: { username: { $eq: username } },
}, },
$or: [ $or: [
{deleted: {$exists: false}}, { deleted: { $exists: false } },
{deleted: {$exists: true, $eq: false}}], { deleted: { $exists: true, $eq: false } }],
}, whatToShow_Unknown); }, whatToShow_Unknown);
return { return {
@@ -418,12 +432,12 @@ MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req)
}; };
}; };
MyGroupSchema.statics.extractCitiesName = async function(idapp, id) { MyGroupSchema.statics.extractCitiesName = async function (idapp, id) {
try { try {
let aggr1 = [ let aggr1 = [
{ {
$match: {idapp, _id: id}, $match: { idapp, _id: id },
}, },
{ {
$lookup: { $lookup: {
@@ -459,13 +473,157 @@ MyGroupSchema.statics.extractCitiesName = async function(idapp, id) {
ris = await this.aggregate(aggr1); ris = await this.aggregate(aggr1);
return ris; return ris;
}catch (e) { } catch (e) {
console.error('e', e); console.error('e', e);
} }
}; };
MyGroupSchema.statics.ifCircuitAlreadyInGroup = async function (idapp, groupname, circuitname) {
// Controllo se è stato già inserito il circuito sul gruppo
return await this.findOne({
idapp,
groupname,
'mycircuits': {
$elemMatch: { circuitname: { $eq: circuitname } },
},
}).lean();
};
// aggiungo il Circuito all'interno del Gruppo
MyGroupSchema.statics.addCircuitFromGroup = async function (idapp, groupname, circuitname) {
return await this.updateOne({ idapp, groupname },
{
$push: {
'mycircuits': {
circuitname,
date: new Date(),
}
}
});
};
// Rimuovo il Circuito all'interno del Gruppo
MyGroupSchema.statics.removeCircuitFromGroup = async function (idapp, groupname, circuitname) {
return await this.updateOne({ idapp, groupname },
{ $pull: { 'mycircuits': { circuitname: { $in: [circuitname] } } } });
};
MyGroupSchema.statics.getQueryReceiveRISGroups = function (idapp, hours) {
const query = [
{
$match: {
idapp,
'lastdate_reqRisGroup': { $gte: tools.IncDateNow(-(1000 * 60 * 60 * hours)) },
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
},
},
{
$group:
{
_id: "$groupname",
count: {
$sum: 1,
},
}
},
{ $sort: { 'lastdate_reqRisGroup': -1 } },
{ $limit: 30 },
{
$lookup: {
from: "mygroups",
let: {
groupname: "$_id",
idapp,
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$$groupname",
"$groupname",
],
},
{
$eq: [
"$$idapp",
"$idapp",
],
},
],
},
},
},
],
as: "mygroup",
},
},
{ $unwind: "$mygroup" },
{
$replaceRoot: {
newRoot: {
$mergeObjects: ["$mygroup", "$$ROOT"],
},
},
},
{
$project: {
_id: 0,
groupname: 1,
title: 1,
descr: 1,
visibility: 1,
idCatGrp: 1,
userId: 1,
photos: 1,
idCity: 1,
website: 1,
link_telegram: 1,
note: 1,
admins: 1,
blocked: 1,
req_users: 1,
createdBy: 1,
date_created: 1,
date_updated: 1,
lastdate_reqRisGroup: 1,
},
},
];
return query;
};
MyGroupSchema.statics.getReceiveRISGroups = async function (idapp) {
return await this.aggregate(this.getQueryReceiveRISGroups(idapp, 8)).then(ris => {
return ris;
});
};
MyGroupSchema.statics.setReceiveRisGroup = async function (idapp, groupname) {
return await this.findOneAndUpdate({
idapp, groupname,
},
{ $set: { 'lastdate_reqRisGroup': new Date() } }, { new: false }).lean().then((record) => {
return !!record;
});
};
const MyGroup = mongoose.model('MyGroup', MyGroupSchema); const MyGroup = mongoose.model('MyGroup', MyGroupSchema);
module.exports = {MyGroup}; module.exports = { MyGroup };

View File

@@ -6,7 +6,10 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const {ObjectID} = require('mongodb'); const { Reaction } = require('./reaction');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => { mongoose.plugin(schema => {
@@ -14,109 +17,101 @@ mongoose.plugin(schema => {
}); });
const MyHospSchema = new Schema({ const MyHospSchema = new Schema({
_id: { ...{
type: Number, _id: {
},
idapp: {
type: String,
required: true,
},
userId: {type: Schema.Types.ObjectId, ref: 'User'},
visibile: {
type: Boolean
},
typeHosp: { // scambio casa / ospitalità
type: Number,
},
numMaxPeopleHosp: {
type: Number,
},
accomodation: [
{
type: { // Letto matrimoniale / letto singolo / divano-letto / almaca / a terra sul tappeto (per sacco a pelo) / culla
type: Number,
},
location: { // in camera privata / in camera condivisa / in soggiorno / in camper / in tenda / in giardino / all'aperto
type: Number,
},
num: {
type: Number,
},
}],
preferences: [ // Accetto bambini, Accetto cani, Accetto gatti, E' consentito fumare in casa, Accessibile con sedia a rotelle
{
type: Number,
}],
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
idContribType: [
{
type: String, type: String,
}], },
idCity: [ idapp: {
{ type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
visibile: {
type: Boolean
},
typeHosp: { // scambio casa / ospitalità
type: Number, type: Number,
}], },
pub_to_share: { numMaxPeopleHosp: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW type: Number,
}, },
descr: { accomodation: [
type: String, {
}, type: { // Letto matrimoniale / letto singolo / divano-letto / almaca / a terra sul tappeto (per sacco a pelo) / culla
note: { type: Number,
type: String, },
default: '', location: { // in camera privata / in camera condivisa / in soggiorno / in camper / in tenda / in giardino / all'aperto
}, type: Number,
website: { },
type: String, num: {
}, type: Number,
link_maplocation: { },
type: String, }],
}, preferences: [ // Accetto bambini, Accetto cani, Accetto gatti, E' consentito fumare in casa, Accessibile con sedia a rotelle
date_created: { {
type: Date, type: Number,
default: Date.now, }],
}, photos: [
date_updated: { {
type: Date, imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
idContribType: [
{
type: String,
}],
idCity: [
{
type: Number,
}],
pub_to_share: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
},
descr: {
type: String,
},
note: {
type: String,
default: '',
},
website: {
type: String,
},
link_maplocation: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
}, },
...Reaction.getFieldsForReactions()
}); });
MyHospSchema.pre('save', async function(next) { MyHospSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
const myrec = await MyHosp.findOne().limit(1).sort({_id: -1}); if (!this.date_created)
if (!!myrec) { this.date_created = new Date();
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date();
} }
next(); next();
}); });
MyHospSchema.statics.findAllIdApp = async function(idapp) { MyHospSchema.statics.findAllIdApp = async function (idapp) {
const MyHosp = this; const MyHosp = this;
const query = [ const query = [
{$match: {idapp}}, { $match: { idapp } },
{$sort: {descr: 1}}, { $sort: { descr: 1 } },
]; ];
return await MyHosp.aggregate(query).then((arrrec) => { return await MyHosp.aggregate(query).then((arrrec) => {
@@ -125,18 +120,18 @@ MyHospSchema.statics.findAllIdApp = async function(idapp) {
}; };
MyHospSchema.statics.getFieldsForSearch = function() { MyHospSchema.statics.getFieldsForSearch = function () {
return []; return [];
}; };
MyHospSchema.statics.getFieldsLastForSearch = function() { MyHospSchema.statics.getFieldsLastForSearch = function () {
return [ return [
{field: 'descr', type: tools.FieldType.string}, { field: 'descr', type: tools.FieldType.string },
{field: 'note', type: tools.FieldType.string}, { field: 'note', type: tools.FieldType.string },
]; ];
}; };
MyHospSchema.statics.executeQueryTable = function(idapp, params, user) { MyHospSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch(); params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch(); params.fieldsearch_last = this.getFieldsLastForSearch();
@@ -147,59 +142,24 @@ MyHospSchema.statics.executeQueryTable = function(idapp, params, user) {
lk_FF: '_id', lk_FF: '_id',
lk_as: 'user', lk_as: 'user',
af_objId_tab: 'myId', af_objId_tab: 'myId',
lk_proj: { lk_proj: this.getProject(),
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
note: 1,
website: 1,
link_maplocation: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
'mycities': 1,
reported: 1,
},
}, },
}; };
params = {...params, ...otherparams}; params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user); return tools.executeQueryTable(this, idapp, params, user);
}; };
MyHospSchema.statics.getMyRecById = function(idapp, id) { MyHospSchema.statics.getMyRecById = function (idapp, id) {
const MyHosp = this; const MyHosp = this;
const query = [ const myparsid = { '_id': id, idapp };
let query = [
{ {
'$match': { '$match':
'$and': [ myparsid,
{
'_id': parseInt(id),
},
],
},
},
{
'$match': {
'idapp': idapp,
},
}, },
{ {
'$sort': { '$sort': {
@@ -237,34 +197,7 @@ MyHospSchema.statics.getMyRecById = function(idapp, id) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
note: 1,
website: 1,
link_maplocation: 1,
descr: 1,
date_created: 1,
date_updated: 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -290,34 +223,7 @@ MyHospSchema.statics.getMyRecById = function(idapp, id) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
note: 1,
website: 1,
link_maplocation: 1,
descr: 1,
date_created: 1,
date_updated: 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -343,34 +249,7 @@ MyHospSchema.statics.getMyRecById = function(idapp, id) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
note: 1,
website: 1,
link_maplocation: 1,
descr: 1,
date_created: 1,
date_updated: 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
/*{ /*{
'$lookup': { '$lookup': {
@@ -396,34 +275,7 @@ MyHospSchema.statics.getMyRecById = function(idapp, id) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
note: 1,
website: 1,
link_maplocation: 1,
descr: 1,
date_created: 1,
date_updated: 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -448,50 +300,52 @@ MyHospSchema.statics.getMyRecById = function(idapp, id) {
}, },
}, },
}, },
{
'$project': {
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
note: 1,
website: 1,
link_maplocation: 1,
descr: 1,
date_created: 1,
date_updated: 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
},
]; ];
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYHOSPS);
const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: this.getProject(objadd.proj),
};
query = [...query, { ...toadd }];
return MyHosp.aggregate(query).then((rec) => { return MyHosp.aggregate(query).then((rec) => {
return rec ? rec[0] : null; return rec ? rec[0] : null;
}); });
}; };
MyHospSchema.statics.getCompleteRecord = function(idapp, id) { MyHospSchema.statics.getCompleteRecord = function (idapp, id) {
const MyHosp = this; const MyHosp = this;
return MyHosp.getMyRecById(idapp, id); return MyHosp.getMyRecById(idapp, id);
}; };
MyHospSchema.statics.getProject = function () {
let proj = {
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
website: 1,
link_maplocation: 1,
//**ADDFIELD_MYHOSP
};
const proj_add = shared_consts.getProjectForAll()
return Object.assign({}, proj, proj_add);
}
const MyHosp = mongoose.model('MyHosp', MyHospSchema); const MyHosp = mongoose.model('MyHosp', MyHospSchema);
module.exports = {MyHosp}; module.exports = { MyHosp };

View File

@@ -135,6 +135,7 @@ const MyPageSchema = new Schema({
MyPageSchema.statics.getFieldsForSearch = function () { MyPageSchema.statics.getFieldsForSearch = function () {
return [{ field: 'title', type: tools.FieldType.string }, return [{ field: 'title', type: tools.FieldType.string },
{ field: 'path', type: tools.FieldType.string },
{ field: 'keywords', type: tools.FieldType.string }, { field: 'keywords', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string }, { field: 'description', type: tools.FieldType.string },
{ field: 'content', type: tools.FieldType.string }] { field: 'content', type: tools.FieldType.string }]

View File

@@ -6,115 +6,118 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const {ObjectID} = require('mongodb'); const { Reaction } = require('./reaction');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => { mongoose.plugin(schema => {
schema.options.usePushEach = true; schema.options.usePushEach = true;
}); });
const MySkillSchema = new Schema({ const MySkillSchema = new Schema(
_id: { {
type: Number, ...{
}, _id: {
idapp: { type: String,
type: String, default: function () {
required: true, return new ObjectID().toString();
}, },
userId: {type: Schema.Types.ObjectId, ref: 'User'}, },
idSector: { idapp: {
type: Number, type: String,
}, required: true,
idSkill: { },
type: Number, userId: { type: Schema.Types.ObjectId, ref: 'User' },
default: 0, idSector: {
}, type: Number,
/*idSubSkill: [ },
{ idSkill: {
type: Number, type: Number,
default: 0, default: 0,
}], },
/*idSubSkill: [
{
type: Number,
default: 0,
}],
*/ */
idStatusSkill: [ idStatusSkill: [
{ {
type: Number, type: Number,
}], }],
idContribType: [ idContribType: [
{ {
type: String, type: String,
}], }],
idCity: [ idCity: [
{ {
type: Number, type: Number,
}], }],
pub_to_share: { pub_to_share: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
}, },
numLevel: { numLevel: {
type: Number, type: Number,
default: 0, default: 0,
}, },
adType: { adType: {
type: Number, type: Number,
}, },
photos: [ photos: [
{ {
imagefile: { imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
note: {
type: String,
default: '',
},
descr: {
type: String, type: String,
}, },
alt: { //**ADDFIELD_MYSKILL
website: {
type: String, type: String,
}, },
description: { date_created: {
type: String, type: Date,
}, },
}], date_updated: {
note: { type: Date,
type: String, },
default: '', },
}, ...Reaction.getFieldsForReactions()
descr: { }, { strict: false });
type: String,
},
//**ADDFIELD_MYSKILL
website: {
type: String,
},
date_created: {
type: Date,
default: Date.now,
},
date_updated: {
type: Date,
},
});
MySkillSchema.pre('save', async function(next) { MySkillSchema.index({ 'idapp': 1 });
MySkillSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
const myrec = await MySkill.findOne().limit(1).sort({_id: -1}); if (!this.date_created)
if (!!myrec) { this.date_created = new Date();
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date();
} }
next(); next();
}); });
MySkillSchema.statics.findAllIdApp = async function(idapp) { MySkillSchema.statics.findAllIdApp = async function (idapp) {
const MySkill = this; const MySkill = this;
const query = [ const query = [
{$match: {idapp}}, { $match: { idapp } },
{$sort: {descr: 1}}, { $sort: { descr: 1 } },
]; ];
return await MySkill.aggregate(query).then((arrrec) => { return await MySkill.aggregate(query).then((arrrec) => {
@@ -123,20 +126,20 @@ MySkillSchema.statics.findAllIdApp = async function(idapp) {
}; };
MySkillSchema.statics.getFieldsForSearch = function() { MySkillSchema.statics.getFieldsForSearch = function () {
return []; return [];
}; };
MySkillSchema.statics.getFieldsLastForSearch = function() { MySkillSchema.statics.getFieldsLastForSearch = function () {
return [ return [
{field: 'note', type: tools.FieldType.string}, { field: 'note', type: tools.FieldType.string },
{field: 'descr', type: tools.FieldType.string}, { field: 'descr', type: tools.FieldType.string },
{field: 'recSkill.descr', type: tools.FieldType.string}, { field: 'recSkill.descr', type: tools.FieldType.string },
{field: 'myskill.descr', type: tools.FieldType.string}, { field: 'myskill.descr', type: tools.FieldType.string },
]; ];
}; };
MySkillSchema.statics.executeQueryTable = function(idapp, params, user) { MySkillSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch(); params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch(); params.fieldsearch_last = this.getFieldsLastForSearch();
@@ -147,58 +150,22 @@ MySkillSchema.statics.executeQueryTable = function(idapp, params, user) {
lk_FF: '_id', lk_FF: '_id',
lk_as: 'user', lk_as: 'user',
af_objId_tab: 'myId', af_objId_tab: 'myId',
lk_proj: { lk_proj: this.getProject(),
idSkill: 1,
// idSubSkill: 1,
myskill: 1,
idStatusSkill: 1,
idContribType: 1,
idCity: 1,
pub_to_share: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
//**ADDFIELD_MYSKILL
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
}; };
params = {...params, ...otherparams}; params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user); return tools.executeQueryTable(this, idapp, params, user);
}; };
MySkillSchema.statics.getMyRecById = function(idapp, idSkill) { MySkillSchema.statics.getMyRecById = function (idapp, idSkill) {
const MySkill = this; const MySkill = this;
const query = [ let query = [
{ {
'$match': { '$match': {
'$and': [ '_id': idSkill, idapp
{
'_id': parseInt(idSkill),
},
],
},
},
{
'$match': {
'idapp': idapp,
}, },
}, },
{ {
@@ -237,37 +204,7 @@ MySkillSchema.statics.getMyRecById = function(idapp, idSkill) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
// 'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
note: 1,
website: 1,
//**ADDFIELD_MYSKILL
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -293,37 +230,7 @@ MySkillSchema.statics.getMyRecById = function(idapp, idSkill) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
// 'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYSKILL
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -349,37 +256,7 @@ MySkillSchema.statics.getMyRecById = function(idapp, idSkill) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
//'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYSKILL
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
/*{ /*{
'$lookup': { '$lookup': {
@@ -407,37 +284,7 @@ MySkillSchema.statics.getMyRecById = function(idapp, idSkill) {
}, },
}, },
{ {
'$project': { $project: this.getProject(),
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
// 'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYSKILL
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
}, },
{ {
'$lookup': { '$lookup': {
@@ -462,47 +309,43 @@ MySkillSchema.statics.getMyRecById = function(idapp, idSkill) {
}, },
}, },
}, },
{
'$project': {
'recSkill': 1,
'sector': 1,
'idSector': 1,
'idSkill': 1,
// 'idSubSkill': 1,
'idStatusSkill': 1,
'idContribType': 1,
'idCity': 1,
pub_to_share: 1,
'numLevel': 1,
adType: 1,
'photos': 1,
'note': 1,
website: 1,
//**ADDFIELD_MYSKILL
'descr': 1,
'date_created': 1,
'date_updated': 1,
'userId': 1,
'username': 1,
'name': 1,
'surname': 1,
'comune': 1,
'mycities': 1,
'profile.img': 1,
"profile.mygroups": 1,
"profile.mycircuits": 1,
'profile.qualifica': 1,
reported: 1,
},
},
]; ];
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYSKILLS);
const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: this.getProject(objadd.proj),
};
query = [...query, { ...toadd }];
return MySkill.aggregate(query).then((rec) => { return MySkill.aggregate(query).then((rec) => {
return rec ? rec[0] : null; return rec ? rec[0] : null;
}); });
}; };
MySkillSchema.statics.getCompleteRecord = function(idapp, id) { MySkillSchema.statics.getProject = function (proj_add2) {
let proj = {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
idStatusSkill: 1,
website: 1,
'numLevel': 1,
//**ADDFIELD_MYSKILL
};
const proj_add = shared_consts.getProjectForAll(proj_add2)
return Object.assign({}, proj, proj_add);
}
MySkillSchema.statics.getCompleteRecord = function (idapp, id) {
const MySkill = this; const MySkill = this;
return MySkill.getMyRecById(idapp, id); return MySkill.getMyRecById(idapp, id);
@@ -511,4 +354,4 @@ MySkillSchema.statics.getCompleteRecord = function(idapp, id) {
const MySkill = mongoose.model('MySkill', MySkillSchema); const MySkill = mongoose.model('MySkill', MySkillSchema);
module.exports = {MySkill}; module.exports = { MySkill };

View File

@@ -20,12 +20,12 @@ const PermissionSchema = new Schema({
type: String, type: String,
default: '' default: ''
} }
},{ _id : false }); }, { _id: false });
PermissionSchema.pre('save', async function (next) { PermissionSchema.pre('save', async function (next) {
if (this.isNew) { if (this.isNew) {
const myrec = await Permission.findOne().limit(1).sort({_id:-1}); const myrec = await Permission.findOne().limit(1).sort({ _id: -1 });
if (!!myrec) { if (!!myrec) {
if (myrec._doc._id === 0) if (myrec._doc._id === 0)
this._id = 1; this._id = 1;
@@ -48,7 +48,7 @@ PermissionSchema.statics.executeQueryTable = function (idapp, params) {
PermissionSchema.statics.findAllIdApp = async function () { PermissionSchema.statics.findAllIdApp = async function () {
const Permission = this; const Permission = this;
const myfind = { }; const myfind = {};
return await Permission.find(myfind, (err, arrrec) => { return await Permission.find(myfind, (err, arrrec) => {
return arrrec return arrrec

View File

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

View File

@@ -35,8 +35,32 @@ const ProvinceSchema = new Schema({
link_grp: { link_grp: {
type: String, type: String,
}, },
card : {
type: String,
},
link_telegram: {
type: String,
},
}, { _id : false }); }, { _id : false });
ProvinceSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Province.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
}
next();
});
ProvinceSchema.statics.getRegionByStrProvince = async function(strprovince) { ProvinceSchema.statics.getRegionByStrProvince = async function(strprovince) {
const myrec = await Province.findOne({prov: strprovince}).lean(); const myrec = await Province.findOne({prov: strprovince}).lean();
if (myrec) { if (myrec) {
@@ -46,7 +70,14 @@ ProvinceSchema.statics.getRegionByStrProvince = async function(strprovince) {
return ''; return '';
} }
ProvinceSchema.statics.getStrProvinceByProv = async function(prov) {
const myrec = await Province.findOne({prov}).lean();
if (myrec) {
return myrec.descr;
}
return '';
}
ProvinceSchema.statics.getFieldsForSearch = function() { ProvinceSchema.statics.getFieldsForSearch = function() {
return [ return [
@@ -91,7 +122,7 @@ ProvinceSchema.statics.executeQueryPickup = async function(idapp, params) {
ProvinceSchema.statics.findAllIdApp = async function(idapp) { ProvinceSchema.statics.findAllIdApp = async function(idapp) {
const myfind = {}; const myfind = {};
return Province.find(myfind).sort({reg: 1, prov: 1}); return Province.find(myfind).sort({descr: 1});
}; };
const Province = mongoose.model('Province', ProvinceSchema); const Province = mongoose.model('Province', ProvinceSchema);

436
src/server/models/reaction.js Executable file
View File

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

45
src/server/models/search.js Executable file
View File

@@ -0,0 +1,45 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const searchSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
text: {
type: String,
},
});
searchSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) {
const Search = this;
let myfind = {};
if (sall === '1')
myfind = { idapp };
else
myfind = { userId, idapp };
return Search.find(myfind, (err, arrsearch) => {
return arrsearch
});
};
const Search = mongoose.model('Search', searchSchema);
module.exports = { Search };

View File

@@ -17,14 +17,14 @@ const sendmsgSchema = new Schema({
}, },
source: { source: {
page: { type: String }, page: { type: String },
event_id: { type: String } event_id: { type: String },
infoevent: { type: String }
}, },
origin: { origin: {
username: { type: String }, type: String,
}, },
dest: { dest: {
idapp: { type: String, }, type: String,
username: { type: String },
}, },
message: { message: {
type: String, type: String,
@@ -54,7 +54,7 @@ sendmsgSchema.statics.findAllMsgByUsernameIdAndIdApp = function (username, lastd
return SendMsg.find({ return SendMsg.find({
$and: [ $and: [
{ $or: [ { 'dest.username': username }, { 'origin.username': username },] }, { $or: [ { 'dest': username }, { 'origin': username },] },
{ 'datemsg': {$gt: new Date(lastdataread)} }, { 'datemsg': {$gt: new Date(lastdataread)} },
{ idapp } { idapp }
] ]
@@ -73,14 +73,14 @@ sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username
return SendMsg.aggregate([ return SendMsg.aggregate([
{ {
$match: { $match: {
$or: [{ 'origin.username': username }, { 'dest.username': username }, { idapp }], $or: [{ 'origin': username }, { 'dest': username }, { idapp }],
$and: [{ idapp }] $and: [{ idapp }]
} }
}, },
{ {
$group: $group:
{ {
_id: "$dest.username", _id: "$dest",
message: { $last: "$message" }, message: { $last: "$message" },
datemsg: { $last: "$datemsg" }, datemsg: { $last: "$datemsg" },
dest: { $last: "$dest" }, dest: { $last: "$dest" },

File diff suppressed because it is too large Load Diff

View File

@@ -62,6 +62,12 @@ const SiteSchema = new Schema({
telegram_key_test: { telegram_key_test: {
type: String, type: String,
}, },
teleg_cfg: {
type: String,
},
teleg_cfg_test: {
type: String,
},
telegram_bot_name_test: { telegram_bot_name_test: {
type: String, type: String,
}, },
@@ -122,6 +128,7 @@ const SiteSchema = new Schema({
enableRegMultiChoice: { type: Boolean }, enableRegMultiChoice: { type: Boolean },
enableDebugOn: { type: Boolean }, enableDebugOn: { type: Boolean },
enabledRegNeedTelegram: { type: Boolean }, enabledRegNeedTelegram: { type: Boolean },
showViewEventi: { type: Boolean },
showViewGroups: { type: Boolean }, showViewGroups: { type: Boolean },
showViewCircuits: { type: Boolean }, showViewCircuits: { type: Boolean },
showViewUsers: { type: Boolean }, showViewUsers: { type: Boolean },
@@ -132,6 +139,8 @@ const SiteSchema = new Schema({
type: Number, type: Number,
default: 0, default: 0,
}, },
videoPromo: { type: String },
PDFPromo: { type: String },
}, },
confsite: { confsite: {
options: { // ConfSite options: { // ConfSite
@@ -223,6 +232,7 @@ module.exports.findAllIdApp = async function (idapp) {
rec.email_pwd = ''; rec.email_pwd = '';
rec.telegram_key = ''; rec.telegram_key = '';
rec.telegram_key_test = ''; rec.telegram_key_test = '';
// rec.confsite = {};
return rec; return rec;
} }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,98 @@
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 UserRequestSchema = new Schema({
_id: {
type: Number,
},
idapp: {
type: String,
},
typeReq: {
type: Number,
},
valueRequested: {
type: Number,
},
strRequested: {
type: String,
},
username: {
type: String,
},
groupname: {
type: String,
},
note: {
type: String,
},
createdBy: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
deleted: {
type: Boolean,
default: false,
},
processed: {
type: Boolean,
default: false,
},
username_answered: {
type: String,
},
state_requested: {
type: Number,
},
msgout_answered: {
type: String,
},
});
UserRequestSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }];
};
UserRequestSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
const { User } = require('./user');
return tools.executeQueryTable(this, idapp, params, user);
};
UserRequestSchema.pre('save', async function (next) {
if (this.isNew) {
this.date_created = new Date();
}
next();
});
UserRequestSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await UserRequest.find(myfind);
};
const UserRequest = mongoose.model('UserRequest', UserRequestSchema);
module.exports = { UserRequest };

View File

@@ -89298,5 +89298,16 @@ module.exports = {
abitanti: '', abitanti: '',
country: 'ONL', country: 'ONL',
}, },
{
_id: 8120,
istat: '',
comune: 'Italia',
prov: 'ITA',
reg: 'ITA',
pref: '',
cap: '',
abitanti: '',
country: 'ITA',
},
], ],
}; };

View File

@@ -62,5 +62,13 @@ module.exports = {
{_id: 60, idSectorGood: [17], descr: 'Per Imbiancare'}, {_id: 60, idSectorGood: [17], descr: 'Per Imbiancare'},
{_id: 61, idSectorGood: [17], descr: 'Giardinaggio'}, {_id: 61, idSectorGood: [17], descr: 'Giardinaggio'},
{_id: 62, idSectorGood: [17], descr: 'Falegnameria'}, {_id: 62, idSectorGood: [17], descr: 'Falegnameria'},
{_id: 63, idSectorGood: [7], descr: 'Pane'},
{_id: 64, idSectorGood: [7], descr: 'Pasta'},
{_id: 65, idSectorGood: [7], descr: 'Formaggi'},
{_id: 66, idSectorGood: [7], descr: 'Olio'},
{_id: 67, idSectorGood: [7], descr: 'Fervida'},
{_id: 68, idSectorGood: [7], descr: 'Fermentati'},
{_id: 69, idSectorGood: [7], descr: 'Marmellate'},
{_id: 70, idSectorGood: [7], descr: 'Salse'},
], ],
}; };

View File

@@ -1,124 +1,126 @@
module.exports = { module.exports = {
list: [ list: [
{_id: 1, reg: 'SIC', prov: 'AG', descr: 'Agrigento', link_grp: 'https://t.me/c/1614195634/562?thread=553'}, {_id: 1, reg: 'SIC', prov: 'AG', descr: 'Agrigento', link_grp: 'https://t.me/c/1614195634/562?thread=553', link_telegram: ''},
{_id: 2, reg: 'PIE', prov: 'AL', descr: 'Alessandria', link_grp: 'https://t.me/c/1614195634/513?thread=504'}, {_id: 2, reg: 'PIE', prov: 'AL', descr: 'Alessandria', link_grp: 'https://t.me/c/1614195634/513?thread=504', link_telegram: ''},
{_id: 3, reg: 'MAR', prov: 'AN', descr: 'Ancona', link_grp: 'https://t.me/c/1614195634/450?thread=446'}, {_id: 3, reg: 'MAR', prov: 'AN', descr: 'Ancona', link_grp: 'https://t.me/c/1614195634/450?thread=446', link_telegram: ''},
{_id: 4, reg: 'VDA', prov: 'AO', descr: 'Aosta', link_grp: 'https://t.me/c/1614195634/521?thread=520'}, {_id: 4, reg: 'VDA', prov: 'AO', descr: 'Aosta', link_grp: 'https://t.me/c/1614195634/521?thread=520', link_telegram: ''},
{_id: 5, reg: 'TOS', prov: 'AR', descr: 'Arezzo', link_grp: 'https://t.me/c/1614195634/583?thread=572'}, {_id: 5, reg: 'TOS', prov: 'AR', descr: 'Arezzo', link_grp: 'https://t.me/c/1614195634/583?thread=572', link_telegram: ''},
{_id: 6, reg: 'MAR', prov: 'AP', descr: 'Ascoli Piceno', link_grp: 'https://t.me/c/1614195634/451?thread=447'}, {_id: 6, reg: 'MAR', prov: 'AP', descr: 'Ascoli Piceno', link_grp: 'https://t.me/c/1614195634/451?thread=447', link_telegram: ''},
{_id: 7, reg: 'PIE', prov: 'AT', descr: 'Asti', link_grp: 'https://t.me/c/1614195634/514?thread=505'}, {_id: 7, reg: 'PIE', prov: 'AT', descr: 'Asti', link_grp: 'https://t.me/c/1614195634/514?thread=505', link_telegram: ''},
{_id: 8, reg: 'CAM', prov: 'AV', descr: 'Avellino', link_grp: 'https://t.me/c/1614195634/413?thread=409'}, {_id: 8, reg: 'CAM', prov: 'AV', descr: 'Avellino', link_grp: 'https://t.me/c/1614195634/413?thread=409', link_telegram: ''},
{_id: 9, reg: 'PUG', prov: 'BA', descr: 'Bari', link_grp: 'https://t.me/c/1614195634/534?thread=528'}, {_id: 9, reg: 'PUG', prov: 'BA', descr: 'Bari', link_grp: 'https://t.me/c/1614195634/534?thread=528', link_telegram: ''},
{_id: 10, reg: 'PUG', prov: 'BT', descr: 'Barletta-Andria-Trani', link_grp: 'https://t.me/c/1614195634/535?thread=529'}, {_id: 10, reg: 'PUG', prov: 'BT', descr: 'Barletta-Andria-Trani', link_grp: 'https://t.me/c/1614195634/535?thread=529', link_telegram: ''},
{_id: 11, reg: 'VEN', prov: 'BL', descr: 'Belluno', link_grp: 'https://t.me/c/1614195634/608?thread=599'}, {_id: 11, reg: 'VEN', prov: 'BL', descr: 'Belluno', link_grp: 'https://t.me/c/1614195634/608?thread=599', link_telegram: ''},
{_id: 12, reg: 'CAM', prov: 'BN', descr: 'Benevento', link_grp: 'https://t.me/c/1614195634/415?thread=411'}, {_id: 12, reg: 'CAM', prov: 'BN', descr: 'Benevento', link_grp: 'https://t.me/c/1614195634/415?thread=411', link_telegram: ''},
{_id: 13, reg: 'LOM', prov: 'BG', descr: 'Bergamo', link_grp: 'https://t.me/c/1614195634/491?thread=477'}, {_id: 13, reg: 'LOM', prov: 'BG', descr: 'Bergamo', link_grp: 'https://t.me/c/1614195634/491?thread=477', link_telegram: ''},
{_id: 14, reg: 'PIE', prov: 'BI', descr: 'Biella', link_grp: 'https://t.me/c/1614195634/515?thread=506'}, {_id: 14, reg: 'PIE', prov: 'BI', descr: 'Biella', link_grp: 'https://t.me/c/1614195634/515?thread=506', link_telegram: ''},
{_id: 15, reg: 'EMR', prov: 'BO', descr: 'Bologna', link_grp: 'https://t.me/c/1614195634/428?thread=419'}, {_id: 15, reg: 'EMR', prov: 'BO', descr: 'Bologna', link_grp: 'https://t.me/c/1614195634/428?thread=419', link_telegram: ''},
{_id: 16, reg: 'TAA', prov: 'BZ', descr: 'Bolzano', link_grp: 'https://t.me/c/1614195634/596?thread=594'}, {_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'}, {_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'}, {_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'}, {_id: 19, reg: 'SAR', prov: 'CA', descr: 'Cagliari', link_grp: 'https://t.me/c/1614195634/546?thread=541', link_telegram: ''},
{_id: 20, reg: 'SIC', prov: 'CL', descr: 'Caltanissetta', link_grp: 'https://t.me/c/1614195634/563?thread=554'}, {_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'}, {_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: ''}, {_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'}, {_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'}, {_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'}, {_id: 25, reg: 'CAL', prov: 'CZ', descr: 'Catanzaro', link_grp: 'https://t.me/c/1614195634/378?thread=377', link_telegram: ''},
{_id: 26, reg: 'ABR', prov: 'CH', descr: 'Chieti', link_grp: 'https://t.me/c/1614195634/366?thread=365'}, {_id: 26, reg: 'ABR', prov: 'CH', descr: 'Chieti', link_grp: 'https://t.me/c/1614195634/366?thread=365', link_telegram: ''},
{_id: 27, reg: 'LOM', prov: 'CO', descr: 'Como', link_grp: 'https://t.me/c/1614195634/492?thread=479'}, {_id: 27, reg: 'LOM', prov: 'CO', descr: 'Como', link_grp: 'https://t.me/c/1614195634/492?thread=479', link_telegram: ''},
{_id: 28, reg: 'CAL', prov: 'CS', descr: 'Cosenza', link_grp: 'https://t.me/c/1614195634/381?thread=379'}, {_id: 28, reg: 'CAL', prov: 'CS', descr: 'Cosenza', link_grp: 'https://t.me/c/1614195634/381?thread=379', link_telegram: ''},
{_id: 29, reg: 'LOM', prov: 'CR', descr: 'Cremona', link_grp: 'https://t.me/c/1614195634/493?thread=480'}, {_id: 29, reg: 'LOM', prov: 'CR', descr: 'Cremona', link_grp: 'https://t.me/c/1614195634/493?thread=480', link_telegram: ''},
{_id: 30, reg: 'CAL', prov: 'KR', descr: 'Crotone', link_grp: 'https://t.me/c/1614195634/382?thread=380'}, {_id: 30, reg: 'CAL', prov: 'KR', descr: 'Crotone', link_grp: 'https://t.me/c/1614195634/382?thread=380', link_telegram: ''},
{_id: 31, reg: 'PIE', prov: 'CN', descr: 'Cuneo', link_grp: 'https://t.me/c/1614195634/516?thread=507'}, {_id: 31, reg: 'PIE', prov: 'CN', descr: 'Cuneo', link_grp: 'https://t.me/c/1614195634/516?thread=507', link_telegram: ''},
{_id: 32, reg: 'SIC', prov: 'EN', descr: 'Enna', link_grp: 'https://t.me/c/1614195634/565?thread=556'}, {_id: 32, reg: 'SIC', prov: 'EN', descr: 'Enna', link_grp: 'https://t.me/c/1614195634/565?thread=556', link_telegram: ''},
{_id: 33, reg: 'MAR', prov: 'FM', descr: 'Fermo', link_grp: 'https://t.me/c/1614195634/453?thread=448'}, {_id: 33, reg: 'MAR', prov: 'FM', descr: 'Fermo', link_grp: 'https://t.me/c/1614195634/453?thread=448', link_telegram: ''},
{_id: 34, reg: 'EMR', prov: 'FE', descr: 'Ferrara', link_grp: 'https://t.me/c/1614195634/429?thread=420'}, {_id: 34, reg: 'EMR', prov: 'FE', descr: 'Ferrara', link_grp: 'https://t.me/c/1614195634/429?thread=420', link_telegram: ''},
{_id: 35, reg: 'TOS', prov: 'FI', descr: 'Firenze', link_grp: 'https://t.me/c/1614195634/584?thread=573'}, {_id: 35, reg: 'TOS', prov: 'FI', descr: 'Firenze', link_grp: 'https://t.me/c/1614195634/584?thread=573', link_telegram: ''},
{_id: 36, reg: 'PUG', prov: 'FG', descr: 'Foggia', link_grp: 'https://t.me/c/1614195634/537?thread=531'}, {_id: 36, reg: 'PUG', prov: 'FG', descr: 'Foggia', link_grp: 'https://t.me/c/1614195634/537?thread=531', link_telegram: ''},
{_id: 37, reg: 'EMR', prov: 'FC', descr: 'Forli-Cesena', link_grp: 'https://t.me/c/1614195634/430?thread=421'}, {_id: 37, reg: 'EMR', prov: 'FC', descr: 'Forli-Cesena', link_grp: 'https://t.me/c/1614195634/430?thread=421', link_telegram: ''},
{_id: 38, reg: 'LAZ', prov: 'FR', descr: 'Frosinone', link_grp: 'https://t.me/c/1614195634/48?thread=44'}, {_id: 38, reg: 'LAZ', prov: 'FR', descr: 'Frosinone', link_grp: 'https://t.me/c/1614195634/48?thread=44', link_telegram: ''},
{_id: 39, reg: 'LIG', prov: 'GE', descr: 'Genova', link_grp: 'https://t.me/c/1614195634/392?thread=388'}, {_id: 39, reg: 'LIG', prov: 'GE', descr: 'Genova', link_grp: 'https://t.me/c/1614195634/392?thread=388', link_telegram: ''},
{_id: 40, reg: 'FVG', prov: 'GO', descr: 'Gorizia', link_grp: 'https://t.me/c/1614195634/469?thread=465'}, {_id: 40, reg: 'FVG', prov: 'GO', descr: 'Gorizia', link_grp: 'https://t.me/c/1614195634/469?thread=465', link_telegram: ''},
{_id: 41, reg: 'TOS', prov: 'GR', descr: 'Grosseto', link_grp: 'https://t.me/c/1614195634/585?thread=574'}, {_id: 41, reg: 'TOS', prov: 'GR', descr: 'Grosseto', link_grp: 'https://t.me/c/1614195634/585?thread=574', link_telegram: ''},
{_id: 42, reg: 'LIG', prov: 'IM', descr: 'Imperia', link_grp: 'https://t.me/c/1614195634/393?thread=389'}, {_id: 42, reg: 'LIG', prov: 'IM', descr: 'Imperia', link_grp: 'https://t.me/c/1614195634/393?thread=389', link_telegram: ''},
{_id: 43, reg: 'MOL', prov: 'IS', descr: 'Isernia', link_grp: 'https://t.me/c/1614195634/399?thread=397'}, {_id: 43, reg: 'MOL', prov: 'IS', descr: 'Isernia', link_grp: 'https://t.me/c/1614195634/399?thread=397', link_telegram: ''},
{_id: 44, reg: 'LIG', prov: 'SP', descr: 'La Spezia', link_grp: 'https://t.me/c/1614195634/394?thread=390'}, {_id: 44, reg: 'LIG', prov: 'SP', descr: 'La Spezia', link_grp: 'https://t.me/c/1614195634/394?thread=390', link_telegram: ''},
{_id: 45, reg: 'ABR', prov: 'AQ', descr: 'L\'Aquila', link_grp: 'https://t.me/c/1614195634/364?thread=363'}, {_id: 45, reg: 'ABR', prov: 'AQ', descr: 'L\'Aquila', link_grp: 'https://t.me/c/1614195634/364?thread=363', link_telegram: ''},
{_id: 46, reg: 'LAZ', prov: 'LT', descr: 'Latina', link_grp: 'https://t.me/c/1614195634/60?thread=46'}, {_id: 46, reg: 'LAZ', prov: 'LT', descr: 'Latina', link_grp: 'https://t.me/c/1614195634/60?thread=46', link_telegram: ''},
{_id: 47, reg: 'PUG', prov: 'LE', descr: 'Lecce', link_grp: 'https://t.me/c/1614195634/538?thread=532'}, {_id: 47, reg: 'PUG', prov: 'LE', descr: 'Lecce', link_grp: 'https://t.me/c/1614195634/538?thread=532', link_telegram: ''},
{_id: 48, reg: 'LOM', prov: 'LC', descr: 'Lecco', link_grp: 'https://t.me/c/1614195634/494?thread=482'}, {_id: 48, reg: 'LOM', prov: 'LC', descr: 'Lecco', link_grp: 'https://t.me/c/1614195634/494?thread=482', link_telegram: ''},
{_id: 49, reg: 'TOS', prov: 'LI', descr: 'Livorno', link_grp: 'https://t.me/c/1614195634/586?thread=575'}, {_id: 49, reg: 'TOS', prov: 'LI', descr: 'Livorno', link_grp: 'https://t.me/c/1614195634/586?thread=575', link_telegram: ''},
{_id: 50, reg: 'LOM', prov: 'LO', descr: 'Lodi', link_grp: 'https://t.me/c/1614195634/495?thread=483'}, {_id: 50, reg: 'LOM', prov: 'LO', descr: 'Lodi', link_grp: 'https://t.me/c/1614195634/495?thread=483', link_telegram: ''},
{_id: 51, reg: 'TOS', prov: 'LU', descr: 'Lucca', link_grp: 'https://t.me/c/1614195634/587?thread=576'}, {_id: 51, reg: 'TOS', prov: 'LU', descr: 'Lucca', link_grp: 'https://t.me/c/1614195634/587?thread=576', link_telegram: ''},
{_id: 52, reg: 'MAR', prov: 'MC', descr: 'Macerata', link_grp: 'https://t.me/c/1614195634/300?thread=162'}, {_id: 52, reg: 'MAR', prov: 'MC', descr: 'Macerata', link_grp: 'https://t.me/c/1614195634/300?thread=162', link_telegram: ''},
{_id: 53, reg: 'LOM', prov: 'MN', descr: 'Mantova', link_grp: 'https://t.me/c/1614195634/497?thread=484'}, {_id: 53, reg: 'LOM', prov: 'MN', descr: 'Mantova', link_grp: 'https://t.me/c/1614195634/497?thread=484', link_telegram: ''},
{_id: 54, reg: 'TOS', prov: 'MS', descr: 'Massa-Carrara', link_grp: 'https://t.me/c/1614195634/588?thread=577'}, {_id: 54, reg: 'TOS', prov: 'MS', descr: 'Massa-Carrara', link_grp: 'https://t.me/c/1614195634/588?thread=577', link_telegram: ''},
{_id: 55, reg: 'BAS', prov: 'MT', descr: 'Matera', link_grp: 'https://t.me/c/1614195634/374?thread=373'}, {_id: 55, reg: 'BAS', prov: 'MT', descr: 'Matera', link_grp: 'https://t.me/c/1614195634/374?thread=373', link_telegram: ''},
{_id: 56, reg: 'SIC', prov: 'ME', descr: 'Messina', link_grp: 'https://t.me/c/1614195634/566?thread=557'}, {_id: 56, reg: 'SIC', prov: 'ME', descr: 'Messina', link_grp: 'https://t.me/c/1614195634/566?thread=557', link_telegram: ''},
{_id: 57, reg: 'LOM', prov: 'MI', descr: 'Milano', link_grp: 'https://t.me/c/1614195634/214?thread=173'}, {_id: 57, reg: 'LOM', prov: 'MI', descr: 'Milano', link_grp: 'https://t.me/c/1614195634/214?thread=173', link_telegram: ''},
{_id: 58, reg: 'EMR', prov: 'MO', descr: 'Modena', link_grp: 'https://t.me/c/1614195634/431?thread=422'}, {_id: 58, reg: 'EMR', prov: 'MO', descr: 'Modena', link_grp: 'https://t.me/c/1614195634/431?thread=422', link_telegram: ''},
{_id: 59, reg: 'LOM', prov: 'MB', descr: 'Monza e della Brianza', link_grp: 'https://t.me/c/1614195634/498?thread=485'}, {_id: 59, reg: 'LOM', prov: 'MB', descr: 'Monza e della Brianza', link_grp: 'https://t.me/c/1614195634/498?thread=485', link_telegram: ''},
{_id: 60, reg: 'CAM', prov: 'NA', descr: 'Napoli', link_grp: 'https://t.me/c/1614195634/407?thread=406'}, {_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'}, {_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'}, {_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: ''}, {_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'}, {_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'}, {_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'}, {_id: 66, reg: 'SIC', prov: 'PA', descr: 'Palermo', link_grp: 'https://t.me/c/1614195634/568?thread=558', link_telegram: ''},
{_id: 67, reg: 'EMR', prov: 'PR', descr: 'Parma', link_grp: 'https://t.me/c/1614195634/432?thread=423'}, {_id: 67, reg: 'EMR', prov: 'PR', descr: 'Parma', link_grp: 'https://t.me/c/1614195634/432?thread=423', link_telegram: ''},
{_id: 68, reg: 'LOM', prov: 'PV', descr: 'Pavia', link_grp: 'https://t.me/c/1614195634/499?thread=486'}, {_id: 68, reg: 'LOM', prov: 'PV', descr: 'Pavia', link_grp: 'https://t.me/c/1614195634/499?thread=486', link_telegram: ''},
{_id: 69, reg: 'UMB', prov: 'PG', descr: 'Perugia', link_grp: 'https://t.me/c/1614195634/403?thread=401'}, {_id: 69, reg: 'UMB', prov: 'PG', descr: 'Perugia', link_grp: 'https://t.me/c/1614195634/403?thread=401', link_telegram: ''},
{_id: 70, reg: 'MAR', prov: 'PU', descr: 'Pesaro e Urbino', link_grp: 'https://t.me/c/1614195634/454?thread=449'}, {_id: 70, reg: 'MAR', prov: 'PU', descr: 'Pesaro e Urbino', link_grp: 'https://t.me/c/1614195634/454?thread=449', link_telegram: ''},
{_id: 71, reg: 'ABR', prov: 'PE', descr: 'Pescara', link_grp: 'https://t.me/c/1614195634/368?thread=367'}, {_id: 71, reg: 'ABR', prov: 'PE', descr: 'Pescara', link_grp: 'https://t.me/c/1614195634/368?thread=367', link_telegram: ''},
{_id: 72, reg: 'EMR', prov: 'PC', descr: 'Piacenza', link_grp: 'https://t.me/c/1614195634/433?thread=424'}, {_id: 72, reg: 'EMR', prov: 'PC', descr: 'Piacenza', link_grp: 'https://t.me/c/1614195634/433?thread=424', link_telegram: ''},
{_id: 73, reg: 'TOS', prov: 'PI', descr: 'Pisa', link_grp: 'https://t.me/c/1614195634/589?thread=578'}, {_id: 73, reg: 'TOS', prov: 'PI', descr: 'Pisa', link_grp: 'https://t.me/c/1614195634/589?thread=578', link_telegram: ''},
{_id: 74, reg: 'TOS', prov: 'PT', descr: 'Pistoia', link_grp: 'https://t.me/c/1614195634/590?thread=579'}, {_id: 74, reg: 'TOS', prov: 'PT', descr: 'Pistoia', link_grp: 'https://t.me/c/1614195634/590?thread=579', link_telegram: ''},
{_id: 75, reg: 'FVG', prov: 'PN', descr: 'Pordenone', link_grp: 'https://t.me/c/1614195634/470?thread=466'}, {_id: 75, reg: 'FVG', prov: 'PN', descr: 'Pordenone', link_grp: 'https://t.me/c/1614195634/470?thread=466', link_telegram: ''},
{_id: 76, reg: 'BAS', prov: 'PZ', descr: 'Potenza', link_grp: 'https://t.me/c/1614195634/376?thread=375'}, {_id: 76, reg: 'BAS', prov: 'PZ', descr: 'Potenza', link_grp: 'https://t.me/c/1614195634/376?thread=375', link_telegram: ''},
{_id: 77, reg: 'TOS', prov: 'PO', descr: 'Prato', link_grp: 'https://t.me/c/1614195634/591?thread=580'}, {_id: 77, reg: 'TOS', prov: 'PO', descr: 'Prato', link_grp: 'https://t.me/c/1614195634/591?thread=580', link_telegram: ''},
{_id: 78, reg: 'SIC', prov: 'RG', descr: 'Ragusa', link_grp: 'https://t.me/c/1614195634/569?thread=559'}, {_id: 78, reg: 'SIC', prov: 'RG', descr: 'Ragusa', link_grp: 'https://t.me/c/1614195634/569?thread=559', link_telegram: ''},
{_id: 79, reg: 'EMR', prov: 'RA', descr: 'Ravenna', link_grp: 'https://t.me/c/1614195634/434?thread=425'}, {_id: 79, reg: 'EMR', prov: 'RA', descr: 'Ravenna', link_grp: 'https://t.me/c/1614195634/434?thread=425', link_telegram: ''},
{_id: 80, reg: 'CAL', prov: 'RC', descr: 'Reggio Calabria', link_grp: 'https://t.me/c/1614195634/385?thread=383'}, {_id: 80, reg: 'CAL', prov: 'RC', descr: 'Reggio Calabria', link_grp: 'https://t.me/c/1614195634/385?thread=383', link_telegram: ''},
{_id: 81, reg: 'EMR', prov: 'RE', descr: 'Reggio Emilia', link_grp: 'https://t.me/c/1614195634/435?thread=426'}, {_id: 81, reg: 'EMR', prov: 'RE', descr: 'Reggio Emilia', link_grp: 'https://t.me/c/1614195634/435?thread=426', link_telegram: ''},
{_id: 82, reg: 'LAZ', prov: 'RI', descr: 'Rieti', link_grp: 'https://t.me/c/1614195634/61?thread=45'}, {_id: 82, reg: 'LAZ', prov: 'RI', descr: 'Rieti', link_grp: 'https://t.me/c/1614195634/61?thread=45', link_telegram: ''},
{_id: 83, reg: 'EMR', prov: 'RN', descr: 'Rimini', link_grp: 'https://t.me/c/1614195634/436?thread=https://t.me/c/1614195634/64?thread=57427'}, {_id: 83, reg: 'EMR', prov: 'RN', descr: 'Rimini', link_grp: 'https://t.me/c/1614195634/436?thread=https://t.me/c/1614195634/64?thread=57427', link_telegram: ''},
{_id: 84, reg: 'LAZ', prov: 'RM', descr: 'Roma', link_grp: ''}, {_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'}, {_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'}, {_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: ''}, {_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'}, {_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'}, {_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'}, {_id: 90, reg: 'TOS', prov: 'SI', descr: 'Siena', link_grp: 'https://t.me/c/1614195634/592?thread=581', link_telegram: ''},
{_id: 91, reg: 'SIC', prov: 'SR', descr: 'Siracusa', link_grp: 'https://t.me/c/1614195634/570?thread=560'}, {_id: 91, reg: 'SIC', prov: 'SR', descr: 'Siracusa', link_grp: 'https://t.me/c/1614195634/570?thread=560', link_telegram: ''},
{_id: 92, reg: 'LOM', prov: 'SO', descr: 'Sondrio', link_grp: 'https://t.me/c/1614195634/500?thread=487'}, {_id: 92, reg: 'LOM', prov: 'SO', descr: 'Sondrio', link_grp: 'https://t.me/c/1614195634/500?thread=487', link_telegram: ''},
{_id: 93, reg: 'PUG', prov: 'TA', descr: 'Taranto', link_grp: 'https://t.me/c/1614195634/539?thread=533'}, {_id: 93, reg: 'PUG', prov: 'TA', descr: 'Taranto', link_grp: 'https://t.me/c/1614195634/539?thread=533', link_telegram: ''},
{_id: 94, reg: 'ABR', prov: 'TE', descr: 'Teramo', link_grp: 'https://t.me/c/1614195634/370?thread=369'}, {_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'}, {_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'}, {_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: ''}, {_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'}, {_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'}, {_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'}, {_id: 100, reg: 'VEN', prov: 'TV', descr: 'Treviso', link_grp: 'https://t.me/c/1614195634/612?thread=602', link_telegram: ''},
{_id: 101, reg: 'FVG', prov: 'TS', descr: 'Trieste', link_grp: 'https://t.me/c/1614195634/471?thread=467'}, {_id: 101, reg: 'FVG', prov: 'TS', descr: 'Trieste', link_grp: 'https://t.me/c/1614195634/471?thread=467', link_telegram: ''},
{_id: 102, reg: 'FVG', prov: 'UD', descr: 'Udine', link_grp: 'https://t.me/c/1614195634/472?thread=468'}, {_id: 102, reg: 'FVG', prov: 'UD', descr: 'Udine', link_grp: 'https://t.me/c/1614195634/472?thread=468', link_telegram: ''},
{_id: 103, reg: 'LOM', prov: 'VA', descr: 'Varese', link_grp: 'https://t.me/c/1614195634/501?thread=488'}, {_id: 103, reg: 'LOM', prov: 'VA', descr: 'Varese', link_grp: 'https://t.me/c/1614195634/501?thread=488', link_telegram: ''},
{_id: 104, reg: 'VEN', prov: 'VE', descr: 'Venezia', link_grp: 'https://t.me/c/1614195634/613?thread=603'}, {_id: 104, reg: 'VEN', prov: 'VE', descr: 'Venezia', link_grp: 'https://t.me/c/1614195634/613?thread=603', link_telegram: ''},
{_id: 105, reg: 'PIE', prov: 'VB', descr: 'Verbano-Cusio-Ossola', link_grp: 'https://t.me/c/1614195634/519?thread=510 '}, {_id: 105, reg: 'PIE', prov: 'VB', descr: 'Verbano-Cusio-Ossola', link_grp: 'https://t.me/c/1614195634/519?thread=510 ', link_telegram: ''},
{_id: 106, reg: 'PIE', prov: 'VC', descr: 'Vercelli', link_grp: 'https://t.me/c/1614195634/512?thread=511'}, {_id: 106, reg: 'PIE', prov: 'VC', descr: 'Vercelli', link_grp: 'https://t.me/c/1614195634/512?thread=511', link_telegram: ''},
{_id: 107, reg: 'VEN', prov: 'VR', descr: 'Verona', link_grp: 'https://t.me/c/1614195634/614?thread=604'}, {_id: 107, reg: 'VEN', prov: 'VR', descr: 'Verona', link_grp: 'https://t.me/c/1614195634/614?thread=604', link_telegram: ''},
{_id: 108, reg: 'CAL', prov: 'VV', descr: 'Vibo Valentia', link_grp: 'https://t.me/c/1614195634/386?thread=384'}, {_id: 108, reg: 'CAL', prov: 'VV', descr: 'Vibo Valentia', link_grp: 'https://t.me/c/1614195634/386?thread=384', link_telegram: ''},
{_id: 109, reg: 'VEN', prov: 'VI', descr: 'Vicenza', link_grp: 'https://t.me/c/1614195634/615?thread=605'}, {_id: 109, reg: 'VEN', prov: 'VI', descr: 'Vicenza', link_grp: 'https://t.me/c/1614195634/615?thread=605', link_telegram: ''},
{_id: 110, reg: 'LAZ', prov: 'VT', descr: 'Viterbo', link_grp: 'https://t.me/c/1614195634/76?thread=74'}, {_id: 110, reg: 'LAZ', prov: 'VT', descr: 'Viterbo', link_grp: 'https://t.me/c/1614195634/76?thread=74', link_telegram: ''},
{_id: 111, reg: 'RSM', prov: 'RSM', descr: 'Repubblica di San Marino', link_grp: 'https://t.me/+HSdNurm0IXY1MGI0'}, {_id: 111, reg: 'RSM', prov: 'RSM', descr: 'Repubblica di San Marino', link_grp: 'https://t.me/+HSdNurm0IXY1MGI0', link_telegram: ''},
{_id: 112, reg: 'EST', prov: 'EST', descr: 'Estero', link_grp: ''}, {_id: 112, reg: 'EST', prov: 'EST', descr: 'Estero', link_grp: '', link_telegram: ''},
{_id: 113, reg: 'ONL', prov: 'ONL', descr: 'On Line', link_grp: ''}, {_id: 113, reg: 'ONL', prov: 'ONL', descr: 'On Line', link_grp: '', link_telegram: ''},
{_id: 114, reg: 'LAZ', prov: 'RM', descr: 'Roma Nord-Est', link_grp: 'https://t.me/c/1614195634/64?thread=57'}, {_id: 114, reg: 'LAZ', prov: 'RM', descr: 'Roma Nord-Est', card: 'NORD-EST', link_grp: 'https://t.me/c/1614195634/64?thread=57', link_telegram: ''},
{_id: 115, reg: 'LAZ', prov: 'RM', descr: 'Roma Sud-Est', link_grp: 'https://t.me/c/1614195634/65?thread=58'}, {_id: 115, reg: 'LAZ', prov: 'RM', descr: 'Roma Sud-Est', card: 'SUD-EST', link_grp: 'https://t.me/c/1614195634/65?thread=58', link_telegram: ''},
{_id: 116, reg: 'LAZ', prov: 'RM', descr: 'Roma Nord', link_grp: 'https://t.me/c/1614195634/75?thread=73'}, {_id: 116, reg: 'LAZ', prov: 'RM', descr: 'Roma Nord', card: 'NORD', link_grp: 'https://t.me/c/1614195634/75?thread=73', link_telegram: ''},
{_id: 117, reg: 'LAZ', prov: 'RM', descr: 'Roma Nord-Ovest', link_grp: 'https://t.me/c/1614195634/62?thread=47'}, {_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', link_grp: 'https://t.me/c/1614195634/67?thread=43'}, {_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'}, {_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'}, {_id: 120, reg: 'SAR', prov: 'SUS', descr: 'Sud Sardegna', link_grp: 'https://t.me/c/1614195634/552?thread=545', link_telegram: ''},
{_id: 121, reg: 'ITA', prov: 'ITA', descr: 'Italia', link_grp: '', link_telegram: ''},
{_id: 122, reg: 'LOM', prov: 'MI', card: 'EST', descr: 'Milano Est', link_grp: '', link_telegram: ''},
], ],
}; };

View File

@@ -42,13 +42,13 @@ module.exports = {
{_id: 40, idSector: [7], descr: 'Muratore'}, {_id: 40, idSector: [7], descr: 'Muratore'},
{_id: 41, idSector: [7], descr: 'Imbianchino'}, {_id: 41, idSector: [7], descr: 'Imbianchino'},
{_id: 42, idSector: [7], descr: 'Elettricista - TV'}, {_id: 42, idSector: [7], descr: 'Elettricista - TV'},
{_id: 43, idSector: [7], descr: 'Falegname e restauro'}, {_id: 43, idSector: [7], descr: 'Falegname'},
{_id: 44, idSector: [7], descr: 'Fabbro'}, {_id: 44, idSector: [7], descr: 'Fabbro'},
{_id: 45, idSector: [7], descr: 'Arredamento'}, {_id: 45, idSector: [7], descr: 'Arredamento'},
{_id: 46, idSector: [7], descr: 'Idraulico'}, {_id: 46, idSector: [7], descr: 'Idraulico'},
{_id: 47, idSector: [7], descr: 'Giardiniere'}, {_id: 47, idSector: [7], descr: 'Giardiniere'},
{_id: 48, idSector: [7], descr: 'Canne fumarie e camini e stufe'}, {_id: 48, idSector: [7], descr: 'Canne fumarie e camini e stufe'},
{_id: 49, idSector: [7], descr: 'Pannelli solari e pompe calore'}, {_id: 49, idSector: [7], descr: 'Pannelli solari'},
{_id: 50, idSector: [7], descr: 'Riparazioni varie'}, {_id: 50, idSector: [7], descr: 'Riparazioni varie'},
{_id: 51, idSector: [7], descr: 'Tuttofare'}, {_id: 51, idSector: [7], descr: 'Tuttofare'},
{_id: 52, idSector: [7], descr: 'Traslochi'}, {_id: 52, idSector: [7], descr: 'Traslochi'},
@@ -121,5 +121,11 @@ module.exports = {
{_id: 126, idSector: [1], descr: 'Terreno'}, {_id: 126, idSector: [1], descr: 'Terreno'},
{_id: 127, idSector: [1], descr: 'Stanza in affitto'}, {_id: 127, idSector: [1], descr: 'Stanza in affitto'},
{_id: 128, idSector: [1], descr: 'Stanza in condivisione'}, {_id: 128, idSector: [1], descr: 'Stanza in condivisione'},
{_id: 129, idSector: [3], descr: 'Home Restaurant'},
{_id: 130, idSector: [7], descr: 'Pannelli Solari'},
{_id: 131, idSector: [7], descr: 'Pompe di calore'},
{_id: 132, idSector: [7], descr: 'Impianti Fotovoltaici'},
{_id: 133, idSector: [7], descr: 'Restauro'},
{_id: 134, idSector: [7], descr: 'Altro'},
], ],
}; };

View File

@@ -0,0 +1,54 @@
const express = require('express');
const router = express.Router();
const tools = require('../tools/general');
const server_constants = require('../tools/server_constants');
const { authenticate } = require('../middleware/authenticate');
const mongoose = require('mongoose').set('debug', false);
const { User } = require('../models/user');
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
async function getCircuitRecAdminsInfo(idapp, data) {
if (data && data.admins) {
for (const admin of data.admins) {
const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
admin.profile = { img: myuser.profile.img };
}
}
return data;
}
router.post('/loadall', authenticate, async (req, res) => {
const idapp = req.body.idapp;
try {
let listaccounts = []
if (User.isAdmin(req.user.perm)) {
listaccounts = await Account.find({ idapp }).lean();
}
res.send({ listaccounts });
} catch (e) {
console.error('Error in Accounts', e);
return res.status(400).send(e);
}
const ris = null;
});
module.exports = router;

View File

@@ -5,24 +5,33 @@ 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 shared_consts = require('../tools/shared_nodejs');
const { authenticate } = require('../middleware/authenticate');
const mongoose = require('mongoose').set('debug', false); const mongoose = require('mongoose').set('debug', false);
const {User} = require('../models/user'); const { User } = require('../models/user');
const {Circuit} = require('../models/circuit'); const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
const _ = require('lodash'); const _ = require('lodash');
const {ObjectID} = require('mongodb'); const { ObjectID } = require('mongodb');
async function getCircuitRecAdminsInfo(idapp, data) { async function getCircuitRecAdminsInfo(idapp, data) {
if (data && data.admins) { try {
for (const admin of data.admins) { if (data && data.admins) {
const myuser = await User.findOne({idapp, username: admin.username}, {'profile.img': 1}).lean(); for (const admin of data.admins) {
admin.profile = {img: myuser.profile.img}; const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
if (myuser && myuser.profile)
admin.profile = { img: myuser.profile.img };
}
} }
} catch (e) {
console.error(e);
return data;
} }
return data; return data;
@@ -35,15 +44,16 @@ router.post('/load', authenticate, async (req, res) => {
try { try {
const {SendNotif} = require('../models/sendnotif'); const { SendNotif } = require('../models/sendnotif');
const {Movement} = require('../models/movement'); const { Movement } = require('../models/movement');
// Check if ìs a Notif to read // Check if ìs a Notif to read
const idnotif = req.body['idnotif'] ? req.body['idnotif'] : ''; const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
const lastdr = req.body['lastdr'] ? req.body['lastdr'] : '';
SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif); SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
const whatshow = Circuit.getWhatToShow(idapp, req.user.username); const whatshow = Circuit.getWhatToShow(idapp, req.user.username);
let data = await Circuit.findOne({idapp, path}, whatshow).lean(); let data = await Circuit.findOne({ idapp, path }, whatshow).lean();
const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username); const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username);
@@ -70,7 +80,17 @@ router.post('/load', authenticate, async (req, res) => {
data.movements = await Movement.getMovsByCircuitId(idapp, usernameOrig, data._id); data.movements = await Movement.getMovsByCircuitId(idapp, usernameOrig, data._id);
} }
res.send({circuit: data, users_in_circuit}); if (data) {
data.account = await Account.getAccountByUsernameAndCircuitId(idapp, '', data._id, false, false, '', data.path);
}
const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(req.user.username, lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER);
/// E' QUIIII !!!!
const useraccounts = await Account.getUserAccounts(idapp, req.user.username);
await User.setLastCircuitOpened(idapp, req.user.username, path);
res.send({ circuit: data, users_in_circuit, arrrecnotif, useraccounts });
} catch (e) { } catch (e) {
console.error('Error in Circuits', e); console.error('Error in Circuits', e);

View File

@@ -5,6 +5,8 @@ const router = express.Router(),
const telegrambot = require('../telegram/telegrambot'); const telegrambot = require('../telegram/telegrambot');
const i18n = require('i18n');
const sharp = require('sharp'); const sharp = require('sharp');
const { authenticate, authenticate_noerror } = require( const { authenticate, authenticate_noerror } = require(
@@ -142,6 +144,8 @@ router.post(process.env.LINK_REQUEST_NEWPASSWORD, async (req, res) => {
const email = body.email.toLowerCase().trim(); const email = body.email.toLowerCase().trim();
const codetocheck = body.codetocheck ? body.codetocheck.trim() : ''; const codetocheck = body.codetocheck ? body.codetocheck.trim() : '';
console.log('Request Reset Pwd:', email, ' idapp=', idapp);
// Check if too many requests // Check if too many requests
if (await User.tooManyReqPassword(idapp, email, true)) { if (await User.tooManyReqPassword(idapp, email, true)) {
console.log(process.env.LINK_REQUEST_NEWPASSWORD, 'TOO MANY REQUESTS !!! EXIT ', email); console.log(process.env.LINK_REQUEST_NEWPASSWORD, 'TOO MANY REQUESTS !!! EXIT ', email);
@@ -266,6 +270,7 @@ router.get('/test1', authenticate_noerror, async (req, res) => {
router.post('/settable', authenticate, async (req, res) => { router.post('/settable', authenticate, async (req, res) => {
const params = req.body; const params = req.body;
const mytable = globalTables.getTableByTableName(params.table); const mytable = globalTables.getTableByTableName(params.table);
let mydata = req.body.data; let mydata = req.body.data;
let extrarec = {}; let extrarec = {};
if (mydata && mydata.hasOwnProperty('extrarec')) { if (mydata && mydata.hasOwnProperty('extrarec')) {
@@ -273,6 +278,11 @@ router.post('/settable', authenticate, async (req, res) => {
delete mydata['extrarec']; delete mydata['extrarec'];
} }
if (mydata === undefined) {
console.error('MYDATA VUOTO !');
return res.status(400).send('Mydata VUOTO');
}
const fieldsvalue = { 'ALL': 1 }; const fieldsvalue = { 'ALL': 1 };
mydata.idapp = req.user.idapp; mydata.idapp = req.user.idapp;
@@ -350,7 +360,7 @@ router.post('/settable', authenticate, async (req, res) => {
const mytablestrutt = globalTables.getTableByTableName(params.table); const mytablestrutt = globalTables.getTableByTableName(params.table);
if (mydata['_id'] !== undefined && mydata['_id'] !== 0) { if (mydata['_id'] !== undefined && mydata['_id'] !== 0 && mydata['_id'] !== '') {
mytablerec.isNew = false; mytablerec.isNew = false;
} }
@@ -360,8 +370,9 @@ router.post('/settable', authenticate, async (req, res) => {
} else if (params.table === 'hours') { } else if (params.table === 'hours') {
} else { } else {
if ((mydata['_id'] === undefined || mydata['_id'] === '' || (mytablerec.isNew && mydata['_id'] === 0)) && (mytablerec._id === undefined)) { if ((mydata['_id'] === undefined || mydata['_id'] === '' || (mytablerec.isNew && mydata['_id'] === 0)) && (mytablerec._id === undefined || mytablerec._id === '0')) {
mytablerec._id = new ObjectID(); mytablerec._id = new ObjectID();
mydata._id = new ObjectID();
} }
} }
@@ -397,12 +408,45 @@ router.post('/settable', authenticate, async (req, res) => {
if (shared_consts.TABLES_UPDATE_LASTMODIFIED.includes(params.table)) { if (shared_consts.TABLES_UPDATE_LASTMODIFIED.includes(params.table)) {
mytablerec.date_updated = new Date(); mytablerec.date_updated = new Date();
mydata.date_updated = new Date();
} }
// console.log('mydata',mydata); // console.log('mydata',mydata);
// return await mytablerec.save().
// then(async (rec) => {
return await mytablerec.save(). const myPromise = new Promise((resolve, reject) => {
then(async (rec) => { resolve(mytablerec._id && mytable.findById(mytablerec._id))
});
// Controlla se esiste già questo record:
if (shared_consts.TABLES_FIELDS_DESCR_AND_CITY_AND_USER.includes(params.table)) {
if (mytablerec.isNew) {
const trovatoDuplicato = await mytable.findOne({ idapp: mytablerec.idapp, descr: mytablerec.descr, idCity: mytablerec.idCity, userId: mytablerec.userId }).lean();
if (trovatoDuplicato) {
// trovatoDuplicato
return res.status(200).send({ code: server_constants.RIS_CODE_REC_DUPLICATED_DESCR_CITY_USER, msg: '' });
}
}
}
return await myPromise
.then(async (doupdate) => {
if (doupdate)
return mytable.updateOne({ _id: mytablerec._id }, mydata, { new: true })
else
return mytablerec.save()
})
.then(async (risult) => {
let rec = null;
if (risult && risult.ok === 1) {
rec = await mytable.findById(mytablerec._id).lean();
} else {
rec = risult;
}
if (shared_consts.TABLES_GETCOMPLETEREC.includes(params.table)) { if (shared_consts.TABLES_GETCOMPLETEREC.includes(params.table)) {
return await mytablestrutt.getCompleteRecord(rec.idapp, rec._id); return await mytablestrutt.getCompleteRecord(rec.idapp, rec._id);
@@ -424,9 +468,12 @@ router.post('/settable', authenticate, async (req, res) => {
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(params.table)) { if (shared_consts.TABLES_ADV_NOTIFICATION.includes(params.table)) {
typedir = shared_consts.TypeNotifs.TYPEDIR_BACHECA; typedir = shared_consts.TypeNotifs.TYPEDIR_BACHECA;
typeid = (params.table === shared_consts.TABLES_MYGOODS) if (params.table === shared_consts.TABLES_MYGOODS)
? shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD
: shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE; else if (params.table === shared_consts.TABLES_MYSKILLS)
typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE
else if (params.table === shared_consts.TABLES_MYHOSPS)
typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_HOSP
setnotif = true; setnotif = true;
} }
@@ -442,16 +489,18 @@ router.post('/settable', authenticate, async (req, res) => {
groupnameDest = myrec ? myrec.groupname : ''; groupnameDest = myrec ? myrec.groupname : '';
setnotif = true; setnotif = true;
} }
if (shared_consts.TABLES_CIRCUITS_NOTIFICATION.includes(params.table)) { /*if (shared_consts.TABLES_CIRCUITS_NOTIFICATION.includes(params.table)) {
typedir = shared_consts.TypeNotifs.TYPEDIR_CIRCUITS; typedir = shared_consts.TypeNotifs.TYPEDIR_CIRCUITS;
typeid = shared_consts.TypeNotifs.ID_CIRCUIT_NEW_REC; typeid = shared_consts.TypeNotifs.ID_CIRCUIT_NEW_REC;
circuitnameDest = myrec ? myrec.name : ''; circuitnameDest = myrec ? myrec.name : '';
setnotif = (myrec.visibility === 0); // Not send a notification to others if the Circuit is HIDDEN or PRIVATE setnotif = (myrec.visibility === 0); // Not send a notification to others if the Circuit is HIDDEN or PRIVATE
} }*/
} }
if (setnotif) { if (setnotif) {
await SendNotif.createNewNotification(req, res, { groupnameDest, circuitnameDest }, params.table, myrec, typedir, typeid); const myreq = { ...req };
const myres = { ...res };
SendNotif.createNewNotification(myreq, myres, { groupnameDest, circuitnameDest }, params.table, myrec, typedir, typeid);
} }
if (params.table === 'circuits') { if (params.table === 'circuits') {
@@ -467,7 +516,12 @@ router.post('/settable', authenticate, async (req, res) => {
return res.send({ rec: myrec, ris }); return res.send({ rec: myrec, ris });
}); });
} else if (params.table === shared_consts.TAB_MYCIRCUITS && isnewrec) { } else if (params.table === shared_consts.TAB_MYCIRCUITS && isnewrec) {
// nuovo Record: // nuovo Circuito:
await User.setCircuitCmd(mydata.idapp, req.user.username, myrec.name,
shared_consts.CIRCUITCMD.CREATE, true, req.user.username, extrarec).then((ris) => {
return res.send({ rec: myrec, ris });
});
// aggiungi il creatore al Circuito stesso // aggiungi il creatore al Circuito stesso
return await User.setCircuitCmd(mydata.idapp, req.user.username, myrec.name, return await User.setCircuitCmd(mydata.idapp, req.user.username, myrec.name,
shared_consts.CIRCUITCMD.SET, true, req.user.username, extrarec).then((ris) => { shared_consts.CIRCUITCMD.SET, true, req.user.username, extrarec).then((ris) => {
@@ -558,9 +612,9 @@ router.post('/setsubrec', authenticate, (req, res) => {
router.post('/gettable', authenticate, (req, res) => { router.post('/gettable', authenticate, (req, res) => {
const params = req.body; const params = req.body;
let idapp = req.user.idapp; let idapp = req.user ? req.user.idapp : params.idapp;
const mytable = globalTables.getTableByTableName(params.table); const mytable = globalTables.getTableByTableName(params.table);
// console.log('mytable', mytable); //console.log('mytable', mytable);
if (!mytable) { if (!mytable) {
console.log(`Table ${params.table} not found`); console.log(`Table ${params.table} not found`);
return res.status(400).send({}); return res.status(400).send({});
@@ -572,7 +626,9 @@ router.post('/gettable', authenticate, (req, res) => {
User.setOnLine(req.user.idapp, req.user.username); User.setOnLine(req.user.idapp, req.user.username);
} }
return mytable.executeQueryTable(idapp, params, req.user).then(ris => { return mytable.executeQueryTable(idapp, params, req.user).then(ris => {
// console.log('ris=', ris);
return res.send(ris); return res.send(ris);
}).catch((e) => { }).catch((e) => {
@@ -668,12 +724,49 @@ router.post('/getpage', async (req, res) => {
const idapp = req.body.idapp; const idapp = req.body.idapp;
const mypath = params.path; const mypath = params.path;
return await MyPage.findOne({ idapp, path: mypath }).then((ris) => { let found = await MyPage.findOne({ idapp, path: mypath }).then((ris) => {
return res.send({ mypage: ris }); if (ris)
return res.send({ mypage: ris });
else
return null;
}).catch((e) => { }).catch((e) => {
console.log(e.message); console.log(e.message);
res.status(400).send(e); res.status(400).send(e);
}); });
if (!found) {
// trova quelli con il :
let regexp = new RegExp(`:`, 'ig')
const searchpagesSpec = await MyPage.find({ idapp, path: { $regex: regexp } });
if (searchpagesSpec) {
let arrsubpath = mypath.split('/');
for (let i = 0; i < searchpagesSpec.length; i++) {
let arrsubstr = searchpagesSpec[i].path.split('/');
if (arrsubpath.length === arrsubpath.length) {
let mypathbuild = '';
for (let j = 0; j < arrsubstr.length; j++) {
if (arrsubstr[j].includes(':')) {
mypathbuild += arrsubpath[j] + '/';
} else {
mypathbuild += arrsubstr[j] + '/';
}
}
if (mypath + '/' === mypathbuild) {
return res.send({ mypage: searchpagesSpec[i] });
}
}
}
}
return await MyPage.findOne({ idapp, path: mypath }).then((ris) => {
return res.send({ mypage: ris });
});
}
return found;
}); });
@@ -714,13 +807,17 @@ router.patch('/chval', authenticate, async (req, res) => {
const fieldsvalue = mydata.fieldsvalue; const fieldsvalue = mydata.fieldsvalue;
const unset = mydata.unset; const unset = mydata.unset;
const { Account } = require('../models/account');
// tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue); // tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue);
// If I change my record... // If I change my record...
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.isFacilitatore(req.user.perm)) &&
(req.user._id.toString() !== id) && (req.user._id.toString() !== id) &&
!tools.ModificheConsentite(mydata.table, fieldsvalue)) { (!tools.ModificheConsentite(mydata.table, fieldsvalue)))
&& !((mydata.table === 'accounts') && await Account.canEditAccountAdmins(req.user.username, mydata.id))
) {
// If without permissions, exit // If without permissions, exit
return res.status(404). return res.status(404).
send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
@@ -795,6 +892,12 @@ router.patch('/chval', authenticate, async (req, res) => {
} }
let precRec = null
if (mydata.table === 'accounts') {
precRec = await mytable.findById(id);
}
return await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }). return await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }).
then(async (rec) => { then(async (rec) => {
// tools.mylogshow(' REC TO MODIFY: ', rec); // tools.mylogshow(' REC TO MODIFY: ', rec);
@@ -821,14 +924,39 @@ router.patch('/chval', authenticate, async (req, res) => {
} }
if (mydata.table === 'accounts') { if (mydata.table === 'accounts') {
let msg = '';
if (rec.circuitId)
circuit = await Circuit.getCircuitByCircuitId(rec.circuitId);
let dest = rec.groupname ? rec.groupname : rec.username;
let valprec = 0
if ('saldo' in fieldsvalue) { if ('saldo' in fieldsvalue) {
msg = 'l\'utente ' + req.user.username + ' ha variato il Saldo di ' + rec.username + ' a ' + fieldsvalue.saldo; valprec = precRec && precRec.saldo ? precRec.saldo : 0
msg = i18n.__('SALDO_VARIATO', circuit.name, req.user.username, dest, valprec, fieldsvalue.saldo, circuit.symbol);
} else if ('fidoConcesso' in fieldsvalue) {
valprec = precRec && precRec.fidoConcesso ? precRec.fidoConcesso : 0
msg = i18n.__('FIDOCONCESSO_VARIATO', circuit.name, req.user.username, dest, valprec, fieldsvalue.fidoConcesso, circuit.symbol);
} else if ('qta_maxConcessa' in fieldsvalue) {
valprec = precRec && precRec.qta_maxConcessa ? precRec.qta_maxConcessa : 0
msg = i18n.__('QTAMAX_VARIATO', circuit.name, req.user.username, dest, valprec, fieldsvalue.qta_maxConcessa, circuit.symbol);
}
if (msg) {
telegrambot.sendMsgTelegramToTheManagers(idapp, msg); telegrambot.sendMsgTelegramToTheManagers(idapp, msg);
telegrambot.sendMsgTelegramToTheAdminsOfCircuit(idapp, circuit.path, msg);
} }
} }
if (mydata.table === 'users') { if (mydata.table === 'users') {
if ('profile.resid_province' in fieldsvalue) {
const card = fieldsvalue.hasOwnProperty('profile.resid_card') ? fieldsvalue['profile.resid_card'] : '';
// Controlla se esiste il Circuito di questa provincia, se non esiste lo crea!
await Circuit.createCircuitIfNotExist(req, idapp, fieldsvalue['profile.resid_province'], card);
}
if (camporequisiti) { if (camporequisiti) {
await User.checkIfSbloccatiRequisiti(idapp, allData, id); await User.checkIfSbloccatiRequisiti(idapp, allData, id);
} }
@@ -1153,11 +1281,11 @@ router.post('/duprec/:table/:id', authenticate, async (req, res) => {
send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
} }
if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) { /* if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) {
// If without permissions, exit // If without permissions, exit
return res.status(404). return res.status(404).
send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
} } */
return await mytable.findById(id).then(async (mydata) => { return await mytable.findById(id).then(async (mydata) => {
@@ -1250,6 +1378,9 @@ function load(req, res, version) {
const permissions = Permission.findAllIdApp(); const permissions = Permission.findAllIdApp();
// const versionstr = User....
// let version = tools.getVersionint(versionstr);
let newstosent = Promise.resolve([]); let newstosent = Promise.resolve([]);
let mailinglist = Promise.resolve([]); let mailinglist = Promise.resolve([]);
let mypage; let mypage;
@@ -1310,7 +1441,7 @@ function load(req, res, version) {
let myuserextra = null; let myuserextra = null;
if (req.user) { if (req.user) {
// askedfriends = User.getAskedFriendsByUsername(idapp, req.user.username); // askedfriends = User.getAskedFriendsByUsername(idapp, req.user.username);
myuserextra = User.addExtraInfo(idapp, req.user); myuserextra = User.addExtraInfo(idapp, req.user._doc, req.user, version);
} }
return Promise.all([ return Promise.all([
@@ -1748,14 +1879,19 @@ router.delete('/delfile', authenticate, (req, res) => {
deleteFile(req, res, 0); deleteFile(req, res, 0);
}); });
function deleteFile(req, res, version) { function deleteFile(req, res, version) {
const relativefile = req.query.filename; const relativefile = req.query.filename;
const idapp = req.user.idapp; const idapp = req.user.idapp;
if (!relativefile || relativefile.endsWith('/')) {
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
}
try { try {
let dirmain = ''; let dirmain = '';
if (version > 0) { if (version > 0) {
if (tools.sulServer() !== 1) { if (!tools.sulServer()) {
dirmain = '/public'; dirmain = '/public';
} }
} }

View File

@@ -5,60 +5,76 @@ const router = express.Router();
const tools = require('../tools/general'); const tools = require('../tools/general');
var server_constants = require('../tools/server_constants'); var server_constants = require('../tools/server_constants');
var {authenticate, auth_default} = require('../middleware/authenticate'); var { authenticate, authenticate_noerror, auth_default } = require('../middleware/authenticate');
var mongoose = require('mongoose').set('debug', false); var mongoose = require('mongoose').set('debug', false);
const Subscription = mongoose.model('subscribers'); const Subscription = mongoose.model('subscribers');
const _ = require('lodash'); const _ = require('lodash');
const {MyBacheca} = require('../models/mybacheca'); const { MyBacheca } = require('../models/mybacheca');
var {User} = require('../models/user'); var { User } = require('../models/user');
const { Reaction } = require('../models/reaction');
const globalTables = require('../tools/globalTables'); const globalTables = require('../tools/globalTables');
const {ObjectID} = require('mongodb'); const { ObjectID } = require('mongodb');
//GET orders //GET orders
router.post('/page', authenticate, function(req, res, next) { router.post('/page', authenticate_noerror, function (req, res, next) {
const {SendNotif} = require('../models/sendnotif'); const { SendNotif } = require('../models/sendnotif');
try { try {
let table = req.body.table; let table = req.body.table;
let id = req.body.id; let id = req.body.id;
let idapp = req.body.idapp; let idapp = req.body.idapp;
const username = req.user.username ? req.user.username : ''; let username = ''
if (req.user)
username = req.user.username ? req.user.username : '';
// Check if ìs a Notif to read if (username) {
const idnotif = req.body.idnotif ? req.body.idnotif : ''; // Check if ìs a Notif to read
SendNotif.setNotifAsRead(idapp, username, idnotif); const idnotif = req.body.idnotif ? req.body.idnotif : '';
SendNotif.setNotifAsRead(idapp, username, idnotif);
}
let mytable = null; let mytable = null;
if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) { if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) {
mytable = globalTables.getTableByTableName(table); mytable = globalTables.getTableByTableName(table);
} }
if (mytable) { if (mytable) {
return mytable.getMyRecById(idapp, id). return mytable.getMyRecById(idapp, id).
then((ris) => { then(async (ris) => {
if (ris) { // Se è un record singolo di tipo Reaction,
res.send(ris); // allora gli devo passare anche le liste degli utenti :
if (globalTables.isTableReaction(table)) {
// ...
// const myreaction = await Reaction.find({idapp, idrec: id}).lean();
// ris.myreaction = myreaction;
} else { };
res.status(400).send();
} if (ris) {
}).catch((e) => { res.send(ris);
console.error('Err', e);
res.status(400).send(e); } else {
}) res.status(400).send();
}
}).catch((e) => {
console.error('Err', e);
res.status(400).send(e);
})
} }
}catch (e) { } catch (e) {
console.error('/page', e); console.error('/page', e);
} }

View File

@@ -5,23 +5,23 @@ 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 } = require('../middleware/authenticate');
const mongoose = require('mongoose').set('debug', false); const mongoose = require('mongoose').set('debug', false);
const {User} = require('../models/user'); const { User } = require('../models/user');
const {MyGroup} = require('../models/mygroup'); const { MyGroup } = require('../models/mygroup');
const _ = require('lodash'); const _ = require('lodash');
const {ObjectID} = require('mongodb'); const { ObjectID } = require('mongodb');
async function getGroupRecAdminsInfo(idapp, data) { async function getGroupRecAdminsInfo(idapp, data) {
if (data && data.admins) { if (data && data.admins) {
for (const admin of data.admins) { for (const admin of data.admins) {
const myuser = await User.findOne({idapp, username: admin.username}, {'profile.img': 1}).lean(); const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
admin.profile = {img: myuser.profile.img}; admin.profile = { img: myuser.profile.img };
} }
} }
@@ -35,14 +35,33 @@ router.post('/load', authenticate, async (req, res) => {
try { try {
const {SendNotif} = require('../models/sendnotif'); const { SendNotif } = require('../models/sendnotif');
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
// Check if ìs a Notif to read // Check if ìs a Notif to read
const idnotif = req.body['idnotif'] ? req.body['idnotif'] : ''; const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif); SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
const whatshow = MyGroup.getWhatToShow(idapp, req.user.username); const whatshow = MyGroup.getWhatToShow(idapp, req.user.username);
let data = await MyGroup.findOne({idapp, groupname}, whatshow).lean(); let data = await MyGroup.findOne({ idapp, groupname }, whatshow).lean();
/*
if (data.mycircuits) {
for (let i = 0; i < data.mycircuits.length; i++) {
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
data.mycircuits[i] = mycirc;
}
}
*/
if (data.mycircuits) {
for (let i = 0; i < data.mycircuits.length; i++) {
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
if (mycirc)
data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname);
}
}
let cities = []; let cities = [];
if (data) { if (data) {
@@ -57,16 +76,16 @@ router.post('/load', authenticate, async (req, res) => {
const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username); const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username);
const users_in_group = await User.find( const users_in_group = await User.find(
{ {
idapp, idapp,
'profile.mygroups': { 'profile.mygroups': {
$elemMatch: {groupname: {$eq: groupname}}, $elemMatch: { groupname: { $eq: groupname } },
},
}, },
whatshowUsers, },
whatshowUsers,
).lean(); ).lean();
res.send({mygroup: data, users_in_group, cities}); res.send({ mygroup: data, users_in_group, cities });
} catch (e) { } catch (e) {
console.error('Error in MyGroups', e); console.error('Error in MyGroups', e);

View File

@@ -47,13 +47,6 @@ const newsletter = [
listUniqueId: '', listUniqueId: '',
mailchimpApiKey: '' mailchimpApiKey: ''
}, },
{
name: 'MandalaSolidale',
mailchimpInstance: '',
listUniqueId: '',
mailchimpApiKey: ''
}
]; ];
async function AddMailingList(locale, idapp, user, settomailchimp, sendnews) { async function AddMailingList(locale, idapp, user, settomailchimp, sendnews) {

View File

@@ -0,0 +1,127 @@
const express = require('express');
const router = express.Router();
const { Reaction } = require('../models/reaction');
const { User } = require('../models/user');
const Hours = require('../models/hours');
const { ObjectID } = require('mongodb');
const sendemail = require('../sendemail');
const { Settings } = require('../models/settings');
const { SendNotif } = require('../models/sendnotif');
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const server_constants = require('../tools/server_constants');
const telegrambot = require('../telegram/telegrambot');
const _ = require('lodash');
const reg = require('../reg/registration');
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
const TypedError = require('../modules/ErrorHandler');
const globalTables = require('../tools/globalTables');
const mongoose = require('mongoose').set('debug', false);
router.post('/cmd', authenticate_noerror, async (req, res) => {
const mydata = req.body.mydata;
const idapp = req.body.idapp;
const cmd = req.body.cmd;
const id = req.body.id;
const tab = req.body.tab;
const num = req.body.num;
const value = req.body.value;
try {
const table = tools.getTableByNumTab(tab);
const mytable = globalTables.getTableByTableName(table);
let username = '';
if (req.user) {
username = req.user.username;
} else {
return res.send({ state: 0, record: null });
}
let ris = null;
let record = null;
const { User } = require('../models/user');
let objtoupdate = {};
if (cmd === shared_consts.CMD_REACTION.SET_FAVORITE) {
if (tab) {
if (value) {
ris = await Reaction.addFavorite(req, idapp, username, id, tab);
} else {
ris = await Reaction.removeFavorite(idapp, username, id, tab);
}
}
} else if (cmd === shared_consts.CMD_REACTION.SET_BOOKMARK) {
if (tab) {
if (value)
ris = await Reaction.addBookmark(req, idapp, username, id, tab);
else
ris = await Reaction.removeBookmark(idapp, username, id, tab);
}
} else if (cmd === shared_consts.CMD_REACTION.SET_ATTEND) {
if (tab) {
if (value)
ris = await Reaction.addAttend(req, idapp, username, id, tab, num);
else
ris = await Reaction.removeAttend(idapp, username, id, tab);
}
} else if (cmd === shared_consts.CMD_REACTION.SET_SEEN) {
if (tab) {
if (value) {
ris = await Reaction.addSeen(req, idapp, username, id, tab);
}
const tabtofind = tools.getNumTabByTable('mybachecas');
if (tab === tabtofind) {
const { MyBacheca } = require('../models/mybacheca');
record = await MyBacheca.getCompleteRecord(idapp, id);
}
}
}
let state = (value && ris && ris.ok === 1) ? 1 : ((!value && ris && ris.ok === 1) ? -1 : 0);
const risreac = await Reaction.calcReactions(idapp, id, tab);
if (risreac) {
delete risreac._id;
objtoupdate = risreac;
}
if (mytable) {
ris = await mytable.updateOne({ _id: id }, {
$set: objtoupdate,
})
}
return res.send({ state, record });
} catch (e) {
res.status(400).send();
res.send({ code: server_constants.RIS_CODE_ERR, msg: e, state: null, record: null });
console.log(e.message);
}
});
module.exports = router;

View File

@@ -10,7 +10,7 @@ const { User } = require('../models/user');
const { Operator } = require('../models/operator'); const { Operator } = require('../models/operator');
const { SendMsg } = require('../models/sendmsg'); const { SendMsg } = require('../models/sendmsg');
const {SendNotif} = require('../models/sendnotif'); const { SendNotif } = require('../models/sendnotif');
const { ObjectID } = require('mongodb'); const { ObjectID } = require('mongodb');
@@ -35,7 +35,7 @@ router.post('/', authenticate, (req, res) => {
User.setOnLine(req.user.idapp, req.user.username); User.setOnLine(req.user.idapp, req.user.username);
} }
const check = tools.checkUserOk(myrecmsg.origin.username, req.user.username, res); const check = tools.checkUserOk(myrecmsg.origin, req.user.username, res);
if (check.exit) return check.ret; if (check.exit) return check.ret;
// console.log('fieldtochange', fieldtochange); // console.log('fieldtochange', fieldtochange);
@@ -49,26 +49,37 @@ router.post('/', authenticate, (req, res) => {
return SendMsg.findById(idobj) return SendMsg.findById(idobj)
.then(async (recmsg) => { .then(async (recmsg) => {
const myrecsend = new SendNotif(
{
title: recmsg.source.infoevent,
sender: recmsg.origin,
dest: recmsg.dest,
openUrl: '',
});
// Add this field because I don't want to add into the database // Add this field because I don't want to add into the database
recmsg.source.infoevent = body.source.infoevent; // myrecsend.source.infoevent = body.source.infoevent;
recmsg.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS; myrecsend.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS;
recmsg.typeid = shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC; myrecsend.typeid = shared_consts.TypeNotifs.ID_EVENTS_SEND_MSG;
myrecsend.msg = recmsg.message;
let myid = recmsg._id;
// ##Todo !! DA SISTEMARE !!! // ##Todo !! DA SISTEMARE !!!
return await SendNotif.saveAndSendNotif(recmsg, req, res).then((out) => { return await SendNotif.saveAndSendNotif(myrecsend, req, res).then((out) => {
if (out) if (out)
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id }); return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: myid });
else else
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}) })
}); });
}).catch((e) => { }).catch((e) => {
console.log(e.message); console.error(e.message);
// res.status(400).send(e); // res.status(400).send(e);
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); // return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}) })
let fine = '';
}); });
router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => { router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {

View File

@@ -144,7 +144,7 @@ router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
return res.status(404).send({code: server_constants.RIS_CODE_NOT_MY_USERNAME}); return res.status(404).send({code: server_constants.RIS_CODE_NOT_MY_USERNAME});
} }
return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp).then(async (arrnotif) => { return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp, shared_consts.LIMIT_NOTIF_FOR_USER).then(async (arrnotif) => {
// const wait = new Promise((resolve, reject) => { // const wait = new Promise((resolve, reject) => {
// setTimeout(() => { // setTimeout(() => {

View File

@@ -7,6 +7,8 @@ const server_constants = require('../tools/server_constants');
const { authenticate } = require('../middleware/authenticate'); const { authenticate } = require('../middleware/authenticate');
const { MyGroup } = require('../models/mygroup');
const mongoose = require('mongoose').set('debug', false) const mongoose = require('mongoose').set('debug', false)
const { User } = require('../models/user'); const { User } = require('../models/user');
@@ -50,6 +52,10 @@ router.post('/load', async (req, res) => {
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),
receiveRislist: await User.getReceiveRISUsers(idapp),
// receiveRislist: await User.find({idapp}).limit(20),
receiveRislistgroup: await MyGroup.getReceiveRISGroups(idapp),
strettelist: await User.getBestStretteDiManoUsers(idapp),
checkuser: await User.checkUser(idapp, username), checkuser: await User.checkUser(idapp, username),
// navi_partite: await Nave.getNaviPartite(idapp), // navi_partite: await Nave.getNaviPartite(idapp),
// navi_in_partenza: await Nave.getNaviInPartenza(idapp), // navi_in_partenza: await Nave.getNaviInPartenza(idapp),

View File

@@ -38,6 +38,8 @@ router.post('/', authenticate, async (req, res) => {
subscriptionModel.access = req.body.others.access; subscriptionModel.access = req.body.others.access;
subscriptionModel.browser = req.get('User-Agent'); subscriptionModel.browser = req.get('User-Agent');
// console.log('subscriptionModel.browser', subscriptionModel.browser);
// Find if already exist // Find if already exist
await Subscription.findOne({ await Subscription.findOne({
userId: subscriptionModel.userId, userId: subscriptionModel.userId,

View File

@@ -0,0 +1,99 @@
const express = require('express');
const router = express.Router();
const tools = require('../tools/general');
const server_constants = require('../tools/server_constants');
const { authenticate } = require('../middleware/authenticate');
const mongoose = require('mongoose').set('debug', false);
const { User } = require('../models/user');
const { MyGroup } = require('../models/mygroup');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
async function getGroupRecAdminsInfo(idapp, data) {
if (data && data.admins) {
for (const admin of data.admins) {
const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
admin.profile = { img: myuser.profile.img };
}
}
return data;
}
router.post('/load', authenticate, async (req, res) => {
const idapp = req.body.idapp;
const groupname = req.body.groupname;
const usernameOrig = req.user.username;
try {
const { SendNotif } = require('../models/sendnotif');
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
// Check if ìs a Notif to read
const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
const whatshow = MyGroup.getWhatToShow(idapp, req.user.username);
let data = await MyGroup.findOne({ idapp, groupname }, whatshow).lean();
/*
if (data.mycircuits) {
for (let i = 0; i < data.mycircuits.length; i++) {
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
data.mycircuits[i] = mycirc;
}
}
*/
if (data.mycircuits) {
for (let i = 0; i < data.mycircuits.length; i++) {
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
if (mycirc)
data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname);
}
}
let cities = [];
if (data) {
cities = await MyGroup.extractCitiesName(idapp, data._id);
if (cities && cities.length > 0) {
cities = cities[0].mycities;
}
}
data = await getGroupRecAdminsInfo(idapp, data);
const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username);
const users_in_group = await User.find(
{
idapp,
'profile.mygroups': {
$elemMatch: { groupname: { $eq: groupname } },
},
},
whatshowUsers,
).lean();
res.send({ mygroup: data, users_in_group, cities });
} catch (e) {
console.error('Error in MyGroups', e);
return res.status(400).send(e);
}
const ris = null;
});
module.exports = router;

File diff suppressed because it is too large Load Diff

View File

@@ -159,14 +159,6 @@ module.exports = {
transport_preview.sendMail(mailOptions).then(console.log).catch(console.error); transport_preview.sendMail(mailOptions).then(console.log).catch(console.error);
} }
}, },
// getHostByIdApp: function (idapp) {
// if (idapp === 1) {
// let siteport = (process.env.PORT_APP1 !== "0") ? (':' + process.env.PORT_APP1) : "";
// return process.env.URLBASE_APP1 + siteport;
// } else {
// return ""
// }
// },
getlinkReg: function(idapp, idreg) { getlinkReg: function(idapp, idreg) {
const strlinkreg = tools.getHostByIdApp(idapp) + process.env.LINKVERIF_REG + `/?idapp=${idapp}&idlink=${idreg}`; const strlinkreg = tools.getHostByIdApp(idapp) + process.env.LINKVERIF_REG + `/?idapp=${idapp}&idlink=${idreg}`;
@@ -203,7 +195,7 @@ module.exports = {
let aportador = mylocalsconf.aportador_solidario ? ' (da ' + mylocalsconf.aportador_solidario + ')' : ''; let aportador = mylocalsconf.aportador_solidario ? ' (da ' + mylocalsconf.aportador_solidario + ')' : '';
const numutenti = await User.getNumUsers(mylocalsconf.idapp); const numutenti = await User.getNumUsers(mylocalsconf.idapp);
tools.sendNotifToAdmin('++ [' + numutenti + '] ' + nometot + aportador); tools.sendNotifToAdmin(mylocalsconf.idapp, true, '++Reg [' + numutenti + '] ' + nometot + aportador);
} }
// if (tools.isManagAndAdminDifferent(idapp)) { // if (tools.isManagAndAdminDifferent(idapp)) {
@@ -235,7 +227,7 @@ module.exports = {
await telegrambot.notifyIscrizioneToTelegram(telegrambot.phase.ISCRIZIONE_CONACREIS, mylocalsconf, 'MSG_ISCRITTO_CONACREIS'); await telegrambot.notifyIscrizioneToTelegram(telegrambot.phase.ISCRIZIONE_CONACREIS, mylocalsconf, 'MSG_ISCRITTO_CONACREIS');
tools.sendNotifToAdmin('Iscrizione Conacreis : ' + mylocalsconf.name + ' ' + mylocalsconf.surname + ' (' + mylocalsconf.username + ')'); tools.sendNotifToAdmin(idapp, true, 'Iscrizione Conacreis : ' + mylocalsconf.name + ' ' + mylocalsconf.surname + ' (' + mylocalsconf.username + ')');
if (tools.isManagAndAdminDifferent(idapp)) { if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/iscrizione_conacreis/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); this.sendEmail_base('admin/iscrizione_conacreis/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
@@ -268,7 +260,7 @@ module.exports = {
await telegrambot.notifyIscrizioneToTelegram(telegrambot.phase.ISCRIZIONE_ARCADEI, mylocalsconf, 'MSG_ISCRITTO_ARCADEI'); await telegrambot.notifyIscrizioneToTelegram(telegrambot.phase.ISCRIZIONE_ARCADEI, mylocalsconf, 'MSG_ISCRITTO_ARCADEI');
tools.sendNotifToAdmin('Iscrizione Arcadei : ' + mylocalsconf.name + ' ' + mylocalsconf.surname + ' (' + mylocalsconf.username + ')'); tools.sendNotifToAdmin(idapp, true, 'Iscrizione Arcadei : ' + mylocalsconf.name + ' ' + mylocalsconf.surname + ' (' + mylocalsconf.username + ')');
if (tools.isManagAndAdminDifferent(idapp)) { if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/iscrizione_arcadei/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); this.sendEmail_base('admin/iscrizione_arcadei/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
@@ -279,6 +271,7 @@ module.exports = {
}, },
sendEmail_RequestNewPassword: async function(lang, user, emailto, idapp, tokenforgot, tokenforgot_code) { sendEmail_RequestNewPassword: async function(lang, user, emailto, idapp, tokenforgot, tokenforgot_code) {
console.log('sendEmail_RequestNewPassword');
let mylocalsconf = { let mylocalsconf = {
idapp, idapp,
@@ -306,6 +299,7 @@ module.exports = {
locale: lang, locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp), nomeapp: tools.getNomeAppByIdApp(idapp),
emailto: emailto, emailto: emailto,
msgbooking: '',
participants: '', participants: '',
participantsLunch: '', participantsLunch: '',
participantsDinner: '', participantsDinner: '',
@@ -354,6 +348,10 @@ module.exports = {
msgtelegram += '\n'; msgtelegram += '\n';
if (recbooking.msgbooking) {
mylocalsconf.msgbooking = 'Messaggio: ' + recbooking.msgbooking.toString()
msgtelegram += mylocalsconf.msgbooking + '\n';
}
if (recbooking.numpeople > 0) { if (recbooking.numpeople > 0) {
mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + tools.getres__('partecipanti', res); mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + tools.getres__('partecipanti', res);
msgtelegram += mylocalsconf.participants + '\n'; msgtelegram += mylocalsconf.participants + '\n';

View File

@@ -1,7 +1,10 @@
require('./config/config'); require('./config/config');
require('./config/config');
// console.log(" lodash"); // console.log(" lodash");
console.log(process.versions);
const _ = require('lodash'); const _ = require('lodash');
// console.log(" cors"); // console.log(" cors");
const cors = require('cors'); const cors = require('cors');
@@ -9,6 +12,8 @@ const cors = require('cors');
// console.log(" 2) fs"); // console.log(" 2) fs");
const fs = require('fs'); const fs = require('fs');
const NUOVO_METODO_TEST = true;
const server_constants = require('./tools/server_constants'); const server_constants = require('./tools/server_constants');
//const throttle = require('express-throttle-bandwidth'); //const throttle = require('express-throttle-bandwidth');
@@ -23,49 +28,33 @@ const bodyParser = require('body-parser');
const path = require('path'); const path = require('path');
const cron = require('node-cron'); const cron = require('node-cron');
console.log('Starting mongoose...');
require('./db/mongoose'); require('./db/mongoose');
const {Settings} = require('./models/settings'); // console.log('Starting pem...');
// const pem = require('pem')
const { Settings } = require('./models/settings');
// test // test
const i18n = require('i18n'); const i18n = require('i18n');
let credentials = null;
// OBTAIN // OBTAIN
// https://www.psclistens.com/insight/blog/enabling-a-nodejs-ssl-webserver-using-let-s-encrypt-pem-certificates/ // https://www.psclistens.com/insight/blog/enabling-a-nodejs-ssl-webserver-using-let-s-encrypt-pem-certificates/
if ((process.env.NODE_ENV === 'production') ||
(process.env.NODE_ENV === 'test')) {
var privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8');
var certificate = fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8');
var credentials = {
key: privateKey,
cert: certificate,
ca: [
fs.readFileSync(process.env.PATH_SSL_ROOT_PEM, 'utf8'),
fs.readFileSync(process.env.PATH_SSL_CHAIN_PEM, 'utf8'),
],
};
var https = require('https');
} else {
if (process.env.HTTPS_LOCALHOST === "true") {
var privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8');
var certificate = fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8');
var 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',
};
var https = require('https');
} else { if ((process.env.NODE_ENV === 'production')) {
var http = require('http'); console.log('*** AMBIENTE DI PRODUZIONE !!!!')
} } else if (process.env.NODE_ENV === 'test') {
console.log('*** ### AMBIENTE DI TEST ')
} }
console.log('DB: ' + process.env.DATABASE); console.log('DB: ' + process.env.DATABASE);
// console.log("PORT: " + port); // console.log("PORT: " + port);
// console.log("MONGODB_URI: " + process.env.MONGODB_URI); // console.log("MONGODB_URI: " + process.env.MONGODB_URI);
@@ -82,17 +71,17 @@ var mongoose = require('mongoose').set('debug', false);
mongoose.set('debug', false); mongoose.set('debug', false);
const {CfgServer} = require('./models/cfgserver'); const { CfgServer } = require('./models/cfgserver');
const {ObjectID} = require('mongodb'); const { ObjectID } = require('mongodb');
const populate = require('./populate/populate'); const populate = require('./populate/populate');
const {Circuit} = require('./models/circuit'); const { Circuit } = require('./models/circuit');
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');
require('./models/project'); require('./models/project');
@@ -123,8 +112,10 @@ myLoad().then(ris => {
const projects_router = require('./router/projects_router'); const projects_router = require('./router/projects_router');
const report_router = require('./router/report_router'); const report_router = require('./router/report_router');
const users_router = require('./router/users_router'); const users_router = require('./router/users_router');
const reactions_router = require('./router/reactions_router');
const mygroups_router = require('./router/mygroups_router'); const mygroups_router = require('./router/mygroups_router');
const circuits_router = require('./router/circuits_router'); const circuits_router = require('./router/circuits_router');
const accounts_router = require('./router/accounts_router');
const iscrittiConacreis_router = require('./router/iscrittiConacreis_router'); const iscrittiConacreis_router = require('./router/iscrittiConacreis_router');
const iscrittiArcadei_router = require('./router/iscrittiArcadei_router'); const iscrittiArcadei_router = require('./router/iscrittiArcadei_router');
const site_router = require('./router/site_router'); const site_router = require('./router/site_router');
@@ -136,18 +127,18 @@ myLoad().then(ris => {
const mygoods_router = require('./router/mygoods_router'); const mygoods_router = require('./router/mygoods_router');
const mygen_router = require('./router/mygen_router'); const mygen_router = require('./router/mygen_router');
const {MyEvent} = require('./models/myevent'); const { MyEvent } = require('./models/myevent');
app.use(express.static('views')); app.use(express.static('views'));
// app.use(express.static(path.join(__dirname, 'client'))); // app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json()); app.use(bodyParser.json());
// app.set('view engine', 'pug'); // app.set('view engine', 'pug');
// Set static folder // Set static folder
// app.use(express.static(path.join(__dirname, 'public'))); // app.use(express.static(path.join(__dirname, 'public')));
i18n.configure({ i18n.configure({
locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'], locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'],
@@ -166,10 +157,13 @@ myLoad().then(ris => {
app.use(bodyParser.json()); app.use(bodyParser.json());
// app.use(express.cookieParser()); // app.use(express.cookieParser());
app.use(i18n.init); app.use(i18n.init);
// Use Routes console.log('Use Routes \...');
// Use Routes
app.use('/', index_router); app.use('/', index_router);
app.use('/subscribe', subscribe_router); app.use('/subscribe', subscribe_router);
app.use('/sendmsg', sendmsg_router); app.use('/sendmsg', sendmsg_router);
@@ -184,8 +178,10 @@ myLoad().then(ris => {
app.use('/test', test_router); app.use('/test', test_router);
app.use('/projects', projects_router); app.use('/projects', projects_router);
app.use('/users', users_router); app.use('/users', users_router);
app.use('/reactions', reactions_router);
app.use('/mygroup', mygroups_router); app.use('/mygroup', mygroups_router);
app.use('/circuit', circuits_router); app.use('/circuit', circuits_router);
app.use('/account', accounts_router);
app.use('/iscritti_conacreis', iscrittiConacreis_router); app.use('/iscritti_conacreis', iscrittiConacreis_router);
app.use('/iscritti_arcadei', iscrittiArcadei_router); app.use('/iscritti_arcadei', iscrittiArcadei_router);
app.use('/report', report_router); app.use('/report', report_router);
@@ -198,24 +194,24 @@ myLoad().then(ris => {
app.use('/mygoods', mygoods_router); app.use('/mygoods', mygoods_router);
app.use('/mygen', mygen_router); app.use('/mygen', mygen_router);
// 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) {
// var err = new Error('Not Found'); // var err = new Error('Not Found');
// err.status = 404; // err.status = 404;
// next(err); // next(err);
// }); // });
// app.set('views', path.join(__dirname, 'views')); // app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug'); // app.set('view engine', 'pug');
// 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();
res.status(err.status || 500).send({error: err.message}); res.status(err.status || 500).send({ error: err.message });
// res.render('error', { // res.render('error', {
// message: err.message, // message: err.message,
// error: err // error: err
@@ -224,28 +220,86 @@ myLoad().then(ris => {
} }
// require('./telegram/telegrambot'); // require('./telegram/telegrambot');
// *** DB CONNECTIONS *** // *** DB CONNECTIONS ***
// mysql_func.mySqlConn_Shen.connect((err) => { // mysql_func.mySqlConn_Shen.connect((err) => {
// if (!err) // if (!err)
// console.log('DB connection to Shen Database succeded.'); // console.log('DB connection to Shen Database succeded.');
// else // else
// console.log('DB connection to Shen Database FAILED \n Error: ' + JSON.stringify(err, undefined, 2)); // console.log('DB connection to Shen Database FAILED \n Error: ' + JSON.stringify(err, undefined, 2));
// }); // });
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.HTTPS_LOCALHOST === "true") { (process.env.NODE_ENV === 'test')) {
var httpsServer = https.createServer(credentials, app);
console.log('httpsServer: port ', port); const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
httpsServer.listen(port); const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
const privateKey = fs.readFileSync(keyStream, "utf8");
const certificate = fs.readFileSync(certificateStream, "utf8");
if (NUOVO_METODO_TEST) {
credentials = {
key: privateKey,
cert: certificate,
};
} else {
credentials = {
key: privateKey,
cert: certificate,
ca: [
fs.readFileSync(process.env.PATH_SSL_ROOT_PEM, 'utf8'),
fs.readFileSync(process.env.PATH_SSL_CHAIN_PEM, 'utf8'),
],
};
}
var https = require('https');
} else {
if (process.env.HTTPS_LOCALHOST === "true") {
var privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8');
var 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',
};
var https = require('https');
} else {
var http = require('http');
}
}
if ((process.env.NODE_ENV === 'production') ||
(process.env.NODE_ENV === 'test') || process.env.HTTPS_LOCALHOST === "true") {
if (false) {
/*pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => {
if (err) {
throw err
}
const httpsServer = https.createServer({ key: keys.clientKey, cert: keys.certificate }, (req, res) => {
res.end('o hai!')
}).listen(port)
}) */
} else {
const httpsServer = https.createServer(credentials, app);
console.log('httpsServer: port ', port);
httpsServer.listen(port);
}
} else { } else {
console.log('httpServer: port ', port); console.log('httpServer: port ', port);
var httpServer = http.createServer(app); const httpServer = http.createServer(app);
httpServer.listen(port); httpServer.listen(port);
} }
@@ -304,17 +358,17 @@ async function mystart() {
faitest(); faitest();
// ----------------- MAILCHIMP ----- // ----------------- MAILCHIMP -----
const querystring = require('querystring'); const querystring = require('querystring');
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('https://login.mailchimp.com/oauth2/authorize?' +
querystring.stringify({ querystring.stringify({
'response_type': 'code', 'response_type': 'code',
'client_id': mailchimpClientId, 'client_id': mailchimpClientId,
'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback', 'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback',
})); }));
}); });
} }
@@ -350,7 +404,7 @@ async function mycron_30min() {
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) {
// ... // ...
@@ -359,22 +413,22 @@ async function mycron_30min() {
} }
function testmsgwebpush() { function testmsgwebpush() {
const {User} = require('./models/user'); const { User } = require('./models/user');
// console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1)); // console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1));
// console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2)); // console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2));
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.sendNotificationToUser(user._id, 'Server',
'Il Server è Ripartito', '/', '', 'server', []).then(ris => { '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
} }
}); });
} }
} }
}); });
@@ -402,16 +456,16 @@ cron.schedule('*/60 * * * *', async () => {
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) => {
}); });
} }
} }
@@ -425,13 +479,13 @@ async function inizia() {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
await telegrambot.sendMsgTelegram(tools.FREEPLANET, await telegrambot.sendMsgTelegram(tools.FREEPLANET,
telegrambot.ADMIN_USER_SERVER, telegrambot.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 {
@@ -445,7 +499,7 @@ async function inizia() {
*/ */
console.log(process.versions);
} catch (e) { } catch (e) {
@@ -468,7 +522,7 @@ async function inizia() {
// } // }
async function estraiImmagini(table) { async function estraiImmagini(table) {
const {User} = require('./models/user'); const { User } = require('./models/user');
let idapp = '13'; let idapp = '13';
@@ -483,7 +537,7 @@ async function estraiImmagini(table) {
console.log('INIZIO - estraiImmagini', table); console.log('INIZIO - estraiImmagini', table);
arrlist = await mytable.find({idapp}).lean(); arrlist = await mytable.find({ idapp }).lean();
let file = ''; let file = '';
let filetocheck = ''; let filetocheck = '';
@@ -498,7 +552,7 @@ async function estraiImmagini(table) {
} }
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) {
const myphotos = rec.photos; const myphotos = rec.photos;
@@ -527,7 +581,7 @@ async function estraiImmagini(table) {
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;
@@ -587,7 +641,7 @@ async function faitest() {
} }
if (testfind) { if (testfind) {
const {City} = require('./models/city'); const { City } = require('./models/city');
let miacity = 'roma'; let miacity = 'roma';
const ris = await City.findByCity(miacity); const ris = await City.findByCity(miacity);
@@ -595,7 +649,7 @@ async function faitest() {
console.log('ris', ris); console.log('ris', ris);
} }
const {User} = require('./models/user'); const { User } = require('./models/user');
if (false) { if (false) {
let myuser = await User.findOne({ let myuser = await User.findOne({
@@ -617,13 +671,13 @@ async function faitest() {
}); });
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;
@@ -653,12 +707,12 @@ async function faitest() {
}; };
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);
} }
} }
} }
module.exports = {app}; module.exports = { app };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -8,52 +8,53 @@ require('../config/config');
require('../models/subscribers'); require('../models/subscribers');
const {ObjectID} = require('mongodb'); const { ObjectID } = require('mongodb');
const {User} = require('../models/user'); const { User } = require('../models/user');
const {MyGroup} = require('../models/mygroup'); const { MyGroup } = require('../models/mygroup');
const {Booking} = require('../models/booking'); const { Booking } = require('../models/booking');
const {Operator} = require('../models/operator'); const { Operator } = require('../models/operator');
const {Where} = require('../models/where'); const { Where } = require('../models/where');
const {MyEvent} = require('../models/myevent'); const { MyEvent } = require('../models/myevent');
const {Contribtype} = require('../models/contribtype'); const { Reaction } = require('../models/reaction');
const {PaymentType} = require('../models/paymenttype'); const { Contribtype } = require('../models/contribtype');
const {Discipline} = require('../models/discipline'); const { PaymentType } = require('../models/paymenttype');
const {Skill} = require('../models/skill'); const { Discipline } = require('../models/discipline');
const {Good} = require('../models/good'); const { Skill } = require('../models/skill');
const {SubSkill} = require('../models/subskill'); const { Good } = require('../models/good');
const {MySkill} = require('../models/myskill'); const { SubSkill } = require('../models/subskill');
const {MyGood} = require('../models/mygood'); const { MySkill } = require('../models/myskill');
const {MyBacheca} = require('../models/mybacheca'); const { MyGood } = require('../models/mygood');
const {MyHosp} = require('../models/myhosp'); const { MyBacheca } = require('../models/mybacheca');
const {StatusSkill} = require('../models/statusSkill'); const { MyHosp } = require('../models/myhosp');
const {City} = require('../models/city'); const { StatusSkill } = require('../models/statusSkill');
const {Province} = require('../models/province'); const { City } = require('../models/city');
const {Sector} = require('../models/sector'); const { Province } = require('../models/province');
const {SectorGood} = require('../models/sectorgood'); const { Sector } = require('../models/sector');
const {CatGrp} = require('../models/catgrp'); const { SectorGood } = require('../models/sectorgood');
const {Level} = require('../models/level'); const { CatGrp } = require('../models/catgrp');
const {AdType} = require('../models/adtype'); const { Level } = require('../models/level');
const {AdTypeGood} = require('../models/adtypegood'); const { AdType } = require('../models/adtype');
const {Circuit} = require('../models/circuit'); const { AdTypeGood } = require('../models/adtypegood');
const {Account} = require('../models/account'); const { Circuit } = require('../models/circuit');
const {Movement} = require('../models/movement'); const { Account } = require('../models/account');
const { Movement } = require('../models/movement');
const Pickup = require('../models/pickup'); 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 {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 {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');
const {SendMsg} = require('../models/sendmsg'); const { SendMsg } = require('../models/sendmsg');
const {Permission} = require('../models/permission'); const { Permission } = require('../models/permission');
const {MsgTemplate} = require('../models/msg_template'); const { MsgTemplate } = require('../models/msg_template');
const {Graduatoria} = require('../models/graduatoria'); const { Graduatoria } = require('../models/graduatoria');
const Product = require('../models/product'); const Product = require('../models/product');
const Producer = require('../models/producer'); const Producer = require('../models/producer');
const Cart = require('../models/cart'); const Cart = require('../models/cart');
@@ -65,7 +66,7 @@ const Site = require('../models/site');
const IscrittiConacreis = require('../models/iscrittiConacreis'); const IscrittiConacreis = require('../models/iscrittiConacreis');
const IscrittiArcadei = require('../models/iscrittiArcadei'); const IscrittiArcadei = require('../models/iscrittiArcadei');
const Group = require('../models/group'); const Group = require('../models/group');
const {Todo} = require('../models/todo'); const { Todo } = require('../models/todo');
const Hours = require('../models/hours'); const Hours = require('../models/hours');
const Order = require('../models/order'); const Order = require('../models/order');
const Cash = require('../models/cash'); const Cash = require('../models/cash');
@@ -79,6 +80,10 @@ const shared_consts = require('./shared_nodejs');
module.exports = { module.exports = {
isTableReaction(tablename) {
return shared_consts.TABLES_REACTIONS.includes(tablename);
},
getTableByTableName(tablename) { getTableByTableName(tablename) {
let mytable = ''; let mytable = '';
@@ -88,7 +93,7 @@ module.exports = {
mytable = MyGroup; mytable = MyGroup;
else if (tablename === 'tessitura') else if (tablename === 'tessitura')
mytable = Tessitura; mytable = Tessitura;
// else if (tablename === 'extralist') // else if (tablename === 'extralist')
// mytable = ExtraList; // mytable = ExtraList;
else if (tablename === 'bookings') else if (tablename === 'bookings')
mytable = Booking; mytable = Booking;
@@ -168,7 +173,7 @@ module.exports = {
mytable = MsgTemplate; mytable = MsgTemplate;
else if (tablename === 'navepersistente') else if (tablename === 'navepersistente')
mytable = NavePersistente; mytable = NavePersistente;
// else if (tablename === 'listaingressos') // else if (tablename === 'listaingressos')
// mytable = ListaIngresso; // mytable = ListaIngresso;
else if (tablename === 'graduatorias') else if (tablename === 'graduatorias')
mytable = Graduatoria; mytable = Graduatoria;
@@ -210,6 +215,8 @@ module.exports = {
mytable = Account; mytable = Account;
else if (tablename === 'movements') else if (tablename === 'movements')
mytable = Movement; mytable = Movement;
else if (tablename === 'reactions')
mytable = Reaction;
else if (shared_consts.TablePickup.includes(tablename)) else if (shared_consts.TablePickup.includes(tablename))
mytable = Pickup; mytable = Pickup;
//else if (shared_consts.TableCities.includes(tablename)) //else if (shared_consts.TableCities.includes(tablename))
@@ -227,6 +234,8 @@ module.exports = {
const sendemail = require('../sendemail'); const sendemail = require('../sendemail');
const { User } = require('../models/user');
/// ... rivedere il crea gruppo... notifiche... /// ... rivedere il crea gruppo... notifiche...
try { try {
if (!recnotif.typesend) { if (!recnotif.typesend) {
@@ -248,7 +257,10 @@ module.exports = {
usernameDest: recnotif.usernameDest ? recnotif.usernameDest : recnotif.dest, usernameDest: recnotif.usernameDest ? recnotif.usernameDest : recnotif.dest,
tag: recnotif.tag ? recnotif.tag : '', tag: recnotif.tag ? recnotif.tag : '',
actions: recnotif.actions ? recnotif.actions : [], actions: recnotif.actions ? recnotif.actions : [],
id: recnotif._id id: recnotif._id,
textaddTelegram: recnotif.textaddTelegram ? recnotif.textaddTelegram : '',
textcontent_Telegram: recnotif.textcontent_Telegram ? recnotif.textcontent_Telegram : '',
linkaddTelegram: recnotif.linkaddTelegram ? recnotif.linkaddTelegram : '',
}; };
if (tools.isBitActive(recnotif.typesend, shared_consts.MessageOptions.Notify_ByPushNotification) && this.checkifSendPushNotification) { if (tools.isBitActive(recnotif.typesend, shared_consts.MessageOptions.Notify_ByPushNotification) && this.checkifSendPushNotification) {
@@ -282,10 +294,12 @@ module.exports = {
} }
}, },
SendMsgToParam: async function(idapp, params) { SendMsgToParam: async function (idapp, params) {
try { try {
console.log('SendMsgToParam', params.typesend); // console.log('SendMsgToParam', params.typesend, params.typemsg);
const { User } = require('../models/user');
let textsent = ''; let textsent = '';
@@ -294,7 +308,7 @@ module.exports = {
if (params.typesend === 0) if (params.typesend === 0)
params.typesend = shared_consts.TypeSend.PUSH_NOTIFICATION; params.typesend = shared_consts.TypeSend.PUSH_NOTIFICATION;
let query = {idapp}; let query = { idapp };
let addquery = {}; let addquery = {};
let invia = true; let invia = true;
@@ -302,39 +316,39 @@ module.exports = {
if (params.typemsg === shared_consts.TypeMsg.SEND_TO_ALL) { if (params.typemsg === shared_consts.TypeMsg.SEND_TO_ALL) {
addquery = {}; addquery = {};
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_SOCI) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_SOCI) {
addquery = {'profile.socio': true}; addquery = { 'profile.socio': true };
} else if (params.typemsg === } else if (params.typemsg ===
shared_consts.TypeMsg.SEND_TO_SOCIO_RESIDENTE) { shared_consts.TypeMsg.SEND_TO_SOCIO_RESIDENTE) {
addquery = {'profile.socioresidente': true}; addquery = { 'profile.socioresidente': true };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_CONSIGLIO) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_CONSIGLIO) {
addquery = {'profile.consiglio': true}; addquery = { 'profile.consiglio': true };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_NON_SOCI) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_NON_SOCI) {
addquery = {'profile.socio': false}; addquery = { 'profile.socio': false };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_PAOLO) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_PAOLO) {
addquery = {username: 'paoloar77'}; addquery = { username: 'paoloar77' };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_USER) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_USER) {
addquery = {username: params.usernameDest}; addquery = { username: params.usernameDest };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) {
addquery = {username: params.usernameDest}; addquery = { username: params.usernameDest };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_TELEG_NO_USERNAME_TELEG) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_TELEG_NO_USERNAME_TELEG) {
addquery = { addquery = {
'profile.teleg_id': {$gt: 1}, 'profile.teleg_id': { $gt: 1 },
$or: [ $or: [
{'profile.username_telegram': {$exists: false}}, { 'profile.username_telegram': { $exists: false } },
{'profile.username_telegram': {$exists: true, $eq: ''}}], { 'profile.username_telegram': { $exists: true, $eq: '' } }],
}; };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_TELEG_NO_VERIF_BY_APORTADOR) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_TELEG_NO_VERIF_BY_APORTADOR) {
addquery = { addquery = {
'profile.teleg_id': {$gt: 1}, 'profile.teleg_id': { $gt: 1 },
'profile.username_telegram': {$exists: true}, 'profile.username_telegram': { $exists: true },
$expr: {$gt: [{$strLenCP: '$profile.username_telegram'}, 3]}, $expr: { $gt: [{ $strLenCP: '$profile.username_telegram' }, 3] },
'verified_by_aportador': {$exists: false}, 'verified_by_aportador': { $exists: false },
}; };
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_GROUP) { } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_GROUP) {
if (params.groupnameDest) { if (params.groupnameDest) {
addquery = { addquery = {
'profile.mygroups': { 'profile.mygroups': {
$elemMatch: {groupname: {$eq: params.groupnameDest}}, $elemMatch: { groupname: { $eq: params.groupnameDest } },
}, },
}; };
} else { } else {
@@ -344,7 +358,7 @@ module.exports = {
if (params.circuitnameDest) { if (params.circuitnameDest) {
addquery = { addquery = {
'profile.mycircuits': { 'profile.mycircuits': {
$elemMatch: {circuitname: {$eq: params.circuitnameDest}}, $elemMatch: { circuitname: { $eq: params.circuitnameDest } },
}, },
}; };
} else { } else {
@@ -358,28 +372,44 @@ module.exports = {
if (invia) { if (invia) {
const allquery = {...query, ...addquery}; const allquery = { ...query, ...addquery };
const arrusers = await User.find( const arrusers = await User.find(
allquery, allquery,
{ {
username: 1, username: 1,
'profile.teleg_id': 1, 'profile.teleg_id': 1,
}, 'profile.notifs': 1,
},
).lean(); ).lean();
for (const user of arrusers) { for (const user of arrusers) {
const mytitle = await tools.convertSpecialTags(user, params.title); const mytitle = await tools.convertSpecialTags(user, params.title);
const mycontent = await tools.convertSpecialTags(user, params.content); const mycontent = await tools.convertSpecialTags(user, params.textcontent_Telegram ? params.textcontent_Telegram : params.content);
let usernotifprofile = null;
if (user.profile.notifs)
usernotifprofile = user.profile.notifs.find((notif) => notif.dir === params.typenotif);
let risult = null; let risult = null;
if (params.sendreally) { let sendmsg = false;
if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) {
const myparam = {...params}; if (params.typenotif === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
risult = await tools.sendNotificationToUser(user._id, mytitle, mycontent, myparam.openUrl, myparam.openUrl2, myparam.tag, if (!usernotifprofile || (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_FAVORITE_ADDED))) {
sendmsg = true;
}
} else {
sendmsg = true;
}
if (sendmsg) {
if (params.sendreally) {
if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) {
const myparam = { ...params };
risult = await tools.sendNotificationToUser(user._id, mytitle, mycontent, myparam.openUrl, myparam.openUrl2, myparam.tag,
myparam.actions, myparam.id). myparam.actions, myparam.id).
then(ris => { then(ris => {
@@ -388,33 +418,35 @@ module.exports = {
console.error(e.message); console.error(e.message);
}); });
} }
if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) { if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) {
const telegid = user.profile.teleg_id; const telegid = user.profile.teleg_id;
text = tools.getContentNotifByParams(params, mycontent, shared_consts.TypeSend.TELEGRAM); text = tools.getContentNotifByParams(params, mycontent, shared_consts.TypeSend.TELEGRAM);
if (telegid > 0) { if (telegid > 0) {
risult = await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, text); risult = await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, text);
await tools.snooze(50); await tools.snooze(25);
textsent = risult.text; textsent = risult.text;
}
} }
} }
}
numrec++; numrec++;
if (params.sendreally && risult) { if (params.sendreally && risult) {
nummsgsent++; nummsgsent++;
} }
if (nummsgsent > 0 && (nummsgsent % 100) === 0) { if (nummsgsent > 0 && (nummsgsent % 100) === 0) {
console.log('Inviati ', nummsgsent, 'messaggi...'); console.log('Inviati ', nummsgsent, 'messaggi...');
}
} }
} }
} }
if (nummsgsent > 0) { if (nummsgsent > 0) {
console.log('FINE Invio Messaggi ! Inviati Totali: ', nummsgsent, 'su', numrec); if (nummsgsent != numrec && (numrec !== 1))
console.log('FINE Invio Messaggi ! Inviati Totali: ', nummsgsent, 'su', numrec);
} }
return { return {
@@ -429,7 +461,7 @@ module.exports = {
}, },
SendMsgToAll: async function(idapp, params) { SendMsgToAll: async function (idapp, params) {
params.typemsg = shared_consts.TypeMsg.SEND_TO_ALL; params.typemsg = shared_consts.TypeMsg.SEND_TO_ALL;
params.sendreally = true; params.sendreally = true;
@@ -438,4 +470,265 @@ module.exports = {
return await this.SendMsgToParam(idapp, params); return await this.SendMsgToParam(idapp, params);
}, },
replaceUsername: async function (idapp, search_username, replace_username) {
if (!search_username || !replace_username) {
return false;
}
try {
let ris = null;
console.log('replaceUsername = ', search_username, replace_username);
ris = await User.findOneAndUpdate({ idapp, username: search_username }, { $set: { username: replace_username } });
console.log('username result = ', ris);
tools.move(server_constants.DIR_UPLOAD + 'profile/' + search_username, server_constants.DIR_UPLOAD + 'profile/' + replace_username, function callback() {
console.log(' ... moved dir', server_constants.DIR_UPLOAD + 'profile/' + search_username, server_constants.DIR_UPLOAD + 'profile/' + replace_username);
});
ris = await User.findOneAndUpdate({ idapp, 'profile.username_telegram': search_username }, { $set: { 'profile.username_telegram': replace_username } });
console.log('profile.username_telegram result = ', ris);
ris = await User.updateMany({ idapp, aportador_iniziale: search_username },
{
$set:
{ aportador_iniziale: replace_username }
});
console.log('aportador_iniziale result = ', ris);
ris = await User.updateMany({ idapp, username_who_report: search_username },
{
$set:
{ username_who_report: replace_username }
});
console.log('username_who_report result = ', ris);
ris = await User.updateMany({ idapp, aportador_solidario: search_username },
{
$set:
{ aportador_solidario: replace_username }
});
console.log('aportador_solidario result = ', ris);
ris = await User.updateMany({ idapp, 'profile.friends.username': search_username },
{
$set:
{ 'profile.friends.$.username': replace_username }
});
console.log('friends.username result = ', ris);
ris = await User.updateMany({ idapp, 'profile.req_friends.username': search_username },
{
$set:
{ 'profile.req_friends.$.username': replace_username }
});
console.log('req_friends.username result = ', ris);
ris = await User.updateMany({ idapp, 'profile.handshake.username': search_username },
{
$set:
{ 'profile.handshake.$.username': replace_username }
});
console.log('handshake.username result = ', ris);
ris = await Circuit.updateMany({ idapp, 'admins.username': search_username },
{ $set: { 'admins.$.username': replace_username } });
console.log('Circuit.admins.username result = ', ris);
ris = await Circuit.updateMany({ idapp, 'req_users.username': search_username },
{ $set: { 'req_users.$.username': replace_username } });
console.log('Circuit.req_users.username result = ', ris);
ris = await Circuit.updateMany({ idapp, 'refused_users.username': search_username },
{ $set: { 'refused_users.$.username': replace_username } });
console.log('Circuit.refused_users.username result = ', ris);
ris = await Account.updateMany({ idapp, 'username': search_username },
{ $set: { 'username': replace_username } });
console.log('Account.username result = ', ris);
ris = await MyGroup.updateMany({ idapp, 'admins.username': search_username },
{ $set: { 'admins.$.username': replace_username } });
console.log('MyGroup.refused_users.username result = ', ris);
ris = await MyGroup.updateMany({ idapp, 'req_users.username': search_username },
{ $set: { 'req_users.$.username': replace_username } });
console.log('MyGroup.req_users.username result = ', ris);
// MyGroup.refused_users.username
ris = await MyGroup.updateMany({ idapp, 'refused_users.username': search_username },
{ $set: { 'refused_users.$.username': replace_username } });
console.log('MyGroup.refused_users.username result = ', ris);
} catch (e) {
console.error(e);
}
},
getNumFavoriteByIdObj: async function (idapp, numtab, id) {
const { Reaction } = require('../models/reaction');
let query = [
{
$match: {
idapp,
idrec: id,
},
},
{
$group:
{
_id: null,
count: {
$sum: {
$cond: {
if: { $ifNull: ["$fav", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
}
},
{ $project: { _id: 0 } }
];
try {
const [result] = await Reaction.aggregate(query);
return result ? result.count : 0;
} catch (err) {
return 0;
}
return 0;
},
getNumBookByIdObj: async function (idapp, numtab, id) {
const { Reaction } = require('../models/reaction');
let query = [
{
$match: {
idapp,
idrec: id,
},
},
{
$group:
{
_id: null,
count: {
$sum: {
$cond: {
if: { $ifNull: ["$book", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
}
},
{ $project: { _id: 0 } }
];
try {
const [result] = await Reaction.aggregate(query);
return result ? result.count : 0;
} catch (err) {
return 0;
}
return 0;
},
getNumAttendByIdObj: async function (idapp, numtab, id) {
const { Reaction } = require('../models/reaction');
let query = [
{
$match: {
idapp,
idrec: id,
},
},
{
$group:
{
_id: null,
count: {
$sum: {
$cond: {
if: { $ifNull: ["$attent", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
},
/*$sum:
{
$reduce: {
input: "$profile.attend",
initialValue: 0,
in: {
$add: ["$$value", "$$this.num"]
}
}
}*/
},
}
},
{ $project: { _id: 0 } }
];
try {
const [result] = await Reaction.aggregate(query);
return result ? result.count : 0;
} catch (err) {
return 0;
}
},
getUserCreatorByNumTabAndId: async function (idapp, id, numtab) {
try {
const table = tools.getTableByNumTab(numtab);
const mytable = this.getTableByTableName(table);
const { User } = require('../models/user');
if (mytable) {
const rec = await mytable.findOne({ _id: id, idapp }, { username: 1, lang: 1, userId: 1, descr: 1 });
if (rec) {
const recuser = await User.getUserById(idapp, rec.userId);
let numattend = await this.getNumAttendByIdObj(idapp, numtab, id);
let numfav = await this.getNumFavoriteByIdObj(idapp, numtab, id);
let numbook = await this.getNumBookByIdObj(idapp, numtab, id);
let exist = false;
if (table === shared_consts.TABLES_MYBACHECAS)
exist = numattend > 1;
else
exist = numfav > 1;
if (recuser)
return { userId: rec.userId, username: recuser.username, descr: rec.descr, id: rec._id, table, exist, numfav, numattend, numbook };
}
}
} catch (e) {
console.error('Err:', e);
}
return null;
},
}; };

View File

@@ -6,6 +6,7 @@ module.exports = Object.freeze({
RIS_CODE_EMAIL_ALREADY_VERIFIED: -5, RIS_CODE_EMAIL_ALREADY_VERIFIED: -5,
RIS_CODE_EMAIL_VERIFIED: 1, RIS_CODE_EMAIL_VERIFIED: 1,
RIS_CODE_REC_DUPLICATED_DESCR_CITY_USER: -110,
RIS_CODE_REC_ALREADY_EXIST_SYMBOL: -102, RIS_CODE_REC_ALREADY_EXIST_SYMBOL: -102,
RIS_CODE_REC_ALREADY_EXIST_CODE: -101, RIS_CODE_REC_ALREADY_EXIST_CODE: -101,
RIS_CODE_REC_ALREADY_EXIST_NAME: -100, RIS_CODE_REC_ALREADY_EXIST_NAME: -100,

View File

@@ -3,6 +3,7 @@ module.exports = {
CHECK_READ_GUIDELINES: 1, CHECK_READ_GUIDELINES: 1,
CHECK_SEE_VIDEO_PRINCIPI: 2, CHECK_SEE_VIDEO_PRINCIPI: 2,
}, },
LIMIT_NOTIF_FOR_USER: 200,
QUERYTYPE_MYGROUP: 1, QUERYTYPE_MYGROUP: 1,
QUERYTYPE_REFUSED_USER_GRP: 2, QUERYTYPE_REFUSED_USER_GRP: 2,
@@ -11,6 +12,10 @@ module.exports = {
QUERYTYPE_REFUSED_USER_CIRCUIT: 12, QUERYTYPE_REFUSED_USER_CIRCUIT: 12,
QUERYTYPE_LIST_MOVEMENTS: 15, QUERYTYPE_LIST_MOVEMENTS: 15,
QUERYTYPE_LIST_ALLMOVEMENTS: 16, QUERYTYPE_LIST_ALLMOVEMENTS: 16,
QUERYTYPE_LIST_MOVEMENTS_GROUPNAME: 17,
QUERYTYPE_LIST_MOVEMENTS_CONTOCOM: 18,
QUERYTYPE_GROUP_CIRCUIT: 20,
QUERYTYPE_REFUSED_GROUP_CIRCUIT: 22,
// --------------------- // ---------------------
FILTER_EXTRALIST_NOT_REGISTERED: 1, FILTER_EXTRALIST_NOT_REGISTERED: 1,
@@ -37,18 +42,22 @@ module.exports = {
FILTER_USER_NO_VERIFIED_APORTADOR: 2097152, FILTER_USER_NO_VERIFIED_APORTADOR: 2097152,
FILTER_USER_SI_TELEGRAM_ID: 4194304, FILTER_USER_SI_TELEGRAM_ID: 4194304,
FILTER_USER_WITHOUT_USERNAME_TELEGRAM: 8388608, FILTER_USER_WITHOUT_USERNAME_TELEGRAM: 8388608,
FILTER_USER_PROVINCE: 16777216,
OPTIONS_SEARCH_ONLY_FULL_WORDS: 1, OPTIONS_SEARCH_ONLY_FULL_WORDS: 1,
OPTIONS_SEARCH_USER_ONLY_FULL_WORDS: 2, OPTIONS_SEARCH_USER_ONLY_FULL_WORDS: 2,
OPTIONS_SEARCH_USER_ALL_WORDS: 4, OPTIONS_SEARCH_USER_ALL_WORDS: 4,
OPTIONS_ADD_COUNT_FAVORITE: 8,
FRIENDSCMD: { FRIENDSCMD: {
SETTRUST: 121, SETTRUST: 121,
REQFRIEND: 125, REQFRIEND: 125,
SETFRIEND: 132, SETFRIEND: 132,
SETHANDSHAKE: 133,
REMOVE_FROM_MYFRIENDS: 144, REMOVE_FROM_MYFRIENDS: 144,
REFUSE_REQ_FRIEND: 145, REFUSE_REQ_FRIEND: 145,
CANCEL_REQ_FRIEND: 146, CANCEL_REQ_FRIEND: 146,
REMOVE_FROM_MYHANDSHAKE: 147,
BLOCK_USER: 155, BLOCK_USER: 155,
UNBLOCK_USER: 156, UNBLOCK_USER: 156,
REPORT_USER: 158, REPORT_USER: 158,
@@ -70,8 +79,10 @@ module.exports = {
}, },
CIRCUITCMD: { CIRCUITCMD: {
CREATE: 1001,
REQ: 2000, REQ: 2000,
SET: 2001, SET: 2001,
SETFIDO: 2005,
REMOVE_FROM_MYLIST: 2144, REMOVE_FROM_MYLIST: 2144,
REFUSE_REQ: 2145, REFUSE_REQ: 2145,
CANCEL_REQ: 2146, CANCEL_REQ: 2146,
@@ -86,6 +97,10 @@ module.exports = {
SENDCOINS_REFUSE_SENT: 2222, SENDCOINS_REFUSE_SENT: 2222,
}, },
USERCMD: {
FAVORITE: 3001,
},
REPORT_FILT_RESP: 1, REPORT_FILT_RESP: 1,
REPORT_FILT_ATTIVITA: 2, REPORT_FILT_ATTIVITA: 2,
@@ -125,29 +140,58 @@ module.exports = {
TABLES_MYHOSPS: 'myhosps', TABLES_MYHOSPS: 'myhosps',
TABLES_MYGOODS: 'mygoods', TABLES_MYGOODS: 'mygoods',
TABLES_MYEVENTS: 'myevents', TABLES_MYEVENTS: 'myevents',
TABLES_CIRCUITS: 'circuits',
TABLES_MYGROUPS: 'mygroups',
MYTABS: [{ id: 0, table: 'none' },
{ id: 1, table: 'myskills' },
{ id: 2, table: 'mybachecas' },
{ id: 3, table: 'myhosps' },
{ id: 4, table: 'mygoods' },
{ id: 5, table: 'myevents' }],
CMD_REACTION: {
SET_FAVORITE: 1,
SET_BOOKMARK: 2,
SET_SEEN: 3,
SET_ATTEND: 4,
},
REACTIONS_FIELD:
{
numseen: 1,
numbook: 1,
numfav: 1,
numattend: 1,
},
TABLES_ENABLE_GETREC_BYID: ['mybachecas', 'myhosps', 'myskills', 'mygoods'], TABLES_ENABLE_GETREC_BYID: ['mybachecas', 'myhosps', 'myskills', 'mygoods'],
TABLES_REACTIONS: ['mybachecas', 'myhosps', 'myskills', 'mygoods'],
TABLES_USER_INCLUDE_MY: ['mygroups', 'circuits'], TABLES_USER_INCLUDE_MY: ['mygroups', 'circuits'],
TABLES_GETCOMPLETEREC: ['myskills', 'mybachecas', 'myhosps', 'mygoods'], TABLES_GETCOMPLETEREC: ['myskills', 'mybachecas', 'myhosps', 'mygoods'],
TABLES_INSERT_ALMOST_ONE_TO_ENABLE_CIRCUIT: ['myskills', 'myhosps', 'mygoods'],
//++Todo: per abilitare gli utenti ad inserire un Circuito aggiungere 'circuits' alla lista TABLES_PERM_NEWREC //++Todo: per abilitare gli utenti ad inserire un Circuito aggiungere 'circuits' alla lista TABLES_PERM_NEWREC
TABLES_PERM_NEWREC: ['skills', 'goods', 'subskills', 'mygroups', 'myhosps'], TABLES_PERM_NEWREC: ['skills', 'goods', 'subskills', 'mygroups', 'myhosps'],
TABLES_REC_ID: ['skills', 'goods', 'subskills'], TABLES_REC_ID: ['skills', 'goods', 'subskills'],
TABLES_FAVORITE_BOOKMARK: ['myskills', 'mygoods', 'mybachecas', 'myhosps'],
TABLES_VISU_STAT_IN_HOME: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'mygroups', 'circuits'], TABLES_VISU_STAT_IN_HOME: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'mygroups', 'circuits'],
TABLES_ADV_NOTIFICATION: ['myskills', 'myhosps', 'mygoods'], TABLES_ADV_NOTIFICATION: ['myskills', 'myhosps', 'mygoods'],
TABLES_ORDER_DATE_UPDATED: ['myskills', 'myhosps', 'mygoods'],
TABLES_ORDER_DESCR: ['mygroups'],
TABLES_EVENTS_NOTIFICATION: ['mybachecas'], TABLES_EVENTS_NOTIFICATION: ['mybachecas'],
TABLES_GROUPS_NOTIFICATION: ['mygroups'], TABLES_GROUPS_NOTIFICATION: ['mygroups'],
TABLES_CIRCUITS_NOTIFICATION: ['circuits'], TABLES_CIRCUITS_NOTIFICATION: ['circuits'],
TABLES_NUM_AS_ID_NUMBER: [ ], TABLES_NUM_AS_ID_NUMBER: [],
TABLES_ID_STRING: [ TABLES_ID_STRING: [
'circuits', 'circuits',
'accounts', 'accounts',
'movements', 'movements',
], ],
TABLES_ID_NUMBER: [ TABLES_ID_NUMBER: [
'permissions', 'permissions',
@@ -162,16 +206,18 @@ module.exports = {
'subskills', 'subskills',
'cities', 'cities',
'provinces', 'provinces',
'myskills', // 'myskills',
'mybachecas', // 'mybachecas',
'myhosps', // 'myhosps',
'mygoods', // 'mygoods',
'mygroups' // 'mygroups'
], ],
TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'], TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'],
TABLES_CREATEDBY: ['mygroups', 'circuits'], TABLES_CREATEDBY: ['mygroups', 'circuits'],
TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits'], TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits'],
TABLES_FIELDS_DESCR_AND_CITY_AND_USER: ['myskills', 'mybachecas', 'myhosps', 'mygoods'],
TABLES_PERM_CHANGE_FOR_USERS: ['myskills', 'mybachecas', 'myhosps', 'mygoods'], TABLES_PERM_CHANGE_FOR_USERS: ['myskills', 'mybachecas', 'myhosps', 'mygoods'],
TABLES_POPULATE_DATA: [ TABLES_POPULATE_DATA: [
@@ -182,19 +228,19 @@ module.exports = {
table: 'adtypes', table: 'adtypes',
key: 'descr', key: 'descr',
}, },
{table: 'catgrps', key: 'descr'}, { table: 'catgrps', key: 'descr' },
{ {
table: 'contribtypes', table: 'contribtypes',
key: 'descr', key: 'descr',
}, },
{table: 'goods', key: 'descr'}, { table: 'goods', key: 'descr' },
{table: 'levels', key: 'descr'}, { table: 'levels', key: 'descr' },
{table: 'cities', key: 'comune'}, { table: 'cities', key: 'comune' },
{table: 'provinces', key: 'descr'}, { table: 'provinces', key: 'descr' },
{table: 'sectorgoods', key: 'descr'}, { table: 'sectorgoods', key: 'descr' },
{table: 'sectors', key: 'descr'}, { table: 'sectors', key: 'descr' },
{table: 'skills', key: 'descr'}, { table: 'skills', key: 'descr' },
{table: 'statusSkills', key: 'descr'}, { table: 'statusSkills', key: 'descr' },
], ],
VISIB_ALL: 0, VISIB_ALL: 0,
@@ -202,6 +248,12 @@ module.exports = {
VISIB_ONLY_MANAGER: 2, VISIB_ONLY_MANAGER: 2,
VISIB_ONLY_ADMIN: 4, VISIB_ONLY_ADMIN: 4,
CIRCUIT_CFG: {
MULT_FIDO_USER: 2.0,
MULT_FIDO_GROUP: 2.0,
},
Visibility_Group: { Visibility_Group: {
PRIVATE: 1, PRIVATE: 1,
HIDDEN: 2, HIDDEN: 2,
@@ -213,6 +265,8 @@ module.exports = {
BOTTYPE_LINK: 2, BOTTYPE_LINK: 2,
BOTTYPE_TEXT: 3, BOTTYPE_TEXT: 3,
BOTTYPE_MENU: 4, BOTTYPE_MENU: 4,
BOTTYPE_MARKDOWN: 5,
BOTTYPE_BOTTONI_INLINE: 6,
RIS_OK: '👍🏻 OK', RIS_OK: '👍🏻 OK',
@@ -283,7 +337,10 @@ module.exports = {
REGISTRATION: 6, REGISTRATION: 6,
RICHIESTA_GRUPPO: 10, RICHIESTA_GRUPPO: 10,
RICHIESTA_AMICIZIA: 15, RICHIESTA_AMICIZIA: 15,
RICHIESTA_HANDSHAKE: 16,
RICHIESTA_CIRCUIT: 20, RICHIESTA_CIRCUIT: 20,
RICHIESTA_FIDO: 25,
ENTRA_RIS_ITALIA: 30,
}, },
OrderStatus: { OrderStatus: {
@@ -309,6 +366,9 @@ module.exports = {
Notif_Reg_Bot_ToManagers: 1, Notif_Reg_Bot_ToManagers: 1,
Notif_Reg_Push_Admin: 2, Notif_Reg_Push_Admin: 2,
Need_Aportador_On_DataReg_To_Verify_Reg: 4, Need_Aportador_On_DataReg_To_Verify_Reg: 4,
AskInvitantesulBot: 8,
AskUsernameSulBot: 16,
registerUserWithBot: 32,
}, },
MsgTeleg: { MsgTeleg: {
@@ -332,12 +392,15 @@ module.exports = {
NEW_ADV_MY_GROUPS: 8, NEW_ADV_MY_GROUPS: 8,
NEW_ADV_MY_RIS_CIRCUIT: 16, NEW_ADV_MY_RIS_CIRCUIT: 16,
NEW_ADV_SECTOR: 32, NEW_ADV_SECTOR: 32,
NEW_ADV_YOUR_PROVINCE: 64,
}, },
StatusNotifs: { StatusNotifs: {
STATUS_FRIENDS_ACCEPTED: 1, STATUS_FRIENDS_ACCEPTED: 1,
STATUS_FRIENDS_REFUSED: 2, STATUS_FRIENDS_REFUSED: 2,
STATUS_FRIENDS_REPORTED: 3, STATUS_FRIENDS_REPORTED: 3,
STATUS_HANDSHAKE_ACCEPTED: 10,
STATUS_HANDSHAKE_REFUSED: 11,
}, },
GroupsNotifs: { GroupsNotifs: {
@@ -350,6 +413,7 @@ module.exports = {
}, },
CircuitsNotif: { CircuitsNotif: {
STATUS_NONE: 0,
STATUS_NEW: 51, STATUS_NEW: 51,
STATUS_ACCEPTED: 53, STATUS_ACCEPTED: 53,
STATUS_REFUSED: 54, STATUS_REFUSED: 54,
@@ -371,10 +435,13 @@ module.exports = {
TYPEDIR_BACHECA: 1, TYPEDIR_BACHECA: 1,
ID_BACHECA_NEW_GOOD: 1, ID_BACHECA_NEW_GOOD: 1,
ID_BACHECA_NEW_SERVICE: 2, ID_BACHECA_NEW_SERVICE: 2,
ID_BACHECA_NEW_HOSP: 4,
TYPEDIR_EVENTS: 2, TYPEDIR_EVENTS: 2,
ID_EVENTS_NEW_REC: 1, ID_EVENTS_NEW_REC: 1,
ID_EVENTS_REMOVE_REC: 2, ID_EVENTS_REMOVE_REC: 2,
ID_EVENTS_ATTEND: 4,
ID_EVENTS_SEND_MSG: 8,
TYPEDIR_FRIENDS: 3, TYPEDIR_FRIENDS: 3,
ID_FRIENDS_NEW_REC: 1, ID_FRIENDS_NEW_REC: 1,
@@ -411,18 +478,25 @@ module.exports = {
ID_CIRCUIT_SENDCOINSREQ_SENT: 4096, ID_CIRCUIT_SENDCOINSREQ_SENT: 4096,
ID_CIRCUIT_COINS_ACCEPTED_SENT: 8192, ID_CIRCUIT_COINS_ACCEPTED_SENT: 8192,
ID_CIRCUIT_COINS_REFUSED_SENT: 16384, ID_CIRCUIT_COINS_REFUSED_SENT: 16384,
ID_CIRCUIT_SETFIDO: 32768,
TYPEDIR_BOOKING: 6, TYPEDIR_BOOKING: 6,
TYPEDIR_MSGS: 7, TYPEDIR_MSGS: 7,
ID_MSGS_NEW_REC: 1, ID_MSGS_NEW_REC: 1,
TYPEDIR_HANDSHAKE: 10,
ID_HANDSHAKE_ACCEPTED: 2,
TYPEDIR_FAVORITE: 11,
ID_FAVORITE_ADDED: 1,
TYPEDIR_TEST: 444, TYPEDIR_TEST: 444,
ID_TEST_NEW_REC: 1, ID_TEST_NEW_REC: 1,
}, },
// Tipi di Notifiche: // Tipi di Notifiche:
/* /*
Notif: { Notif: {
UPDATE_APP: 1, UPDATE_APP: 1,
@@ -473,25 +547,33 @@ module.exports = {
DEFAULT_NOTIFS_USER: [ DEFAULT_NOTIFS_USER: [
{ {
"dir": 1, 'dir': 1,
"value": 24 'value': 88
}, },
{ {
"dir": 2, 'dir': 2,
"value": 1 'value': 4
}, },
{ {
"dir": 3, 'dir': 3,
"value": 1 'value': 1
}, },
{ {
"dir": 4, 'dir': 4,
"value": 1 'value': 1
}, },
{ {
"dir": 5, 'dir': 5,
"value": 1 'value': 1
} },
{
'dir': 11,
'value': 1
},
{
'dir': 12,
'value': 1
},
], ],
CIRCUIT_STATUS: { CIRCUIT_STATUS: {
@@ -501,4 +583,231 @@ module.exports = {
FASE3_MONETA_ABILITATA: 3, FASE3_MONETA_ABILITATA: 3,
}, },
CIRCUIT_PARAMS: {
SCOPERTO_MIN_GRP: 200,
SCOPERTO_MAX_GRP: 400,
SCOPERTO_MIN_CONTO_COMUNITARIO: 500,
SCOPERTO_MAX_CONTO_COMUNITARIO: 1000,
},
TABLETYPE: {
DefaultCal: 0,
MyBachecas: 1,
},
getProjectByTable(table, proj_add) {
let proj = {}
if (table === this.TABLES_MYGOODS) {
proj = {
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
//**ADDFIELD_MYGOOD
}
} else if (table === this.TABLES_MYGROUPS) {
proj = {
groupname: 1,
title: 1,
descr: 1,
img: 1,
visibility: 1,
admins: 1,
idCatGrp: 1,
date_created: 1,
date_updated: 1,
photos: 1,
idCity: 1,
note: 1,
website: 1,
link_telegram: 1,
comune: 1,
mycities: 1,
sector: 1,
recCatGrp: 1,
}
} else if (table === this.TABLES_CIRCUITS) {
proj = {
_id: 1,
groupnameId: 1,
path: 1,
name: 1,
strProv: 1,
subname: 1,
longdescr: 1,
regulation: 1,
numMembers: 1,
totCircolante: 1,
totTransato: 1,
systemUserId: 1,
createdBy: 1,
date_created: 1,
date_updated: 1,
nome_valuta: 1,
fido_scoperto_default: 1,
deperimento: 1,
showAlways: 1,
status: 1,
transactionsEnabled: 1,
qta_max_default: 1,
fido_scoperto_default_grp: 1,
qta_max_default_grp: 1,
valuta_per_euro: 1,
symbol: 1,
idCity: 1,
pub_to_share: 1,
visibility: 1,
color: 1,
abbrev: 1,
data_costituz: 1,
photos: 1,
admins: 1,
req_users: 1,
refused_users: 1,
'mycities': 1,
//**ADDFIELD_CIRCUITS
}
} else if (table === this.TABLES_MYSKILLS) {
proj = {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
myskill: 1,
idStatusSkill: 1,
idContribType: 1,
numLevel: 1,
adType: 1,
photos: 1,
note: 1,
website: 1,
//**ADDFIELD_MYSKILL
}
} else if (table === this.TABLES_MYHOSPS) {
proj = {
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
idContribType: 1,
photos: 1,
idCity: 1,
note: 1,
website: 1,
link_maplocation: 1,
}
} else if (table === this.TABLES_MYBACHECAS) {
proj = {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
// 'idSubSkill': 1,
idStatusSkill: 1,
idContribType: 1,
dateTimeStart: 1,
dateTimeEnd: 1,
website: 1,
organisedBy: 1,
contact_phone: 1,
contact_telegram: 1,
address: 1,
min_partecip: 1,
max_partecip: 1,
contribstr: 1,
link_maplocation: 1,
'mygrp.groupname': 1,
'mygrp.title': 1,
'mygrp.photos': 1,
//**ADDFIELD_MYBACHECAS
}
}
if (proj_add)
proj = Object.assign({}, proj, proj_add);
return proj;
},
getProjectForAll(proj_add, table) {
let proj = {
idContribType: 1,
idCity: 1,
pub_to_share: 1,
adType: 1,
photos: 1,
note: 1,
descr: 1,
date_created: 1,
date_updated: 1,
userId: 1,
username: 1,
name: 1,
surname: 1,
groupname: 1,
lasttimeonline: 1,
comune: 1,
myreact: 1,
mycities: 1,
lang: 1,
'profile.img': 1,
'profile.mygroups': 1,
'profile.mycircuits': 1,
'profile.qualifica': 1,
'profile.resid_province': 1,
'profile.resid_card': 1,
'profile.username_telegram': 1,
'profile.favorite': 1,
'profile.bookmark': 1,
'profile.attend': 1,
'profile.seen': 1,
reported: 1,
date_report: 1,
username_who_report: 1,
namecomplete: 1,
date_reg: 1,
};
if (proj_add)
proj = Object.assign({}, proj, proj_add);
proj = {...proj, ...this.REACTIONS_FIELD};
if (table) {
let proj_add3 = this.getProjectByTable(table);
proj = Object.assign({}, proj, proj_add3);
}
return proj;
},
getDirectoryByTable(table, barre = false) {
let add = '';
if (barre)
add = '/';
if (table === 'myskills') {
return add + 'myservice' + add
} else if (table === 'mybachecas') {
return add + 'mypage' + add
} else if (table === 'myhosps') {
return add + 'myhosps' + add
} else if (table === 'mygoods') {
return add + 'mygood' + add
} else if (table === 'mygroups') {
return add + 'grp' + add
} else if (table === 'circuits') {
return add + 'circuit' + add
}
return ''
},
}; };

9
test.http Normal file
View File

@@ -0,0 +1,9 @@
### Init:
get http://localhost:3000/
### Create a new
get https://splendidus.it:3000/
### Create a new
get https://mail.freeplanet.app:3000/

10992
yarn.lock Normal file

File diff suppressed because it is too large Load Diff