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

@@ -1,6 +1,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",
@@ -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: [
{
"profile.mygroups": {
$elemMatch: {
groupname: {
$in: [
"000017",
"risoprova",
"VillaggiamoItalia",
"Terraw",
"RisoBenevento",
"111",
"gruppodefaultriso",
"pontiUmani",
],
},
},
},
},
{
pub_to_share: 1,
},
],
},
{
$or: [
{
pub_to_share: {
$exists: false, $exists: false,
}, },
}, },
{ {
deleted: { pub_to_share: {
$exists: true, $exists: true,
$eq: false, $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) {
try {
const account = this; 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;
}
account.totTransato += Math.abs(amount);
account.date_updated = new Date();
return await account.save();
}
return null; // *** 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,
}; };
AccountSchema.statics.addtoSaldo = async function (myaccount, amount) { // Update Record
return await Account.findByIdAndUpdate(account.id,
{
$set: myaccountupdate
}).then((ris) => {
console.log('calcPending', ris);
}).catch((err) => {
console.error('calcPending', err);
});
}
}
// -----
} catch (e) {
console.error(e);
}
}
AccountSchema.statics.addtoSaldo = async function (myaccount, amount, mitt) {
const Account = this; 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) {
if (!this.date_created)
this.date_created = new Date(); 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

@@ -47,9 +47,11 @@ 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,
@@ -111,9 +113,9 @@ MovementSchema.statics.addMov = async function(idapp, accountFromIdTable, accoun
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) {
@@ -172,7 +174,69 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
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',
@@ -183,26 +247,26 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
}, },
{ $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: {
@@ -226,7 +290,68 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
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:
{ {
@@ -240,6 +365,16 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function(idapp, username,
'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,6 +390,7 @@ 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 {
@@ -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',
@@ -377,6 +569,62 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
preserveNullAndEmptyArrays: true, 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:
{ {
@@ -390,6 +638,16 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
'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,
'groupto.groupname': 1,
'groupto.title': 1,
'contocomfrom.path': 1,
'contocomfrom.name': 1,
'contocomfrom.title': 1,
'contocomto.path': 1,
'contocomto.name': 1,
'contocomto.title': 1,
}, },
}, },
@@ -407,7 +665,7 @@ MovementSchema.statics.getQueryAllUsersMovsByCircuitId = async function(idapp, c
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);
@@ -423,7 +681,6 @@ MovementSchema.statics.checkIfCoinsAlreadySent = async function(notifId) {
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) {

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,14 +19,19 @@ mongoose.plugin(schema => {
}); });
const MyBachecaSchema = new Schema({ const MyBachecaSchema = new Schema({
...{
_id: { _id: {
type: Number, type: String,
default: function () {
return new ObjectID().toString();
},
}, },
idapp: { idapp: {
type: String, type: String,
required: true, required: true,
}, },
userId: { type: Schema.Types.ObjectId, ref: 'User' }, userId: { type: Schema.Types.ObjectId, ref: 'User' },
groupname: { type: String },
idSector: { idSector: {
type: Number, type: Number,
}, },
@@ -47,6 +57,30 @@ const MyBachecaSchema = new Schema({
dateTimeEnd: { dateTimeEnd: {
type: Date, type: Date,
}, },
organisedBy: {
type: String
},
contact_phone: {
type: String
},
contact_telegram: {
type: String
},
address: {
type: String,
},
min_partecip: {
type: Number,
},
max_partecip: {
type: Number,
},
link_maplocation: {
type: String,
},
contribstr: {
type: String,
},
numLevel: { numLevel: {
type: Number, type: Number,
default: 0, default: 0,
@@ -79,26 +113,17 @@ const MyBachecaSchema = new Schema({
}, },
date_created: { date_created: {
type: Date, type: Date,
default: Date.now,
}, },
date_updated: { date_updated: {
type: Date, 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) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date(); this.date_created = new Date();
} }
@@ -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,6 +6,10 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const { Reaction } = require('./reaction');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb'); const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
@@ -14,8 +18,9 @@ mongoose.plugin(schema => {
}); });
const MyGoodSchema = new Schema({ const MyGoodSchema = new Schema({
...{
_id: { _id: {
type: Number, type: String,
}, },
idapp: { idapp: {
type: String, type: String,
@@ -80,26 +85,17 @@ const MyGoodSchema = new Schema({
}, },
date_created: { date_created: {
type: Date, type: Date,
default: Date.now,
}, },
date_updated: { date_updated: {
type: Date, 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) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date(); this.date_created = new Date();
} }
@@ -145,35 +141,7 @@ 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,
},
}, },
}; };
@@ -185,20 +153,15 @@ MyGoodSchema.statics.executeQueryTable = function(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,42 +303,19 @@ 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;
}); });
@@ -512,6 +328,23 @@ MyGoodSchema.statics.getCompleteRecord = function(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);

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,
@@ -76,6 +79,7 @@ const MyGroupSchema = new Schema({
admins: [ admins: [
{ {
username: { type: String }, username: { type: String },
perm: { type: Number },
date: { type: Date }, date: { type: Date },
}, },
], ],
@@ -110,11 +114,15 @@ const MyGroupSchema = new Schema({
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 () {
@@ -139,17 +147,7 @@ MyGroupSchema.statics.executeQueryTable = function(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) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date(); this.date_created = new Date();
} }
@@ -220,6 +218,20 @@ MyGroupSchema.statics.removeAdminOfMyGroup = async function(idapp, username, gro
{ $pull: { admins: { username: { $in: [username] } } } }); { $pull: { admins: { username: { $in: [username] } } } });
}; };
MyGroupSchema.statics.getListAdminsByGroupName = async function (idapp, groupname) {
let arr = await MyGroup.findOne({
idapp,
groupname,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
}, { admins: 1 }).lean();
return arr && arr.admins ? arr.admins : [];
};
MyGroupSchema.statics.getWhatToShow = function (idapp, username) { MyGroupSchema.statics.getWhatToShow = function (idapp, username) {
// FOR ME, PERMIT ALL // FOR ME, PERMIT ALL
return { return {
@@ -242,7 +254,8 @@ 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,
}; };
}; };
@@ -259,7 +272,8 @@ 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,
}; };
}; };
@@ -295,12 +309,12 @@ 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',
}, },
}, },
@@ -465,6 +479,150 @@ MyGroupSchema.statics.extractCitiesName = async function(idapp, id) {
}; };
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);

View File

@@ -6,6 +6,9 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const { Reaction } = require('./reaction');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb'); const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
@@ -14,8 +17,9 @@ mongoose.plugin(schema => {
}); });
const MyHospSchema = new Schema({ const MyHospSchema = new Schema({
...{
_id: { _id: {
type: Number, type: String,
}, },
idapp: { idapp: {
type: String, type: String,
@@ -85,26 +89,17 @@ const MyHospSchema = new Schema({
}, },
date_created: { date_created: {
type: Date, type: Date,
default: Date.now,
}, },
date_updated: { date_updated: {
type: Date, 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) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date(); this.date_created = new Date();
} }
@@ -147,34 +142,7 @@ 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,
},
}, },
}; };
@@ -186,20 +154,12 @@ MyHospSchema.statics.executeQueryTable = function(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,38 +300,19 @@ 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;
}); });
@@ -492,6 +325,27 @@ MyHospSchema.statics.getCompleteRecord = function(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,6 +6,10 @@ mongoose.level = 'F';
const tools = require('../tools/general'); const tools = require('../tools/general');
const { Reaction } = require('./reaction');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb'); const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
@@ -13,9 +17,14 @@ mongoose.plugin(schema => {
schema.options.usePushEach = true; schema.options.usePushEach = true;
}); });
const MySkillSchema = new Schema({ const MySkillSchema = new Schema(
{
...{
_id: { _id: {
type: Number, type: String,
default: function () {
return new ObjectID().toString();
},
}, },
idapp: { idapp: {
type: String, type: String,
@@ -83,26 +92,20 @@ const MySkillSchema = new Schema({
}, },
date_created: { date_created: {
type: Date, type: Date,
default: Date.now,
}, },
date_updated: { date_updated: {
type: Date, type: Date,
}, },
}); },
...Reaction.getFieldsForReactions()
}, { strict: false });
MySkillSchema.index({ 'idapp': 1 });
MySkillSchema.pre('save', async function (next) { 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) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
this.date_created = new Date(); this.date_created = new Date();
} }
@@ -147,34 +150,7 @@ 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,
},
}, },
}; };
@@ -186,19 +162,10 @@ MySkillSchema.statics.executeQueryTable = function(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,46 +309,42 @@ 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.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) { MySkillSchema.statics.getCompleteRecord = function (idapp, id) {
const MySkill = this; const MySkill = this;

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" },

View File

@@ -22,27 +22,39 @@ mongoose.plugin(schema => {
const sendNotifSchema = new Schema({ const sendNotifSchema = new Schema({
idapp: { idapp: {
type: String, type: String,
index: true,
}, },
typedir: { typedir: {
type: Number, type: Number,
default: 0, default: 0,
index: true,
}, },
typeid: { typeid: {
type: Number, type: Number,
default: 0, default: 0,
index: true,
}, },
sender: { // mittente sender: { // mittente
type: String, type: String,
default: '', default: '',
index: true,
}, },
dest: { dest: {
type: String, type: String,
default: '', default: '',
}, },
title: { descr: {
type: String, type: String,
}, },
descr: { sendergroup: { // mittente
type: String,
default: '',
},
destgroup: {
type: String,
default: '',
},
title: {
type: String, type: String,
}, },
openUrl: { openUrl: {
@@ -58,6 +70,7 @@ const sendNotifSchema = new Schema({
status: { status: {
type: Number, type: Number,
default: 0, default: 0,
index: true,
}, },
typesend: { typesend: {
type: Number, type: Number,
@@ -88,11 +101,31 @@ const sendNotifSchema = new Schema({
options: { options: {
type: Array, type: Array,
}, },
textaddTelegram: {
type: String,
},
textcontent_Telegram: {
type: String,
},
linkaddTelegram: {
type: String,
}
}); });
sendNotifSchema.index({ idapp: 1 });
sendNotifSchema.index({ typedir: 1 });
sendNotifSchema.index({ typeid: 1 });
sendNotifSchema.index({ sender: 1 });
sendNotifSchema.index({ idapp: 1, typedir: 1, typeid: 1, status: 1, sender: 1 });
sendNotifSchema.statics.setNotifAsRead = function (idapp, username, idnotif) { sendNotifSchema.statics.setNotifAsRead = function (idapp, username, idnotif) {
const SendNotif = this; const SendNotif = this;
if (!username)
return null;
try { try {
if (idnotif) { if (idnotif) {
@@ -128,16 +161,19 @@ sendNotifSchema.statics.getRecNotif = function(id) {
}; };
sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, lastdataread, idapp) { sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, lastdataread, idapp, limitrecord) {
const SendNotif = this; const SendNotif = this;
if (!lastdataread)
lastdataread = 0;
return SendNotif.find({ return SendNotif.find({
$and: [ $and: [
{ idapp }, { idapp },
{ 'dest': username }, { 'dest': username },
{ 'datenotif': { $gt: new Date(lastdataread) } }, { 'datenotif': { $gt: new Date(lastdataread) } },
], ],
}).lean().sort({datenotif: -1}).then(async (arrnotif) => { }).lean().limit(limitrecord).sort({ datenotif: -1 }).then(async (arrnotif) => {
// console.log('arrnotif', arrnotif.length); // console.log('arrnotif', arrnotif.length);
return this.compileOtherFields(arrnotif); return this.compileOtherFields(arrnotif);
@@ -148,15 +184,19 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la
}; };
sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) { sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, userorig) {
const numchars = 80; const numchars = 80;
let newdescr = ''; let newdescr = '';
let newdescrtelegram = '';
let mydescr = ''; let mydescr = '';
let myidrec = ''; let myidrec = '';
let userorig = recnotif.sender; let sender = recnotif.sender ? recnotif.sender : '';
let tag = ''; let tag = '';
const { Circuit } = require('../models/circuit');
const { User } = require('../models/user');
try { try {
if (recnotif.myrectableorig) { if (recnotif.myrectableorig) {
myidrec = recnotif.myrectableorig._id; myidrec = recnotif.myrectableorig._id;
@@ -165,27 +205,57 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) {
if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA) { if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA) {
if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD) { if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD) {
newdescr = i18n.__('<strong>%s</strong> new Good: %s', userorig, mydescr); newdescr = i18n.__('NEW_GOOD', userorig, mydescr);
recnotif.openUrl = '/mygood/' + myidrec; recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TABLES_MYGOODS, true) + myidrec;
tag = 'newgood'; tag = 'newgood';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE) {
newdescr = i18n.__('<strong>%s</strong> new Service: %s', userorig, mydescr); newdescr = i18n.__('NEW_SERVICE', userorig, mydescr);
recnotif.openUrl = '/myservice/' + myidrec; recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TABLES_MYSKILLS, true) + myidrec;
tag = 'newservice'; tag = 'newservice';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_HOSP) {
newdescr = i18n.__('NEW_HOSP', userorig, mydescr);
recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TABLES_MYHOSPS, true) + myidrec;
tag = 'newhosp';
} }
recnotif.linkaddTelegram = 'Vedi annuncio';
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS) {
recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TABLES_MYBACHECAS, true) + myidrec;
tag = 'newevent';
if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_NEW_REC) {
let eventobj = await tools.getEventForTelegram(recnotif.myrectableorig, mydescr, userorig);
newdescr = eventobj.newdescr;
newdescrtelegram = eventobj.newdescrtelegram;
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_SEND_MSG) {
newdescr = i18n.__('EVENT_SEND_MSG', userorig, recnotif.title, recnotif.msg);
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_ATTEND) {
// ++ Controlla se esiste già
let esitegia = recnotif.paramsObj.recObjCreator.exist; // ++
if (esitegia)
newdescr = i18n.__('SET_ATTEND_OTHERS', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.numattend - 1, recnotif.paramsObj.recObjCreator.descr);
else
newdescr = i18n.__('SET_ATTEND', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.descr);
recnotif.openUrl = shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) + recnotif.paramsObj.recObjCreator.id;
tag = 'attend';
}
recnotif.textcontent_Telegram = newdescrtelegram;
recnotif.linkaddTelegram = i18n.__('SHOW_POST');
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) { } else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) {
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC) { if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC) {
newdescr = i18n.__('<strong>%s</strong> asked you for Friendship', userorig, mydescr); newdescr = i18n.__('<strong>%s</strong> asked you for Friendship', sender, mydescr);
tag = 'newfriend'; tag = 'newfriend';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED) {
newdescr = i18n.__('<strong>%s</strong> accepted your Friendship', userorig, mydescr); newdescr = i18n.__('<strong>%s</strong> accepted your Friendship', sender, mydescr);
tag = 'acceptedfriend'; tag = 'acceptedfriend';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED_MY_REQUEST) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED_MY_REQUEST) {
newdescr = i18n.__('✅ You have accepted %s\' Friendship request!', userorig, mydescr); newdescr = i18n.__('✅ You have accepted %s\' Friendship request!', sender, mydescr);
tag = 'acceptedfriend'; tag = 'acceptedfriend';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_REFUSED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_REFUSED) {
newdescr = i18n.__('<strong>%s</strong> refused your Friendship', userorig, mydescr); newdescr = i18n.__('<strong>%s</strong> refused your Friendship', sender, mydescr);
tag = 'refusedfriend'; tag = 'refusedfriend';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_REPORTED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_REPORTED) {
tag = 'reportuser'; tag = 'reportuser';
@@ -193,174 +263,303 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) {
newdescr = i18n.__('FRIEND_REPORTED_YOU', recnotif.paramsObj.username_worked); newdescr = i18n.__('FRIEND_REPORTED_YOU', recnotif.paramsObj.username_worked);
recnotif.openUrl = '/my/' + recnotif.paramsObj.username_worked; recnotif.openUrl = '/my/' + recnotif.paramsObj.username_worked;
} else if (recnotif.paramsObj.isAdmin) { } else if (recnotif.paramsObj.isAdmin) {
newdescr = i18n.__('FRIEND_REPORTED', recnotif.paramsObj.usernameDest, userorig); newdescr = i18n.__('FRIEND_REPORTED', recnotif.paramsObj.usernameDest, sender);
recnotif.openUrl = '/my/' + recnotif.paramsObj.usernameDest; recnotif.openUrl = '/my/' + recnotif.paramsObj.usernameDest;
} else { } else {
recnotif.openUrl = '/my/' + recnotif.paramsObj.username_action; recnotif.openUrl = '/my/' + recnotif.paramsObj.username_action;
newdescr = i18n.__('FRIEND_REPORTED_TO_ME', recnotif.paramsObj.username_action, recnotif.paramsObj.username_action); newdescr = i18n.__('FRIEND_REPORTED_TO_ME', recnotif.paramsObj.username_action, recnotif.paramsObj.username_action);
} }
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_UNBLOCKED) {
tag = 'unblockeduser';
if (recnotif.paramsObj.usernameDest === recnotif.paramsObj.username_action) {
newdescr = i18n.__('FRIEND_UNBLOCKED_YOU', recnotif.paramsObj.username_worked);
recnotif.openUrl = '/my/' + recnotif.paramsObj.username_worked;
} else if (recnotif.paramsObj.isAdmin) {
newdescr = i18n.__('FRIEND_UNBLOCKED', recnotif.paramsObj.usernameDest, userorig);
} else {
newdescr = i18n.__('FRIEND_UNBLOCKED_TO_ME', recnotif.paramsObj.username_action, recnotif.paramsObj.username_action);
} }
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_HANDSHAKE) {
recnotif.openUrl = '/my/' + sender;
if (recnotif.typeid === shared_consts.TypeNotifs.ID_HANDSHAKE_ACCEPTED) {
newdescr = i18n.__('HANDSHAKE_SET', sender, mydescr);
tag = 'acceptedhandshake';
} }
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS) { } else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS) {
tag = 'group'; tag = 'group';
recnotif.openUrl = '/grp/' + recnotif.paramsObj.groupnameDest; recnotif.openUrl = shared_consts.getDirectoryByTable('mygroups', true) + recnotif.paramsObj.groupnameDest;
if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_NEW_REC) { if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_NEW_REC) {
newdescr = i18n.__('GROUP_CREATED', userorig, recnotif.paramsObj.groupnameDest); newdescr = i18n.__('GROUP_CREATED', sender, recnotif.paramsObj.groupnameDest);
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_ACCEPTED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_ACCEPTED) {
if (recnotif.paramsObj.isAdmin) { if (recnotif.paramsObj.isAdmin) {
newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
} else { } else {
newdescr = i18n.__('GROUPS_ACCEPTED', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_ACCEPTED', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
} }
tag = 'addgroup'; tag = 'addgroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REMOVED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REMOVED) {
if (recnotif.paramsObj.username_action === recnotif.paramsObj.usernameDest && userorig === recnotif.paramsObj.usernameDest) { if (recnotif.paramsObj.username_action === recnotif.paramsObj.usernameDest && sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('GROUPS_EXIT_USER_TO_ME', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_EXIT_USER_TO_ME', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
} else if (userorig === recnotif.paramsObj.usernameDest) { } else if (sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('GROUPS_REMOVED_TO_ME', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_REMOVED_TO_ME', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
} else if (userorig === recnotif.paramsObj.username_action) { } else if (sender === recnotif.paramsObj.username_action) {
newdescr = i18n.__('GROUPS_EXIT_USER', userorig, recnotif.paramsObj.groupnameDest); newdescr = i18n.__('GROUPS_EXIT_USER', sender, recnotif.paramsObj.groupnameDest);
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
} else { } else {
newdescr = i18n.__('GROUPS_REMOVED', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_REMOVED', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
} }
tag = 'remgroup'; tag = 'remgroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REFUSED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REFUSED) {
newdescr = i18n.__('GROUPS_REFUSED', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_REFUSED', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
tag = 'refgroup'; tag = 'refgroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REQUEST_TO_ENTER) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REQUEST_TO_ENTER) {
newdescr = i18n.__('GROUP_REQUEST_TO_ENTER', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.singleadmin_username); newdescr = i18n.__('GROUP_REQUEST_TO_ENTER', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.singleadmin_username);
tag = 'reqgroups'; tag = 'reqgroups';
// sendnotifPush = false; // non lo rimandare 2 volte ! // sendnotifPush = false; // non lo rimandare 2 volte !
// telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_GRUPPO, myuser, singleadmin.username, groupname, group._id); // telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_GRUPPO, myuser, singleadmin.username, groupname, group._id);
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_BLOCK_USER) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_BLOCK_USER) {
newdescr = i18n.__('RICHIESTA_BLOCCO_GRUPPO', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.singleadmin_username); newdescr = i18n.__('RICHIESTA_BLOCCO_GRUPPO', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.singleadmin_username);
tag = 'blockgroups'; tag = 'blockgroups';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_DELETE_USER) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_DELETE_USER) {
newdescr = i18n.__('GRUPPO_ELIMINATO', userorig, recnotif.paramsObj.username_action); newdescr = i18n.__('GRUPPO_ELIMINATO', sender, recnotif.paramsObj.username_action);
tag = 'deletegroup'; tag = 'deletegroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_ADDED_ADMIN_OFMYGROUP) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_ADDED_ADMIN_OFMYGROUP) {
if (userorig === recnotif.paramsObj.usernameDest) { if (sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('GROUPS_ADDED_ADMIN_GROUP_YOU', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_ADDED_ADMIN_GROUP_YOU', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
} else { } else {
newdescr = i18n.__('GROUPS_ADDED_ADMIN_GROUP', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_ADDED_ADMIN_GROUP', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
} }
tag = 'addadmingrp'; tag = 'addadmingrp';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REMOVED_ADMIN_OFMYGROUP) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REMOVED_ADMIN_OFMYGROUP) {
if (userorig === recnotif.paramsObj.usernameDest) { if (sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('GROUPS_REMOVED_ADMIN_GROUP_YOU', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_REMOVED_ADMIN_GROUP_YOU', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
} else { } else {
newdescr = i18n.__('GROUPS_REMOVED_ADMIN_GROUP', userorig, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('GROUPS_REMOVED_ADMIN_GROUP', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
} }
tag = 'removeadmingrp'; tag = 'removeadmingrp';
} }
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS) { } else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS) {
tag = 'circuit'; tag = 'circuit';
recnotif.openUrl = '/circuit/' + recnotif.paramsObj.path; let strtipocontoDest = '';
let strtipocontoOrig = '';
let groupOComorig = '';
let groupOComdest = '';
recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path;
if (recnotif.paramsObj.extrarec) {
strtipocontoOrig = recnotif.paramsObj.extrarec.contoComOrig ? i18n.__('COMUNITARIO') : i18n.__('COLLETTIVO');
strtipocontoDest = recnotif.paramsObj.extrarec.contoComDest ? i18n.__('COMUNITARIO') : i18n.__('COLLETTIVO');
groupOComorig = recnotif.paramsObj.extrarec.contoComOrig ? recnotif.paramsObj.extrarec.contoComOrig : recnotif.paramsObj.extrarec.grouporig;
groupOComdest = recnotif.paramsObj.extrarec.contoComDest ? recnotif.paramsObj.extrarec.contoComDest : recnotif.paramsObj.extrarec.groupdest;
}
let myorig = '';
let mydest = '';
let destinatario = '';
let qty = '';
let symbol = '';
let username_action = '';
let username_mittente = '';
let circuitname = '';
let numuserincircuit = 0;
try {
username_action = recnotif.paramsObj.username_action
username_mittente = recnotif.paramsObj.sender ? recnotif.paramsObj.sender : username_action
myorig = recnotif.paramsObj.extrarec.grouporig;
mydest = recnotif.paramsObj.extrarec.groupdest ? recnotif.paramsObj.extrarec.groupdest : recnotif.paramsObj.extrarec.dest;
destinatario = recnotif.paramsObj.extrarec.dest ? recnotif.paramsObj.extrarec.dest : (recnotif.paramsObj.extrarec.groupdest ? recnotif.paramsObj.extrarec.groupdest : recnotif.paramsObj.extrarec.contoComDest);
qty = recnotif.paramsObj.extrarec && recnotif.paramsObj.extrarec.qty ? recnotif.paramsObj.extrarec.qty.toString() : '';
symbol = recnotif.paramsObj.extrarec ? recnotif.paramsObj.extrarec.symbol : '';
circuitname = recnotif.paramsObj.circuitnameDest;
numuserincircuit = await User.countUsersInCircuit(recnotif.idapp, circuitname);
} catch (e) {
}
recnotif.textaddTelegram = '';
if (groupOComdest) {
destinatario += ' (' + username_mittente + ')'
}
if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_NEW_REC) { if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_NEW_REC) {
newdescr = i18n.__('CIRCUIT_CREATED', userorig, recnotif.paramsObj.circuitnameDest); newdescr = i18n.__('CIRCUIT_CREATED', sender, recnotif.paramsObj.circuitnameDest);
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SETFIDO) {
if (recnotif.paramsObj.isAdmin) {
if (recnotif.extrarec.groupname) {
newdescr = i18n.__('FIDO_IMPOSTATO_ADMINS_CIRCUIT_MYGROUP', recnotif.extrarec.groupname, -recnotif.paramsObj.extrarec.fidoConcesso, recnotif.paramsObj.circuitnameDest,
username_action);
} else {
newdescr = i18n.__('FIDO_IMPOSTATO_ADMINS_CIRCUIT', sender, -recnotif.paramsObj.extrarec.fidoConcesso, recnotif.paramsObj.circuitnameDest,
username_action);
}
recnotif.openUrl = '/my/' + sender;
} else {
newdescr = i18n.__('FIDO_IMPOSTATO', -recnotif.paramsObj.extrarec.fidoConcesso, username_action, recnotif.paramsObj.circuitnameDest);
}
tag = 'setfido';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_ACCEPTED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_ACCEPTED) {
if (recnotif.paramsObj.isAdmin) { if (recnotif.paramsObj.isAdmin) {
newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT', userorig, recnotif.paramsObj.circuitnameDest, if (recnotif.extrarec.groupname) {
recnotif.paramsObj.username_action); newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest,
recnotif.openUrl = '/my/' + userorig; username_action);
} else { } else {
if (userorig === recnotif.paramsObj.usernameDest) { newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT', sender, recnotif.paramsObj.circuitnameDest,
newdescr = i18n.__('CIRCUIT_ACCEPTED', recnotif.paramsObj.username_action, recnotif.paramsObj.circuitnameDest, tools.getHostByIdApp(recnotif.idapp) + recnotif.openUrl); username_action);
}
recnotif.openUrl = '/my/' + sender;
} else {
if (sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('CIRCUIT_ACCEPTED', username_action, recnotif.paramsObj.circuitnameDest, tools.getHostByIdApp(recnotif.idapp) + recnotif.openUrl);
} else { } else {
newdescr = i18n.__('CIRCUIT_ACCEPTED_YOU', recnotif.paramsObj.usernameDest, recnotif.paramsObj.circuitnameDest); newdescr = i18n.__('CIRCUIT_ACCEPTED_YOU', recnotif.paramsObj.usernameDest, recnotif.paramsObj.circuitnameDest);
} }
} }
tag = 'addcircuit'; tag = 'addcircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REMOVED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REMOVED) {
if (recnotif.paramsObj.username_action === recnotif.paramsObj.usernameDest && userorig === recnotif.paramsObj.usernameDest) { if (username_action === recnotif.paramsObj.usernameDest && sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('CIRCUIT_EXIT_USER_TO_ME', recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_EXIT_USER_TO_ME', recnotif.paramsObj.circuitnameDest, username_action);
} else if (userorig === recnotif.paramsObj.usernameDest) { } else if (sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('CIRCUIT_REMOVED_TO_ME', recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_REMOVED_TO_ME', recnotif.paramsObj.circuitnameDest, username_action);
} else if (userorig === recnotif.paramsObj.username_action) { } else if (sender === username_action) {
newdescr = i18n.__('CIRCUIT_EXIT_USER', userorig, recnotif.paramsObj.circuitnameDest); newdescr = i18n.__('CIRCUIT_EXIT_USER', sender, recnotif.paramsObj.circuitnameDest);
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
} else { } else {
newdescr = i18n.__('CIRCUIT_REMOVED', userorig, recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_REMOVED', sender, recnotif.paramsObj.circuitnameDest, username_action);
} }
tag = 'remcircuit'; tag = 'remcircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REFUSED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REFUSED) {
if (recnotif.paramsObj.isAdmin) { if (recnotif.paramsObj.isAdmin) {
newdescr = i18n.__('CIRCUIT_REFUSED_TO_ME', userorig, recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); if (recnotif.extrarec.groupname) {
newdescr = i18n.__('CIRCUIT_REFUSED_TO_MYGROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest, username_action);
}
} else { } else {
newdescr = i18n.__('CIRCUIT_REFUSED', recnotif.paramsObj.username_action, recnotif.paramsObj.circuitnameDest); newdescr = i18n.__('CIRCUIT_REFUSED', username_action, recnotif.paramsObj.circuitnameDest);
} }
tag = 'refcircuit'; tag = 'refcircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REQUEST_TO_ENTER) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REQUEST_TO_ENTER) {
newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER', userorig, recnotif.paramsObj.circuitnameDest,
recnotif.paramsObj.singleadmin_username); aportador_solidario = await User.getAportadorSolidarioByUsername(recnotif.idapp, sender);
if (recnotif.extrarec.groupname) {
newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER_WITH_GROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest,
numuserincircuit, recnotif.paramsObj.singleadmin_username);
} else {
newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER', sender, '<strong>' + recnotif.paramsObj.circuitnameDest + '</strong>', numuserincircuit, aportador_solidario);
}
const myadmins = await Circuit.getListAdmins(recnotif.idapp, recnotif.paramsObj.circuitnameDest);
recnotif.textaddTelegram += '\n' + i18n.__('CIRCUIT_ADMINS', myadmins.num, myadmins.str);
recnotif.textaddTelegram += '\n' + i18n.__('CIRCUIT_WHERE_IS_PRESENT', await Circuit.getListCircuitsByUsername(recnotif.idapp, sender, recnotif.extrarec.groupname));
tag = 'reqcircuits'; tag = 'reqcircuits';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_DELETE_USER) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_DELETE_USER) {
newdescr = i18n.__('CIRCUIT_ELIMINATO', userorig, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_ELIMINATO', sender, username_action);
tag = 'deletecircuit'; tag = 'deletecircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_ADDED_ADMIN) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_ADDED_ADMIN) {
if (userorig === recnotif.paramsObj.usernameDest) { if (sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('CIRCUIT_ADDED_ADMIN_YOU', recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_ADDED_ADMIN_YOU', recnotif.paramsObj.usernameDest, recnotif.paramsObj.circuitnameDest, username_action);
} else { } else {
newdescr = i18n.__('CIRCUIT_ADDED_ADMIN', userorig, recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_ADDED_ADMIN', sender, recnotif.paramsObj.circuitnameDest, username_action);
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
} }
tag = 'addadmingrp'; tag = 'addadmingrp';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REMOVED_ADMIN) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REMOVED_ADMIN) {
if (userorig === recnotif.paramsObj.usernameDest) { if (sender === recnotif.paramsObj.usernameDest) {
newdescr = i18n.__('CIRCUIT_REMOVED_ADMIN_YOU', recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_REMOVED_ADMIN_YOU', recnotif.paramsObj.usernameDest, recnotif.paramsObj.circuitnameDest, username_action);
} else { } else {
newdescr = i18n.__('CIRCUIT_REMOVED_ADMIN', userorig, recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); newdescr = i18n.__('CIRCUIT_REMOVED_ADMIN', sender, recnotif.paramsObj.circuitnameDest, username_action);
recnotif.openUrl = '/my/' + userorig; recnotif.openUrl = '/my/' + sender;
} }
tag = 'removeadmincircuit'; tag = 'removeadmincircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ) {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ', tools.getAhref(recnotif.paramsObj.username_action, await tools.getLinkUserTelegram(recnotif.idapp, recnotif.paramsObj.username_action)), recnotif.paramsObj.extrarec.qty.toString(), if (groupOComdest) {
recnotif.paramsObj.extrarec.symbol); newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_GROUP', tools.getAhref(username_action, await tools.getLinkUserTelegram(recnotif.idapp, username_action)), qty,
symbol, strtipocontoDest, groupOComdest, circuitname);
} else if (groupOComorig && (sender === recnotif.paramsObj.usernameDest)) {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_YOU', strtipocontoOrig, groupOComorig, username_action, qty, symbol, recnotif.paramsObj.extrarec.dest, circuitname);
} else if (groupOComorig) {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER', strtipocontoOrig, groupOComorig, username_action, qty, symbol, recnotif.paramsObj.extrarec.dest, circuitname);
} else {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ', tools.getAhref(username_action, await tools.getLinkUserTelegram(recnotif.idapp, username_action)), qty,
symbol, circuitname);
}
tag = 'sendcoin'; tag = 'sendcoin';
recnotif.openUrl = '/circuit/' + recnotif.paramsObj.path; //++Todo: dove lo mando ? recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path; //++Todo: dove lo mando ?
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT) {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_TO_ME', recnotif.paramsObj.extrarec.qty.toString(),
recnotif.paramsObj.extrarec.symbol, recnotif.paramsObj.extrarec.dest); if (myorig) {
if (groupOComdest) {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_GROUP', strtipocontoOrig, myorig, username_action, qty, symbol, strtipocontoDest, groupOComdest, circuitname);
} else {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER', strtipocontoOrig, myorig, username_action, qty, symbol, mydest, circuitname);
}
} else {
if (groupOComdest) {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_TO_GROUP', qty, symbol, strtipocontoDest, groupOComdest, circuitname);
} else {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_TO_ME', qty, symbol, mydest, circuitname);
}
}
tag = 'sendcoin'; tag = 'sendcoin';
recnotif.openUrl = '/circuit/' + recnotif.paramsObj.path; //++Todo: dove lo mando ? recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path; //++Todo: dove lo mando ?
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED) {
newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED', recnotif.paramsObj.extrarec.qty.toString(), recnotif.paramsObj.extrarec.symbol, newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED', qty, symbol,
recnotif.paramsObj.username_action) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, username_action, circuitname) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
recnotif.paramsObj.extrarec.symbol
); if (myorig) {
if (groupOComdest) {
newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_GROUP', strtipocontoDest, myorig, username_action, qty, symbol, strtipocontoDest, groupOComdest, circuitname, username_mittente) + `\n`
+ i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
} else {
newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_YOU', qty, symbol, strtipocontoOrig, myorig, circuitname, username_action)
+ `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol);
}
} else {
if (groupOComdest) {
newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_GROUP', strtipocontoDest, groupOComdest, username_action, qty, symbol, username_mittente)
+ `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
} else {
newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_YOU', qty, symbol, username_action, circuitname)
+ `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
}
}
tag = 'sendcoin'; tag = 'sendcoin';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED_SENT) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED_SENT) {
newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_TO_ME', recnotif.paramsObj.extrarec.qty.toString(), if (!destinatario) {
recnotif.paramsObj.extrarec.symbol, destinatario = username_action
recnotif.paramsObj.extrarec.dest) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoOrig, }
recnotif.paramsObj.extrarec.symbol); let saldostr = i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoOrig, symbol, circuitname);
if (groupOComorig) {
saldostr = i18n.__('SALDO_UPDATE_WHO', groupOComorig, recnotif.paramsObj.extrarec.saldoOrig, symbol, circuitname);
}
newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_TO_ME', qty, symbol, destinatario, circuitname)
+ `\n` + saldostr;
tag = 'sendcoin'; tag = 'sendcoin';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED) {
newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED', recnotif.paramsObj.extrarec.qty.toString(), recnotif.paramsObj.extrarec.symbol, newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED', qty, symbol, username_action, circuitname);
recnotif.paramsObj.username_action);
tag = 'sendcoin'; tag = 'sendcoin';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT) { } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT) {
newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED_TO_ME', recnotif.paramsObj.extrarec.qty.toString(), recnotif.paramsObj.extrarec.symbol,
recnotif.paramsObj.extrarec.dest); newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED_TO_ME', qty, symbol, destinatario, circuitname);
tag = 'sendcoin';ac tag = 'sendcoin';
} }
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
// ++ Controlla se esiste già
let esitegia = recnotif.paramsObj.recObjCreator.exist; // ++
if (esitegia)
newdescr = i18n.__('SET_FAVORITE_OTHERS', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.numfav - 1, recnotif.paramsObj.recObjCreator.descr);
else
newdescr = i18n.__('SET_FAVORITE', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.descr);
tag = 'favorite';
recnotif.openUrl = shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) + recnotif.paramsObj.recObjCreator.id;
recnotif.linkaddTelegram = i18n.__('SHOW_POST');
} }
recnotif.tag = recnotif.tag ? recnotif.tag : tag; recnotif.tag = recnotif.tag ? recnotif.tag : tag;
@@ -425,15 +624,19 @@ sendNotifSchema.statics.saveAndSendNotif = async function(myrecnotif, req, res,
const SendNotif = this; const SendNotif = this;
let idapp = req.body.idapp; let idapp = req.body.idapp;
const check = tools.checkUserOk(myrecnotif.sender, user ? myrecnotif.sender : req.user.username, res); let check = tools.checkUserOk(myrecnotif.sender, user ? myrecnotif.sender : req.user.username, res);
if (!check)
check = tools.checkUserOk(myrecnotif.sendergroup, user ? myrecnotif.sendergroup : req.user.username, res);
if (check.exit) return check.ret; if (check.exit) return check.ret;
const {myrecout, save} = await SendNotif.updateStatusAndDescr(myrecnotif, false); const { myrecout, save } = await SendNotif.updateStatusAndDescr(myrecnotif, false, req.user.username);
if (!myrecout) if (!myrecout)
return null; return null;
// console.log('myrecout._id', myrecout._id.toString()); // console.log('myrecout._id', myrecout._id.toString());
let risnotif = null;
if (save) { if (save) {
let res = null; let res = null;
try { try {
@@ -444,7 +647,10 @@ sendNotifSchema.statics.saveAndSendNotif = async function(myrecnotif, req, res,
const myrecread = await SendNotif.findById(idobj).lean(); const myrecread = await SendNotif.findById(idobj).lean();
// console.log('myrecread._id', myrecread._id.toString()); // console.log('myrecread._id', myrecread._id.toString());
return await globalTables.sendNotif(myrecread.typedir, myrecread.typeid, res, idapp, user ? user : req.user, myrecread); if (myrecread)
risnotif = await globalTables.sendNotif(myrecread.typedir, myrecread.typeid, res, idapp, user ? user : req.user, myrecread);
else
return false;
} }
} catch (e) { } catch (e) {
@@ -453,18 +659,21 @@ sendNotifSchema.statics.saveAndSendNotif = async function(myrecnotif, req, res,
} }
} else { } else {
return await globalTables.sendNotif(myrecout.typedir, myrecout.typeid, res, idapp, user ? user : req.user, myrecout); risnotif = await globalTables.sendNotif(myrecout.typedir, myrecout.typeid, res, idapp, user ? user : req.user, myrecout);
} }
return risnotif;
}; };
sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysave) { sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlysave, userorig) {
const SendNotif = this; const SendNotif = this;
try { try {
if (!myrecnotif.openUrl) { if (!myrecnotif.openUrl) {
// If not exist, then I set openUrl and description // If not exist, then I set openUrl and description
myrecnotif = await this.getDescrAndLinkByRecNotif(myrecnotif); myrecnotif = await this.getDescrAndLinkByRecNotif(myrecnotif, userorig);
} }
let newstatus = 0; let newstatus = 0;
@@ -472,8 +681,10 @@ sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysa
let typeidsearch = 0; let typeidsearch = 0;
let dest = ''; let dest = '';
let sender = myrecnotif.sender; let sender = myrecnotif.sender ? myrecnotif.sender : '';
let newdest = myrecnotif.dest; let newdest = myrecnotif.dest ? myrecnotif.dest : '';
let sendergroup = myrecnotif.sendergroup ? myrecnotif.sendergroup : '';
let newdestgroup = myrecnotif.destgroup ? myrecnotif.destgroup : '';
// Controllare se devo modificare un Notif già esistente ! // Controllare se devo modificare un Notif già esistente !
if (myrecnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) { if (myrecnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) {
@@ -533,23 +744,31 @@ sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysa
typeidsearch = shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT; typeidsearch = shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT;
if (myrecnotif.paramsObj.extrarec.hasOwnProperty('notifIdToUpdate')) if (myrecnotif.paramsObj.extrarec.hasOwnProperty('notifIdToUpdate'))
idnotiftosearch = myrecnotif.paramsObj.extrarec.notifIdToUpdate; idnotiftosearch = myrecnotif.paramsObj.extrarec.notifIdToUpdate;
if (myrecnotif.paramsObj.extrarec.hasOwnProperty('idStatusToSent'))
idnotiftosearch = myrecnotif.paramsObj.extrarec.idStatusToSent;
newstatus = shared_consts.CircuitsNotif.STATUS_COINS_ACCEPTED_SENT; newstatus = shared_consts.CircuitsNotif.STATUS_COINS_ACCEPTED_SENT;
} else if (myrecnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT) { } else if (myrecnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT) {
typeidsearch = shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT; typeidsearch = shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT;
if (myrecnotif.paramsObj.extrarec.hasOwnProperty('notifIdToUpdate')) if (myrecnotif.paramsObj.extrarec.hasOwnProperty('notifIdToUpdate'))
idnotiftosearch = myrecnotif.paramsObj.extrarec.notifIdToUpdate; idnotiftosearch = myrecnotif.paramsObj.extrarec.notifIdToUpdate;
if (myrecnotif.paramsObj.extrarec.hasOwnProperty('idStatusToSent'))
idnotiftosearch = myrecnotif.paramsObj.extrarec.idStatusToSent;
newstatus = shared_consts.CircuitsNotif.STATUS_COINS_REFUSED_SENT; newstatus = shared_consts.CircuitsNotif.STATUS_COINS_REFUSED_SENT;
} }
} }
if (newstatus) { if (newstatus) {
const fields_to_update = { let fields_to_update = {
status: newstatus, status: newstatus,
read: false, read: false,
descr: myrecnotif.descr, descr: myrecnotif.descr,
datenotif: new Date(), datenotif: new Date(),
sender, sender,
dest: newdest, dest: newdest,
sendergroup,
destgroup: newdestgroup,
}; };
let query = { let query = {
@@ -566,19 +785,28 @@ sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysa
_id: idnotiftosearch, _id: idnotiftosearch,
status: 0, status: 0,
}; };
}
fields_to_update = {
status: newstatus,
read: false,
descr: myrecnotif.descr,
datenotif: new Date(),
};
// Cerca il record e se lo trova lo aggiorna // Cerca il record e se lo trova lo aggiorna
const myrec = await SendNotif.findOneAndUpdate(query, { $set: fields_to_update }, { const myrec = await SendNotif.findOneAndUpdate(query, { $set: fields_to_update }, {
new: true, new: false,
returnNewDocument: true, returnNewDocument: true,
}); });
if (myrec) { if (myrec) {
return {myrecout: myrec, save: false}; return { myrecout: myrec, save: true };
} }
} }
}
// myrecnotif._id = new ObjectID(); // myrecnotif._id = new ObjectID();
if (newstatus > 0) { if (newstatus > 0) {
myrecnotif.status = newstatus; myrecnotif.status = newstatus;
@@ -624,11 +852,11 @@ sendNotifSchema.statics.checkIfCoinsAlreadySent = async function(notifId) {
}; };
sendNotifSchema.statics.saveNotif = async function(myrecnotif) { sendNotifSchema.statics.saveNotif = async function (myrecnotif, req) {
const SendNotif = this; const SendNotif = this;
const {myrecout, save} = await SendNotif.updateStatusAndDescr(myrecnotif, true); const { myrecout, save } = await SendNotif.updateStatusAndDescr(myrecnotif, true, req.user.username);
if (!myrecout) if (!myrecout)
return null; return null;
@@ -651,7 +879,9 @@ sendNotifSchema.statics.getDefaultRec = function(req) {
typedir: '', typedir: '',
typeid: '', typeid: '',
sender: req.user ? req.user.username : '', sender: req.user ? req.user.username : '',
sendergroup: '',
dest: '', dest: '',
destgroup: '',
descr: '', descr: '',
openUrl: '', openUrl: '',
datenotif: new Date(), datenotif: new Date(),
@@ -693,9 +923,11 @@ sendNotifSchema.statics.createNewNotification = async function(req, res, paramsO
myrecnotif.idrec = rec._id; myrecnotif.idrec = rec._id;
} }
myrecnotif.typedir = typedir; myrecnotif.typedir = typedir;
myrecnotif.typeid = typeid; myrecnotif.typeid = typeid;
await SendNotif.sendToTheDestinations(myrecnotif, req, res); await SendNotif.sendToTheDestinations(myrecnotif, req, res);
return true; return true;
@@ -736,6 +968,7 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r
// Send only to the destination to reach: // Send only to the destination to reach:
const userlist = await User.find({ const userlist = await User.find({
idapp: myrecnotifpass.idapp, idapp: myrecnotifpass.idapp,
// username: 'SuryaArena2', //TOGLIERE
$or: [ $or: [
{ deleted: { $exists: false } }, { deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }], { deleted: { $exists: true, $eq: false } }],
@@ -746,6 +979,9 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r
lang: 1, lang: 1,
username: 1, username: 1,
'profile.notifs': 1, 'profile.notifs': 1,
'profile.mycircuits': 1,
'profile.resid_province': 1,
'profile.resid_card': 1,
'profile.notif_idCities': 1, 'profile.notif_idCities': 1,
'profile.notif_provinces': 1, 'profile.notif_provinces': 1,
'profile.notif_regions': 1, 'profile.notif_regions': 1,
@@ -753,22 +989,29 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r
'profile.notif_sector_goods': 1, 'profile.notif_sector_goods': 1,
}).lean(); }).lean();
let arrcircuits = [];
let arrprovinces = []; let arrprovinces = [];
let arrregions = []; let arrregions = [];
let idSector = 0; let idSector = 0;
const mytable = globalTables.getTableByTableName(myrecnotifpass.tablerec); const mytable = globalTables.getTableByTableName(myrecnotifpass.tablerec);
if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA || myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS) {
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) || if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) ||
shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
const myrectableorig = await mytable.findOne({_id: myrecnotifpass.idrec}).lean(); if (myrecnotifpass.idrec && myrecnotifpass.idrec !== '0') {
// const myrectableorig = await mytable.findOne({ _id: myrecnotifpass.idrec }).lean();
const myrectableorig = await mytable.getCompleteRecord(myrecnotifpass.idapp, myrecnotifpass.idrec);
if (myrectableorig) { if (myrectableorig) {
for (const city of myrectableorig.idCity) { for (const city of myrectableorig.idCity) {
const prov = await City.getProvinceByIdCity(city);
arrprovinces.push(await City.getProvinceByIdCity(city)); arrprovinces.push(await City.getProvinceByIdCity(city));
arrregions.push(await City.getRegionByIdCity(city)); arrregions.push(await City.getRegionByIdCity(city));
arrcircuits.push(await City.getCircuitNameBystrProv(prov));
} }
if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) { if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) {
idSector = myrectableorig.idSectorGood; idSector = myrectableorig.idSectorGood;
} else { } else {
@@ -778,21 +1021,49 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r
} }
myrecnotifpass.myrectableorig = myrectableorig; myrecnotifpass.myrectableorig = myrectableorig;
} }
}
}
myrecnotifpass = await this.getDescrAndLinkByRecNotif(myrecnotifpass); myrecnotifpass = await this.getDescrAndLinkByRecNotif(myrecnotifpass, req.user.username);
delete myrecnotifpass._doc['_id']; delete myrecnotifpass._doc['_id'];
for (const user of userlist) { for (const user of userlist) {
const mycircuits = user.profile.mycircuits;
if (user.profile && user.profile.notifs) { if (user.profile && user.profile.notifs) {
const usernotifprofile = user.profile.notifs.find((notif) => notif.dir === myrecnotifpass.typedir); const usernotifprofile = user.profile.notifs.find((notif) => notif.dir === myrecnotifpass.typedir);
let send = false; let send = false;
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) ||
shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS) {
if (myrecnotifpass.tablerec === shared_consts.TABLES_MYBACHECAS) {
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_EVENTS_ATTEND)) {
send = true;
}
}
}
if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
if (shared_consts.TABLES_FAVORITE_BOOKMARK.includes(myrecnotifpass.tablerec)) {
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_FAVORITE_ADDED)) {
send = true;
}
}
} else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA
|| myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS
|| myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS
) {
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec)
|| shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)
|| shared_consts.TABLES_GROUPS_NOTIFICATION.includes(myrecnotifpass.tablerec)
) {
// Estrai la Città, la Provincia e la regione. // Estrai la Città, la Provincia e la regione.
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_YOUR_PROVINCE) &&
user.profile.resid_province && arrprovinces.indexOf(user.profile.resid_province) >= 0) {
send = true;
}
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_PROVINCE) && if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_PROVINCE) &&
user.profile.notif_provinces && user.profile.notif_provinces.some(r => arrprovinces.indexOf(r) >= 0)) { user.profile.notif_provinces && user.profile.notif_provinces.some(r => arrprovinces.indexOf(r) >= 0)) {
send = true; send = true;
@@ -803,6 +1074,11 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r
send = true; send = true;
} }
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_MY_RIS_CIRCUIT) &&
user.profile.mycircuits && user.profile.mycircuits.some(r => arrcircuits.indexOf(r.circuitname) >= 0)) {
send = true;
}
if (idSector && usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_SECTOR)) { if (idSector && usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_SECTOR)) {
// Controlla se è del settore selezionato // Controlla se è del settore selezionato
if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) { if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) {
@@ -815,17 +1091,24 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r
} }
} }
/*} else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS) {
if (shared_consts.TABLES_GROUPS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { if (shared_consts.TABLES_GROUPS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.GroupsNotifs.STATUS_GROUPS_NEW)) { if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.GroupsNotifs.STATUS_GROUPS_NEW)) {
send = true; send = true;
} }
} }
} else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS) {
if (shared_consts.TABLES_CIRCUITS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.CircuitsNotif.STATUS_NEW)) {
send = true;
}
}*/
}
if (send) { if (send) {
let myrecnotif = new SendNotif(myrecnotifpass); let myrecnotif = new SendNotif(myrecnotifpass);
myrecnotif.dest = user.username; myrecnotif.dest = user.username;
return await SendNotif.saveAndSendNotif(myrecnotif, req, res, user); await SendNotif.saveAndSendNotif(myrecnotif, req, res, user);
} }
} }
} }
@@ -847,7 +1130,7 @@ sendNotifSchema.statics.sendToSingleUserDest = async function(myrecnotif, req, r
: myrecnotif.dest; : myrecnotif.dest;
if (onlysave) { if (onlysave) {
return await SendNotif.saveNotif(myrecnotif); return await SendNotif.saveNotif(myrecnotif, req);
} else { } else {
return await SendNotif.saveAndSendNotif(myrecnotif, req, res, null); return await SendNotif.saveAndSendNotif(myrecnotif, req, res, null);
} }
@@ -859,13 +1142,15 @@ sendNotifSchema.statics.sendToSingleUserDest = async function(myrecnotif, req, r
}; };
sendNotifSchema.statics.getSumPendingTransactions = async function(idapp, username, circuitname) {
sendNotifSchema.statics.getSumPendingTransactionsMittente = async function (idapp, username, circuitname, groupname) {
const SendNotif = this; const SendNotif = this;
try { try {
const query = { const query = {
idapp, idapp,
sender: username, sender: username,
sendergroup: groupname,
typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS, typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ, typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
status: 0, status: 0,
@@ -880,6 +1165,60 @@ sendNotifSchema.statics.getSumPendingTransactions = async function(idapp, userna
}; };
sendNotifSchema.statics.getSumPendingTransactionsDest = async function (idapp, username, circuitname, groupname) {
const SendNotif = this;
try {
const query = {
idapp,
sender: username,
sendergroup: groupname,
typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
status: 0,
'extrarec.circuitname': circuitname,
'extrarec.dest': username,
'extrarec.groupdest': groupname,
};
return await SendNotif.find(query).lean();
} catch (e) {
console.error('e', e);
}
};
sendNotifSchema.statics.updatePendingTransactions = async function (recnotif) {
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
try {
if (recnotif && recnotif.extrarec && recnotif.extrarec.circuitname) {
const circuit = await Circuit.getCircuitByName(recnotif.idapp, recnotif.extrarec.circuitname);
const accountdestTable = await Account.getAccountByUsernameAndCircuitId(recnotif.idapp, recnotif.extrarec.dest, circuit._id, true, false, recnotif.extrarec.groupdest, recnotif.extrarec.contoComDest);
const accountorigTable = await Account.getAccountByUsernameAndCircuitId(recnotif.idapp, recnotif.sender, circuit._id, true, true, recnotif.extrarec.grouporig, recnotif.extrarec.contoComOrig);
if (accountdestTable)
await accountdestTable.calcPending(false);
if (accountorigTable)
await accountorigTable.calcPending(true);
}
} catch (e) {
console.error(e);
}
};
sendNotifSchema.statics.checkIfAlreadyExist = async function (idapp, tag, idpost, numtab) {
};
const SendNotif = mongoose.model('SendNotif', sendNotifSchema); const SendNotif = mongoose.model('SendNotif', sendNotifSchema);
module.exports = { SendNotif: SendNotif }; module.exports = { SendNotif: SendNotif };

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,12 +5,15 @@ const tools = require('../tools/general');
const server_constants = require('../tools/server_constants'); const server_constants = require('../tools/server_constants');
const shared_consts = require('../tools/shared_nodejs');
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 { Circuit } = require('../models/circuit'); const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
const _ = require('lodash'); const _ = require('lodash');
@@ -18,12 +21,18 @@ const {ObjectID} = require('mongodb');
async function getCircuitRecAdminsInfo(idapp, data) { async function getCircuitRecAdminsInfo(idapp, data) {
try {
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();
if (myuser && myuser.profile)
admin.profile = { img: myuser.profile.img }; admin.profile = { img: myuser.profile.img };
} }
} }
} catch (e) {
console.error(e);
return data;
}
return data; return data;
} }
@@ -40,6 +49,7 @@ router.post('/load', authenticate, async (req, res) => {
// 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);
@@ -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,7 +612,7 @@ 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) {
@@ -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) => {
if (ris)
return res.send({ mypage: 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,9 +5,10 @@ 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');
@@ -15,13 +16,14 @@ 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');
@@ -30,21 +32,35 @@ router.post('/page', authenticate, function(req, res, next) {
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 : '';
if (username) {
// 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, username, 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) => {
// Se è un record singolo di tipo Reaction,
// 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;
};
if (ris) { if (ris) {
res.send(ris); res.send(ris);

View File

@@ -36,6 +36,8 @@ 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'] : '';
@@ -44,6 +46,23 @@ router.post('/load', authenticate, async (req, res) => {
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) {
cities = await MyGroup.extractCitiesName(idapp, data._id); cities = await MyGroup.extractCitiesName(idapp, data._id);

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

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

View File

@@ -28,7 +28,8 @@ const _ = require('lodash');
const reg = require('../reg/registration'); const reg = require('../reg/registration');
const {authenticate} = require('../middleware/authenticate'); const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
const Cart = require('../models/cart'); const Cart = require('../models/cart');
const CartClass = require('../modules/Cart'); const CartClass = require('../modules/Cart');
@@ -38,6 +39,7 @@ const TypedError = require('../modules/ErrorHandler');
const { MyGroup } = require('../models/mygroup'); const { MyGroup } = require('../models/mygroup');
const { Circuit } = require('../models/circuit'); const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
const mongoose = require('mongoose').set('debug', false); const mongoose = require('mongoose').set('debug', false);
@@ -152,7 +154,7 @@ router.post('/', async (req, res) => {
if (lastrec.ipaddr === user.ipaddr) { if (lastrec.ipaddr === user.ipaddr) {
// Se l'ha fatto troppo ravvicinato // Se l'ha fatto troppo ravvicinato
if (lastrec.date_reg) { if (lastrec.date_reg) {
let ris = tools.isdiffSecDateLess(lastrec.date_reg, 120); let ris = tools.isdiffSecDateLess(lastrec.date_reg, 5);
if (ris) { if (ris) {
tools.writeIPToBan( tools.writeIPToBan(
user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' +
@@ -395,27 +397,67 @@ router.patch('/:id', authenticate, (req, res) => {
}); });
}); });
router.post('/profile', authenticate, (req, res) => { router.post('/receiveris', authenticate, (req, res) => {
const usernameOrig = req.user.username; const username = req.user ? req.user.username : '';
const groupname = req.body.groupname;
const idapp = req.body.idapp;
try {
if (!username)
return res.send({ code: server_constants.RIS_CODE_ERR });
if (groupname) {
return MyGroup.setReceiveRisGroup(idapp, groupname)
.then(risult => {
res.send({ code: server_constants.RIS_CODE_OK });
}).catch((err) => {
tools.mylog('ERRORE IN receiveris: ' + err.message);
res.status(400).send();
});
} else if (username) {
return User.setReceiveRis(idapp, username)
.then(risult => {
res.send({ code: server_constants.RIS_CODE_OK });
}).catch((err) => {
tools.mylog('ERRORE IN receiveris: ' + err.message);
res.status(400).send();
});
}
} catch (e) {
res.status(400).send();
};
});
router.post('/profile', authenticate_noerror, (req, res) => {
const usernameOrig = req.user ? req.user.username : '';
const perm = req.user ? req.user.perm : tools.Perm.PERM_NONE;
const username = req.body['username']; const username = req.body['username'];
const idapp = req.body.idapp; const idapp = req.body.idapp;
const locale = req.body.locale; const locale = req.body.locale;
//++Todo: controlla che tipo di dati ha il permesso di leggere //++Todo: controlla che tipo di dati ha il permesso di leggere
try { try {
// 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);
return User.getUserProfileByUsername(idapp, username, req.user.username, return User.getUserProfileByUsername(idapp, username, usernameOrig,
false, req.user.perm). false, perm).
then((ris) => { then((ris) => {
return User.getFriendsByUsername(idapp, req.user.username). return User.getFriendsByUsername(idapp, usernameOrig).
then((friends) => { then(async (friends) => {
res.send({user: ris, friends}); if (username === usernameOrig) {
const userprofile = await User.getExtraInfoByUsername(idapp, username);
ris.profile = userprofile;
}
return { ris, friends };
}).then(tot => {
return res.send({ user: tot.ris, friends: tot.friends });
}); });
}).catch((e) => { }).catch((e) => {
@@ -672,6 +714,33 @@ router.post('/circuits', authenticate, (req, res) => {
}); });
router.post('/updatesaldo', authenticate, async (req, res) => {
const username = req.user.username;
idapp = req.body.idapp;
locale = req.body.locale;
circuitId = req.body.circuitId;
groupname = req.body.groupname;
const lastdr = req.body['lastdr'] ? req.body['lastdr'] : '';
try {
const userprofile = await User.getExtraInfoByUsername(idapp, username);
let ris = {
userprofile
}
const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER);
ris.arrrecnotif = arrrecnotif;
return res.send({ ris });
} catch (e) {
tools.mylog('ERRORE IN updatesaldo: ' + e);
res.status(400).send();
};
});
router.post('/friends/cmd', authenticate, async (req, res) => { router.post('/friends/cmd', authenticate, async (req, res) => {
const usernameLogged = req.user.username; const usernameLogged = req.user.username;
const idapp = req.body.idapp; const idapp = req.body.idapp;
@@ -683,7 +752,12 @@ router.post('/friends/cmd', authenticate, async (req, res) => {
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
if (usernameOrig !== usernameLogged) { if ((usernameOrig !== usernameLogged) && (
(usernameDest !== usernameLogged) &&
((cmd === shared_consts.FRIENDSCMD.SETFRIEND) ||
(cmd === shared_consts.FRIENDSCMD.SETHANDSHAKE))
)) {
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: '' });
} }
@@ -703,6 +777,29 @@ router.post('/friends/cmd', authenticate, async (req, res) => {
}); });
router.post('/sendcmd', authenticate, async (req, res) => {
const usernameLogged = req.user.username;
const idapp = req.body.idapp;
const locale = req.body.locale;
let usernameOrig = req.body.usernameOrig;
let usernameDest = req.body.usernameDest;
const cmd = req.body.cmd;
const value = req.body.value;
usernameOrig = await User.getRealUsernameByUsername(idapp, usernameOrig);
usernameDest = await User.getRealUsernameByUsername(idapp, usernameDest);
return User.sendCmd(req, idapp, usernameOrig, usernameDest, cmd, value).
then((ris) => {
res.send(ris);
}).
catch((e) => {
tools.mylog('ERRORE IN sendcmd: ' + e.message);
res.status(400).send();
});
});
router.post('/groups/cmd', authenticate, (req, res) => { router.post('/groups/cmd', authenticate, (req, res) => {
const usernameLogged = req.user.username; const usernameLogged = req.user.username;
const idapp = req.body.idapp; const idapp = req.body.idapp;
@@ -741,6 +838,7 @@ router.post('/circuits/cmd', authenticate, async (req, res) => {
const value = req.body.value; const value = req.body.value;
const extrarec = req.body.extrarec; const extrarec = req.body.extrarec;
/*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
if (usernameOrig !== usernameLogged) { if (usernameOrig !== usernameLogged) {
@@ -767,12 +865,15 @@ router.post('/circuits/cmd', authenticate, async (req, res) => {
}); });
async function eseguiDbOp(idapp, mydata, locale) { async function eseguiDbOp(idapp, mydata, locale, req, res) {
let ris = await User.DbOp(idapp, mydata); let ris = await User.DbOp(idapp, mydata);
const populate = require('../populate/populate'); const populate = require('../populate/populate');
const globalTables = require('../tools/globalTables');
const { Reaction } = require('../models/reaction');
let mystr = ''; let mystr = '';
try { try {
@@ -1081,6 +1182,12 @@ async function eseguiDbOp(idapp, mydata, locale) {
ris = populate.rewriteTable('contribtypes'); ris = populate.rewriteTable('contribtypes');
} else if (mydata.dbop === 'ReplaceUsername') {
if (User.isAdmin(req.user.perm)) {
ris = globalTables.replaceUsername(req.body.idapp, mydata.search_username, mydata.replace_username);
}
} else if (mydata.dbop === 'copyFrom1To14') { } else if (mydata.dbop === 'copyFrom1To14') {
const idapporig = 1; const idapporig = 1;
const idappdest = 14; const idappdest = 14;
@@ -1119,6 +1226,21 @@ async function eseguiDbOp(idapp, mydata, locale) {
console.log('e', e); console.log('e', e);
} }
} else if (mydata.dbop === 'removeRecordsFav') {
// Passa le tabelle da users sulle nuove tabelle:
await User.removerecordsFavorite();
} else if (mydata.dbop === 'updateReactionsCounts') {
await Reaction.updateReactionsCounts();
} else if (mydata.dbop === 'newRecordsFav') {
// Passa le tabelle da users sulle nuove tabelle:
await User.moverecordsFavorite(1);
await User.moverecordsFavorite(2);
await User.moverecordsFavorite(3);
await User.moverecordsFavorite(4);
await User.moverecordsFavorite(5);
} else if (mydata.dbop === 'emptyTabCatServiziBeni') { } else if (mydata.dbop === 'emptyTabCatServiziBeni') {
const { Sector } = require('../models/sector'); const { Sector } = require('../models/sector');
@@ -1194,6 +1316,96 @@ async function eseguiDbOp(idapp, mydata, locale) {
await City.remove({}); await City.remove({});
await Province.remove({}); await Province.remove({});
} else if (mydata.dbop === 'ConvTablesFromIntToString') {
const { MySkill } = require('../models/myskill');
const { MyBacheca } = require('../models/mybacheca');
const { MyHosp } = require('../models/myhosp');
const { MyGood } = require('../models/mygood');
const { MyGroup } = require('../models/mygroup');
console.log('INIZIO - Conversioni');
// 'myskills',
// 'mybachecas',
// 'myhosps',
// 'mygoods',
// 'mygroups'
await ConvertiDaIntAStr(MySkill);
await ConvertiDaIntAStr(MyBacheca);
await ConvertiDaIntAStr(MyHosp);
await ConvertiDaIntAStr(MyGood);
await ConvertiDaIntAStr(MyGroup);
console.log('FINE - Conversioni');
} else if (mydata.dbop === 'Removeinteger') {
const { MySkill } = require('../models/myskill');
const { MyBacheca } = require('../models/mybacheca');
const { MyHosp } = require('../models/myhosp');
const { MyGood } = require('../models/mygood');
const { MyGroup } = require('../models/mygroup');
console.log('INIZIO - Rimozione');
await RimuoviInteri(MySkill);
await RimuoviInteri(MyBacheca);
await RimuoviInteri(MyHosp);
await RimuoviInteri(MyGood);
await RimuoviInteri(MyGroup);
console.log('FINE - Rimozione');
} else if (mydata.dbop === 'createAllCircuits') {
const { Province } = require('../models/province');
const arrProv = await Province.find({});
for (const recprov of arrProv) {
await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov);
}
} else if (mydata.dbop === 'ImpostaMinMaxPersonali') {
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, '');
} else if (mydata.dbop === 'ImpostaMinMaxPersonaliCircuito') {
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
} else if (mydata.dbop === 'ImpostaMinMaxComunitari') {
await Account.SetMinMaxComunitari(idapp, mydata.valmin, mydata.valmax);
} else if (mydata.dbop === 'ImpostaMinMaxCollettivi') {
await Account.SetMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax);
} else if (mydata.dbop === 'ImpostaDefMinMaxPersonali') {
await Circuit.SetDefMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
} else if (mydata.dbop === 'ImpostaDefMinMaxCollettivi') {
await Circuit.SetDefMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
} else if (mydata.dbop === 'AbilitaTuttiCircuiti') {
await Circuit.AbilitaTuttiCircuiti(idapp);
} else if (mydata.dbop === 'AzzeraRegolamentiTuttiCircuiti') {
await Circuit.AzzeraRegolamentiTuttiCircuiti(idapp);
} else if (mydata.dbop === 'setstrProvByIdCityCircuits') {
await Circuit.setstrProvByIdCityCircuits(idapp);
} else if (mydata.dbop === 'updateSaldoAndTransato_AllAccounts') {
await Account.updateSaldoAndTransato_AllAccounts(idapp);
/*} else if (mydata.dbop === 'visuNave') { /*} else if (mydata.dbop === 'visuNave') {
mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col)); mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col));
@@ -1228,7 +1440,123 @@ async function eseguiDbOp(idapp, mydata, locale) {
} catch (e) { } catch (e) {
console.log(e.message); console.log(e.message);
} }
};
async function ConvertiDaIntAStr(mytable) {
try {
console.log('INIZIO - ConvertiDaIntAStr ', mytable.modelName);
return await mytable.find({ '_id': { $type: 16 } })
.then(async (arr) => {
console.log('num record ', arr.length)
let ind = 0;
for (let x of arr) {
const idnew = x._id;
if (idnew < 10000) {
const idint = parseInt(x._id, 10) + 10000;
const myrec = new mytable(x._doc);
myrec._doc.date_created = x._doc.date_created;
myrec._doc.date_updated = x._doc.date_updated;
if (!myrec._doc.date_updated) {
if (myrec.hasOwnProperty('date_created'))
myrec._doc.date_updated = myrec._doc.date_created;
} }
if ((myrec.hasOwnProperty('date_updated') && !myrec._doc.date_created))
myrec._doc.date_created = myrec._doc.date_updated;
myrec._doc._id = idint + '';
let ris = await myrec.save((async function (err, doc) {
if (doc) {
ind++;
//await mytable.findOneAndRemove({ _id: parseInt(doc._id, 10) });
console.log('++Add (', ind, ')', doc._id);
} else {
const myid = parseInt(err.keyValue._id, 10) + 0;
const canc = await mytable.findOneAndRemove({ _id: myid });
if (canc)
console.log('err', err.message, 'canc', canc._doc._id);
}
}));
}
}
console.log('FINE - ConvertiDaIntAStr ', mytable.modelName);
});
} catch (err) {
console.error(err);
}
}
async function RimuoviInteri(mytable) {
try {
console.log('INIZIO - RimuoviInteri ', mytable.modelName);
const arr = await mytable.find({ '_id': { $lte: 10000 } })
console.log(' search interi...', arr.length);
const ris = await mytable.deleteMany({ '_id': { $lte: 10000 } })
console.log('FINE - RimuoviInteri ', mytable.modelName, ris);
} catch (err) {
console.error(err);
}
}
async function eseguiDbOpUser(idapp, mydata, locale, req, res) {
let ris = await User.DbOp(idapp, mydata);
const populate = require('../populate/populate');
const globalTables = require('../tools/globalTables');
let mystr = '';
try {
if (mydata.dbop === 'CreateAccountCircuits') {
const allcirc = await Circuit.find({ idapp });
for (const mycirc of allcirc) {
// Il Conto Comunitario prende il nome del circuito !
await Account.createAccount(idapp, '', mycirc.name, true, '', mycirc.path);
}
} else if (mydata.dbop === 'saveStepTut') {
await User.findOneAndUpdate({ _id: mydata._id },
{ $set: { 'profile.stepTutorial': mydata.value } });
} else if (mydata.dbop === 'noNameSurname') {
await User.findOneAndUpdate({ _id: mydata._id },
{ $set: { 'profile.noNameSurname': mydata.value } });
} else if (mydata.dbop === 'noCircuit') {
await User.findOneAndUpdate({ _id: mydata._id },
{ $set: { 'profile.noCircuit': mydata.value } });
} else if (mydata.dbop === 'noCircIta') {
await User.findOneAndUpdate({ _id: mydata._id },
{ $set: { 'profile.noCircIta': mydata.value } });
} else if (mydata.dbop === 'noFoto') {
await User.findOneAndUpdate({ _id: mydata._id },
{ $set: { 'profile.noFoto': mydata.value } });
}
} catch (e) {
}
};
router.post('/dbop', authenticate, async (req, res) => { router.post('/dbop', authenticate, async (req, res) => {
@@ -1236,10 +1564,47 @@ router.post('/dbop', authenticate, async (req, res) => {
idapp = req.body.idapp; idapp = req.body.idapp;
locale = req.body.locale; locale = req.body.locale;
try { if (!User.isAdmin(req.user.perm)) {
const ris = await eseguiDbOp(idapp, mydata, locale); // If without permissions, exit
return res.status(404).
send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
res.send(ris); try {
let ris = await eseguiDbOp(idapp, mydata, locale, req, res);
if (!ris) {
ris = {};
}
ris = await User.updateMyData(ris, idapp, req.user.username);
res.send({ code: server_constants.RIS_CODE_OK, data: ris.data });
} catch (e) {
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e });
console.log(e.message);
}
});
router.post('/dbopuser', authenticate, async (req, res) => {
const mydata = req.body.mydata;
idapp = req.body.idapp;
locale = req.body.locale;
try {
let ris = await eseguiDbOpUser(idapp, mydata, locale, req, res);
if (!ris) {
ris = {};
}
ris = await User.updateMyData(ris, idapp, req.user.username);
res.send({ code: server_constants.RIS_CODE_OK, ris });
} catch (e) { } catch (e) {
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e });
@@ -1269,4 +1634,5 @@ router.post('/mgt', authenticate, async (req, res) => {
}); });
module.exports = router; module.exports = router;

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');
// console.log('Starting pem...');
// const pem = require('pem')
const { Settings } = require('./models/settings'); 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);
@@ -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');
@@ -169,6 +160,9 @@ myLoad().then(ris => {
// app.use(express.cookieParser()); // app.use(express.cookieParser());
app.use(i18n.init); app.use(i18n.init);
console.log('Use Routes \...');
// Use Routes // Use Routes
app.use('/', index_router); app.use('/', index_router);
app.use('/subscribe', subscribe_router); app.use('/subscribe', subscribe_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);
@@ -238,14 +234,72 @@ myLoad().then(ris => {
console.log('*** PRODUCTION! '); console.log('*** PRODUCTION! ');
} }
if ((process.env.NODE_ENV === 'production') ||
(process.env.NODE_ENV === 'test')) {
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
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') || if ((process.env.NODE_ENV === 'production') ||
(process.env.NODE_ENV === 'test') || process.env.HTTPS_LOCALHOST === "true") { (process.env.NODE_ENV === 'test') || process.env.HTTPS_LOCALHOST === "true") {
var httpsServer = https.createServer(credentials, app);
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); console.log('httpsServer: port ', port);
httpsServer.listen(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);
} }
@@ -445,7 +499,7 @@ async function inizia() {
*/ */
console.log(process.versions);
} catch (e) { } catch (e) {

View File

@@ -2,15 +2,18 @@ const tools = require('../tools/general');
const appTelegram = [tools.FREEPLANET, tools.RISO]; const appTelegram = [tools.FREEPLANET, tools.RISO];
const appTelegram_TEST = [tools.FREEPLANET, tools.ARCADEI, tools.RISO]; const appTelegram_TEST = [tools.FREEPLANET, tools.RISO];
const appTelegram_DEVELOP = [tools.RISO]; const appTelegram_DEVELOP = [tools.RISO];
// const appTelegram_DEVELOP = [tools.FIOREDELLAVITA];
const appTelegramFinti = ['2', tools.CNM, tools.ARCADEI]; const appTelegramFinti = ['2', tools.CNM];
const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET, tools.FREEPLANET]; const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET];
//PIPPO
const printf = require('util').format; const printf = require('util').format;
const {User} = require('../models/user'); const { User, FuncUsers } = require('../models/user');
const { MyGroup } = require('../models/mygroup'); const { MyGroup } = require('../models/mygroup');
const { Circuit } = require('../models/circuit'); const { Circuit } = require('../models/circuit');
const { CalZoom } = require('../models/calzoom'); const { CalZoom } = require('../models/calzoom');
@@ -143,6 +146,7 @@ MsgBot = {
'grazie 😘', 'grazie 😘',
'grazie😘'], 'grazie😘'],
PRINCIPE_AZZURRO: ['principe azzurro'], PRINCIPE_AZZURRO: ['principe azzurro'],
START_INV: ['/start inv'],
COSE_COVID: [ COSE_COVID: [
'cos\'è il covid', 'cos\'è il covid',
'cosa è il covid', 'cosa è il covid',
@@ -450,8 +454,6 @@ const Status = {
const Cmd = { const Cmd = {
VALIDATE_REGISTRATION: 1, VALIDATE_REGISTRATION: 1,
RICHIESTA_GRUPPO: 2,
RICHIESTA_CIRCUIT: 3,
}; };
const Destin = { const Destin = {
@@ -478,8 +480,8 @@ const txt = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' +
emoji.get('dizzy'), emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Scrivete nel messaggio l\'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:', MSG_ASK_USERNAME_BO: 'Scrivete nel messaggio l\'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:',
MSG_ASK_USERNAME_INVITANTE: 'Scrivi <b>l\'username telegram</b> di chi ti ha invitato su %s (senza spazi)', MSG_ASK_USERNAME_INVITANTE: 'Scrivi nel messaggio <b>l\'USERNAME TELEGRAM</b> di chi ti ha INVITATO',
MSG_NEW_REG: '<br>Se non ce l\'avete, entrate sul Canale (<a href="https://t.me/+pZ40VpmL1NhkZjE0">PROGETTO RISO</a>), trovate la vostra provincia e chiedete di entrare nel gruppo.', MSG_NEW_REG: '<br><br>⁉️🙈 Per aiuto scrivi sulla <a href="https://t.me/riso_gruppo">Chat RISO</a><br>oppure direttamente a Paolo (@surya1977) ☀️.',
MSG_ERRORE_INVITANTE_NOT_FOUND: 'L\'username dell\'invitante appena digitato non sembra essere corretto! Ti ricordo che dev\'essere l\'username con cui si è registrato su RISO', MSG_ERRORE_INVITANTE_NOT_FOUND: 'L\'username dell\'invitante appena digitato non sembra essere corretto! Ti ricordo che dev\'essere l\'username con cui si è registrato su RISO',
MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (40 caratteri massimo)', MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (40 caratteri massimo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Per Completare la Verifica Telegram BOT, dovete ora scrivere qui sotto nel messaggio l\'Username (senza spazi) OPPURE la email con cui vi siete registrati sul sito', MSG_ERRORE_USERNAME_NOT_FOUND: 'Per Completare la Verifica Telegram BOT, dovete ora scrivere qui sotto nel messaggio l\'Username (senza spazi) OPPURE la email con cui vi siete registrati sul sito',
@@ -495,11 +497,12 @@ const txt = {
MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.', MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE + MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' Si è appena Registrato "%s" (n. %s)\nInvitato da %s', ' Si è appena Registrato "%s" (n. %s)\nInvitato da %s',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s si sta registrando alla App di RISO e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Amicizia di %s !', MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Amicizia di %s !',
MSG_HANDSHAKE_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Stretta di mano di %s !',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!\n' + MSG_APORTADOR_DEST_CONFIRMED: '✅ La tua registrazione a RISO è stata accettata da %s!\n' +
'Vai sulla App oppure clicca qui per entrare\n👉🏻 %s', 'Vai sulla App oppure clicca qui per entrare\n👉🏻 %s',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK + MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
@@ -543,7 +546,7 @@ const txt_es = {
MSG_EXIT_TELEGRAM: 'La cuenta ha sido desconectada de Telegram BOT.', MSG_EXIT_TELEGRAM: 'La cuenta ha sido desconectada de Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE + MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' Acaba de registrarse "%s (n. %s)"\n(Invitado de %s)', ' Acaba de registrarse "%s (n. %s)"\n(Invitado de %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!',
@@ -576,7 +579,7 @@ const txt_fr = {
MSG_EXIT_TELEGRAM: 'L\'account a été déconnecté de Telegram BOT.', MSG_EXIT_TELEGRAM: 'L\'account a été déconnecté de Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE + MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' Vous venez à peine de vous inscrire "%s (n. %s) %s', ' Vous venez à peine de vous inscrire "%s (n. %s) %s',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!',
@@ -607,7 +610,7 @@ const txt_si = {
MSG_EXIT_TELEGRAM: 'Račun se nahaja v programu Telegram BOT.', MSG_EXIT_TELEGRAM: 'Račun se nahaja v programu Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE + MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
'Registracija registracije %s (n. %s)\n(povabil ga %s)', 'Registracija registracije %s (n. %s)\n(povabil ga %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!',
@@ -637,7 +640,7 @@ const txt_en = {
MSG_EXIT_TELEGRAM: 'The account has now been disconnected from this Telegram BOT.', MSG_EXIT_TELEGRAM: 'The account has now been disconnected from this Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE + MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' He/She\'s just registered "%s (n. %s)"\n(Invited from %s)', ' He/She\'s just registered "%s (n. %s)"\n(Invited from %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!',
@@ -670,7 +673,7 @@ const txt_pt = {
MSG_EXIT_TELEGRAM: 'A conta foi agora desconectada deste Telegrama BOT.', MSG_EXIT_TELEGRAM: 'A conta foi agora desconectada deste Telegrama BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE + MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' Acabou de se registar "%s (n. %s)"\n(Convidado por %s)', ' Acabou de se registar "%s (n. %s)"\n(Convidado por %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente da %s!',
@@ -710,7 +713,7 @@ const MyTelegramBot = {
MyForm = null) { MyForm = null) {
if (!idtelegram) if (!idtelegram)
return; return { text: '' };
const cl = getclTelegByidapp(idapp); const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) { if (cl && idtelegram) {
@@ -719,6 +722,8 @@ const MyTelegramBot = {
chat_id, ripr_menuPrec); chat_id, ripr_menuPrec);
} }
return { text: '' };
}, },
deleteRecInMemByUsername: function (idapp, username_bo) { deleteRecInMemByUsername: function (idapp, username_bo) {
@@ -757,6 +762,11 @@ const MyTelegramBot = {
return FormDaMostrare; return FormDaMostrare;
}, },
getclTelegByidapp: function (idapp) {
const cl = getclTelegByidapp(idapp);
return cl;
},
getCiao: function (idapp, username, lang) { getCiao: function (idapp, username, lang) {
return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n'; return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n';
}, },
@@ -803,7 +813,7 @@ const MyTelegramBot = {
if (text) { if (text) {
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp,
addtext + text, false, null, userdest); addtext + text, false, null);
} }
}, },
@@ -821,18 +831,25 @@ const MyTelegramBot = {
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text); await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text);
}, },
askConfirmationUser: async function(idapp, myfunc, myuser, userDest = '', groupname = '', groupid = '', regexpire = '') { askConfirmationUser: async function (idapp, myfunc, myuser, userDest = '', name = '', groupid = '', regexpire = '', groupname = '') {
try { try {
const cl = getclTelegByidapp(idapp); const cl = getclTelegByidapp(idapp);
if (!cl) if (!cl)
return false; return false;
const langdest = myuser.lang; const langdest = myuser.lang;
const telegid = myuser.profile.teleg_id; const telegid = myuser.profile.teleg_id;
let userrecDest = await User.getUserShortDataByUsername(idapp, userDest);
let userId = userrecDest._id;
let title = this.getNomeAppByIdApp(idapp);
let keyb = null; let keyb = null;
let domanda = ''; let domanda = '';
let send_notif = false;
let actions = [];
const struserinfomsg = tools.getUserInfoMsg(idapp, myuser); const struserinfomsg = tools.getUserInfoMsg(idapp, myuser);
@@ -863,22 +880,22 @@ const MyTelegramBot = {
await setVerifiedReg(myuser.idapp, myuser.lang, myuser.username, userDest); await setVerifiedReg(myuser.idapp, myuser.lang, myuser.username, userDest);
} else { } else {
domanda = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM') + '<br>' + struserinfomsg; domanda = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM', myuser.username) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [ keyb = cl.getInlineKeyboard(myuser.lang, [
{ {
text: '✅ Abilita ' + myuser.username, text: '✅ Abilita ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest, callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest,
}, },
{ /*{
text: '🚫 Rifiuta ' + myuser.username, text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest, callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest,
}, }, */
]); ]);
} }
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) { } else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) {
domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), groupname) + '<br>' + struserinfomsg; domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [ keyb = cl.getInlineKeyboard(myuser.lang, [
{ {
@@ -890,23 +907,45 @@ const MyTelegramBot = {
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid, callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid,
}, },
]); ]);
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_CIRCUIT) { } else if (myfunc === shared_consts.CallFunz.RICHIESTA_FIDO) {
domanda = i18n.__({phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest}, groupname) + '<br>' + struserinfomsg; if (groupname) {
domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [ keyb = cl.getInlineKeyboard(myuser.lang, [
{ {
text: '✅ Accetta ' + myuser.username, text: '✅ Abilita fido a ' + groupname,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid + tools.SEP + groupname,
},
/*{
text: '🚫 Rifiuta ' + groupname,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid + tools.SEP + groupname,
},*/
]);
} else {
domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name) + '<br>' + struserinfomsg;
const keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Abilita fido a ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid, groupid,
}, },
{ /*{
text: '🚫 Rifiuta ' + myuser.username, text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid, groupid,
}, }, */
]); ]);
} }
}
if (send_notif) {
// SEND PUSH NOTIFICATION
await this.sendNotificationToUser(userId, title, descr, openUrl, '', tag, actions);
}
// Invia Msg // Invia Msg
if (domanda) { if (domanda) {
@@ -938,7 +977,7 @@ const MyTelegramBot = {
let typeid = 0; let typeid = 0;
let paramsObj = {}; let paramsObj = {};
const struserinfomsg = tools.getUserInfoMsg(idapp, myuser); const struserinfomsg = tools.getUserShortInfoMsg(idapp, myuser);
if (myfunc === shared_consts.CallFunz.RICHIESTA_AMICIZIA) { if (myfunc === shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
sendnotif = true; sendnotif = true;
@@ -958,6 +997,20 @@ const MyTelegramBot = {
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '', callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
}, },
]); ]);
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
sendnotif = true;
typedir = shared_consts.TypeNotifs.TYPEDIR_HANDSHAKE;
typeid = shared_consts.TypeNotifs.ID_HANDSHAKE_ACCEPTED;
paramsObj = { usernameDest: userDest };
domanda = printf(tools.gettranslate('RICHIESTA_HANDSHAKE', langdest), myuser.username) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅🤝 Ricambia la stretta di mano',
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
},
]);
} }
// Invia Msg // Invia Msg
@@ -1000,6 +1053,32 @@ const MyTelegramBot = {
}, },
sendMsgTelegramToTheAdminsOfCircuit: async function (
idapp, circuitpath, text, onlyintofile = false, MyForm = null, nottousername = '') {
tools.writeManagersLog(text);
let teleg_id = 0;
if (!onlyintofile) {
const usersmanagers = await Circuit.getListAdminsByCircuitPath(idapp, circuitpath);
if (usersmanagers) {
for (const rec of usersmanagers) {
if (rec.username !== nottousername) {
teleg_id = await User.TelegIdByUsername(idapp, rec.username);
if (teleg_id) {
await this.sendMsgTelegramByIdTelegram(idapp, teleg_id,
emo.ROBOT_FACE + ': ' + text, undefined, undefined, true,
MyForm);
await tools.snooze(100);
}
}
}
}
}
return true;
},
sendMsgTelegramToTheManagersAndZoomeri: async function ( sendMsgTelegramToTheManagersAndZoomeri: async function (
idapp, text, onlyintofile, MyForm = null) { idapp, text, onlyintofile, MyForm = null) {
@@ -1097,7 +1176,7 @@ const MyTelegramBot = {
}, },
sendMsgTelegramToTheAdmin: async function (idapp, text, senzaintestazione) { sendMsgTelegramToTheAdmin: async function (idapp, text, senzaintestazione) {
const usersmanagers = await User.getusersManagers(idapp); const usersmanagers = await User.getusersAdmin(idapp);
let intestaz = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': '; let intestaz = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': ';
if (senzaintestazione) if (senzaintestazione)
@@ -1158,8 +1237,6 @@ const MyTelegramBot = {
idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec, idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec,
MyForm = null) { MyForm = null) {
console.log('sendMsgTelegramByIdTelegram', text);
if (!idtelegram) if (!idtelegram)
return; return;
@@ -1244,43 +1321,10 @@ const MyTelegramBot = {
}; };
async function sendMsgTelegramToTheAdmin(idapp, text, msg) {
const usersmanagers = await User.getusersManagers(idapp);
const clorig = getclTelegByidapp(idapp);
const rec = clorig.getRecInMem(msg);
let username = '';
if (!!rec) {
username = rec.username_bo;
} else {
username = msg.chat.username;
}
text = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': Da ' +
msg.chat.first_name + ' ' + msg.chat.last_name + ' [' + username +
']: \n' + text;
tools.writeEventsLog(text);
if (usersmanagers) {
for (const rec of usersmanagers) {
if (User.isAdmin(rec.perm)) {
const idtelegram = rec.profile.teleg_id;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
await cl.sendMsg(idtelegram, text);
}
await tools.snooze(300);
}
}
}
return true;
}
async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) { async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) {
try { try {
await User.setVerifiedByAportador(idapp, usernameorig, true); await User.setVerifiedByAportador(idapp, usernameorig, true);
await User.setFriendsCmd(null, idapp, usernameorig, usernameDest, shared_consts.FRIENDSCMD.SETFRIEND); // await User.setFriendsCmd(null, idapp, usernameorig, usernameDest, shared_consts.FRIENDSCMD.SETFRIEND);
const msgDest = printf(getstr(lang, 'MSG_APORTADOR_CONFIRMED'), const msgDest = printf(getstr(lang, 'MSG_APORTADOR_CONFIRMED'),
`${usernameorig}`, usernameDest); `${usernameorig}`, usernameDest);
@@ -1328,6 +1372,32 @@ async function local_sendMsgTelegramToTheManagers(
} }
return true; return true;
}
async function local_sendMsgTelegramToTheAdmin(
idapp, text, msg, username_bo) {
const usersAdmin = await User.getusersAdmin(idapp);
let username = msg.chat.username;
if (username_bo)
username = username_bo;
text = emo.ROBOT_FACE + ': Da ' + msg.chat.first_name + ' ' +
msg.chat.last_name + ' (' + username + '): \n' + text;
tools.writeEventsLog(text);
if (usersAdmin) {
for (const rec of usersAdmin) {
const idtelegram = rec.profile.teleg_id;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
await cl.sendMsg(idtelegram, text, undefined, undefined, undefined,
undefined, true);
}
await tools.snooze(100);
}
}
return true;
} }
async function local_sendMsgTelegram(idapp, username, text) { async function local_sendMsgTelegram(idapp, username, text) {
@@ -1424,7 +1494,7 @@ class Telegram {
if (!riscreate) { if (!riscreate) {
let rec = this.getRecInMem(msg); let rec = this.getRecInMem(msg);
if (!rec) if (!rec)
rec = this.addUser(msg); rec = await this.addUser(msg);
if (rec.user) if (rec.user)
rec.status = Status.VERIFIED; rec.status = Status.VERIFIED;
@@ -1551,9 +1621,14 @@ class Telegram {
} }
} }
let parse_mode = 'HTML';
let arr_bott_inline = []
if (risp === '') { if (risp === '') {
if (menusite) { if (menusite) {
risp = await this.getValueMenu(this.idapp, rec, msg, testo, lang); risp = await this.getValueMenu(this.idapp, rec, msg, testo, lang);
parse_mode = await this.getParseModeByMenu(this.idapp, rec, msg, testo, lang);
arr_bott_inline = await this.getArrBottInlineByMenu(this.idapp, rec, msg, testo, lang);
noanswer = true; noanswer = true;
} else if (MsgBot.CIAO.includes(testo.replace('!', ''))) { } else if (MsgBot.CIAO.includes(testo.replace('!', ''))) {
risp = 'Ciao '; risp = 'Ciao ';
@@ -1625,6 +1700,9 @@ class Telegram {
} else if (MsgBot.PRINCIPE_AZZURRO.find( } else if (MsgBot.PRINCIPE_AZZURRO.find(
(rec) => testo.indexOf(rec) > -1)) { (rec) => testo.indexOf(rec) > -1)) {
risp = 'Chissà... Forse si!\nAnche se meglio averne un altro di scorta, nel caso il Principe non sia disponibile.'; risp = 'Chissà... Forse si!\nAnche se meglio averne un altro di scorta, nel caso il Principe non sia disponibile.';
} else if (MsgBot.START_INV.find(
(rec) => testo.indexOf(rec) > -1)) {
risp = 'Sei già registrato a RISO. Per accedere alla App, aprila dall\'icona sul tuo schermo, oppure vai su https://riso.app ed installa la App.\n\nSe hai dimenticato la password: \n clicca sul menu in basso su "⚒ Strumenti" e poi "🔑 Cambio Password"'
} else if (MsgBot.COSE_COVID.find( } else if (MsgBot.COSE_COVID.find(
(rec) => testo.indexOf(rec) > -1)) { (rec) => testo.indexOf(rec) > -1)) {
risp = 'Un \'influenza più "grave", dovuta a paure e a fattori interiori di evoluzione, oltre ad una pulizia del corpo. '; risp = 'Un \'influenza più "grave", dovuta a paure e a fattori interiori di evoluzione, oltre ad una pulizia del corpo. ';
@@ -1709,7 +1787,7 @@ class Telegram {
if (contastiera) { if (contastiera) {
keyboard = { keyboard = {
'parse_mode': 'HTML', 'parse_mode': parse_mode,
'reply_markup': { 'reply_markup': {
'resize_keyboard': true, 'resize_keyboard': true,
'keyboard': await this.getKeyboard(id, undefined, this.getlang(msg)), 'keyboard': await this.getKeyboard(id, undefined, this.getlang(msg)),
@@ -1718,6 +1796,12 @@ class Telegram {
} }
let keyboard_inline = undefined;
if (arr_bott_inline.length > 0) {
keyboard_inline = cl.getInlineKeyboard(myuser.lang, arr_bott_inline);
}
if (rec.numdomande > 3 && rec.msgcodeprec === '') { if (rec.numdomande > 3 && rec.msgcodeprec === '') {
// if (rec.user) { // if (rec.user) {
// const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username, rec.user.aportador_solidario_name_surname); // const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username, rec.user.aportador_solidario_name_surname);
@@ -1743,7 +1827,7 @@ class Telegram {
await tools.snooze(300); await tools.snooze(300);
risp = '[BOT' + emo.ROBOT_FACE + ' scrive]:\n' + risp; risp = '[BOT' + emo.ROBOT_FACE + ' scrive]:\n' + risp;
} }
this._inviaMsg(id, risp, keyboard); this._inviaMsg(id, risp, keyboard, undefined, undefined, undefined, undefined, { parse_mode, keyboard_inline });
let strlog = 'USER [' + myname + ']: ' + testo + '\n'; let strlog = 'USER [' + myname + ']: ' + testo + '\n';
@@ -2147,7 +2231,7 @@ class Telegram {
if (rec.user) { if (rec.user) {
mystr += printf( mystr += printf(
tools.get__('INFO_LINK_DA_CONDIVIDERE', this.getlang(msg)), tools.get__('INFO_LINK_DA_CONDIVIDERE', this.getlang(msg)),
tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username); tools.getHostByIdApp(this.idapp) + '/registrati/' + rec.user.username);
mystr += tools.ACAPO + tools.ACAPO + mystr += tools.ACAPO + tools.ACAPO +
printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)), printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)),
tools.getlinkzoom(null)); tools.getlinkzoom(null));
@@ -2306,8 +2390,13 @@ class Telegram {
async menuRestartSrv(rec, msg, cmd2) { async menuRestartSrv(rec, msg, cmd2) {
if (cmd2 === '6711') { if (cmd2 === '6711') {
await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha rilanciato il Server NODE.JS...'); await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha rilanciato il Server NODE.JS...');
const ris = await tools.execScript(this.idapp, msg, '~/batch/production_restart_server.sh', let file = '~/batch/production_restart_server.sh';
this.chisono(rec) + ' Restart il Server (Node.Js)'); if (process.env.NODE_ENV === 'test') {
file = '~/batch/test_restart_server.sh';
}
const ris = await tools.execScript(this.idapp, msg, file,
this.chisono(rec) + ' Restart il Server (Node.Js) : ' + process.version);
} else { } else {
this.nonAbilitato(msg); this.nonAbilitato(msg);
} }
@@ -2523,7 +2612,7 @@ class Telegram {
if (rec && !rec.aportador_solidario) { if (rec && !rec.aportador_solidario) {
rec.status = Status.SET_USERNAME_INVITANTE; rec.status = Status.SET_USERNAME_INVITANTE;
let mystr = getstr(this.getlang(msg), 'MSG_ASK_USERNAME_INVITANTE', tools.getNomeAppByIdApp(this.idapp), null); let mystr = getstr(this.getlang(msg), 'MSG_ASK_USERNAME_INVITANTE', null);
if (this.idapp === tools.RISO) { if (this.idapp === tools.RISO) {
mystr += getstr(this.getlang(msg), 'MSG_NEW_REG'); mystr += getstr(this.getlang(msg), 'MSG_NEW_REG');
@@ -2722,6 +2811,52 @@ class Telegram {
} }
} }
async addUserInDB_enteringInTelegramBot(msg) {
try {
// cerca se esiste già l'utente in Memoria
const rec = this.getRecInMem(msg);
if (!rec.user) {
// cerca se esiste già l'utente con il suo ID Telegram
const user = await User.UserByIdTelegram(this.idapp, msg.from.id);
if (!user) {
// Se non esiste già, creo la registrazione dell'Utente, senza password:
const myuserdata = {
idapp: this.idapp,
username: msg.from.username || msg.from.id,
name: msg.from.first_name || '',
lang: msg.from.language_code || 'it',
surname: msg.from.last_name || '',
profile: {
teleg_id: msg.from.id,
}
}
const recuser = await FuncUsers.createRegistration_withTelegram(myuserdata);
if (recuser) {
rec.user = recuser;
console.log(recuser.username, ' SI E\' VERIFICATO CON TELEGRAM !');
// let username = recuser.name;
/*if (!!msg.from.username) {
await MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, recuser);
} else {
console.log(' ... MA GLI MANCA L\'USERNAME TELEGRAM !! ');
} */
}
}
}
return { ris: !!rec.user, recuser: rec.user };
} catch (e) {
console.error('Error addUserInDB_enteringInTelegramBot', e);
}
return { ris: false, recuser: null };
}
async sistemaRecDest(rec, msg) { async sistemaRecDest(rec, msg) {
let recdest = this.getRecByUsername(rec.msgall_username_specifico); let recdest = this.getRecByUsername(rec.msgall_username_specifico);
if (!recdest) { if (!recdest) {
@@ -2746,8 +2881,6 @@ class Telegram {
async setCmdToUsername(rec, username, cmd_to_set, valuebool) { async setCmdToUsername(rec, username, cmd_to_set, valuebool) {
if (cmd_to_set === Cmd.VALIDATE_REGISTRATION) { if (cmd_to_set === Cmd.VALIDATE_REGISTRATION) {
return await User.setVerifiedByAportador(rec.user.idapp, username, valuebool); return await User.setVerifiedByAportador(rec.user.idapp, username, valuebool);
} else if (cmd_to_set === Cmd.RICHIESTA_GRUPPO) {
} }
} }
@@ -2982,12 +3115,13 @@ class Telegram {
let mymsg = msg.text.toString().trim().toLowerCase(); let mymsg = msg.text.toString().trim().toLowerCase();
let invitante = ''; let invitante = '';
let regexpire = ''; let regexpire = '';
const sep = '-'
if (mymsg.startsWith('/start')) { if (mymsg.startsWith('/start')) {
let myarrmsg = mymsg.split(' '); let myarrmsg = mymsg.split(' ');
if (myarrmsg.length > 0) { if (myarrmsg.length > 0) {
mymsg = myarrmsg[1]; mymsg = myarrmsg[1];
if (mymsg.startsWith('inv_')) { if (mymsg.startsWith('inv' + sep)) {
let arrparams = mymsg.split('_'); let arrparams = mymsg.split(sep);
if (arrparams.length > 2) { if (arrparams.length > 2) {
invitante = arrparams[1]; invitante = arrparams[1];
regexpire = arrparams[3]; regexpire = arrparams[3];
@@ -3031,9 +3165,13 @@ class Telegram {
} }
const rec = this.getRecInMem(msg); const rec = this.getRecInMem(msg);
let testo = msg.text.toLowerCase().trim();
status = this.getstatus(rec); status = this.getstatus(rec);
if (status === Status.WAITFOR_USERNAME_TELEGRAM && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) { if (testo === Menu.EXIT_TELEGRAM) {
await this.menuExitToTelegram(msg);
} else if (status === Status.WAITFOR_USERNAME_TELEGRAM && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) {
// await this.setUsernameBo(msg); // await this.setUsernameBo(msg);
await this.settotheDatabase(msg); await this.settotheDatabase(msg);
} else if (status === Status.WAITFOR_USERNAME_INVITANTE && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) { } else if (status === Status.WAITFOR_USERNAME_INVITANTE && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) {
@@ -3203,10 +3341,10 @@ class Telegram {
const id = this.getchatid(msg); const id = this.getchatid(msg);
let rec = null; let rec = null;
try { try {
const user = await User.UserByIdTelegram(this.idapp, id); let user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.getRecInMem(msg); let rec = this.getRecInMem(msg);
if (user && !rec) { if (user && !rec) {
rec = this.addUser(msg); rec = await this.addUser(msg);
} }
if (rec) { if (rec) {
rec.user = user; rec.user = user;
@@ -3228,7 +3366,7 @@ class Telegram {
} }
} }
addUser(msg) { async addUser(msg) {
const lang = this.getlang(msg); const lang = this.getlang(msg);
const code = 100000 + Math.round(Math.random() * 899999); const code = 100000 + Math.round(Math.random() * 899999);
@@ -3260,20 +3398,37 @@ class Telegram {
pageChange: false, pageChange: false,
menuSaved: {}, menuSaved: {},
pagenow: 1, pagenow: 1,
parse_mode: 'HTML',
menuDb: null, menuDb: null,
aportador_solidario: '', aportador_solidario: '',
}; };
rec.status = Status.NONE;
if (!msg.from.username) { if (!msg.from.username) {
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskUsernameSulBot)) {
rec.status = Status.WAITFOR_USERNAME_TELEGRAM; rec.status = Status.WAITFOR_USERNAME_TELEGRAM;
}
} else { } else {
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) {
rec.status = Status.WAITFOR_USERNAME_INVITANTE; rec.status = Status.WAITFOR_USERNAME_INVITANTE;
} }
}
this.arrUsers.push(rec); this.arrUsers.push(rec);
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) {
// Aportador // Aportador
this.setInvitante(msg, this.getInvitanteByMsg(msg), false); this.setInvitante(msg, this.getInvitanteByMsg(msg), false);
}
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.registerUserWithBot)) {
const ris = await this.addUserInDB_enteringInTelegramBot(msg);
if (ris && ris.recuser) {
rec.recuser = ris.recuser;
rec.status = Status.VERIFIED;
}
}
return rec; return rec;
@@ -3327,13 +3482,13 @@ class Telegram {
for (const rec of recuser.menuDb) { for (const rec of recuser.menuDb) {
rec.active_mem = false; rec.active_mem = false;
const visibilita = (tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_ADMIN, isAdmin)
&& tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_MANAGER, isManager)
&& tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLYIF_VERIFIED, isVerified))
|| rec.visibility === 0;
if (rec.active && rec.page === recuser.pagenow if (rec.active && rec.page === recuser.pagenow
&& (tools.isBitAttivoESelez(rec.visibility, && visibilita
shared_consts.VISIB_ONLY_ADMIN, isAdmin) &&
tools.isBitAttivoESelez(rec.visibility,
shared_consts.VISIB_ONLY_MANAGER, isManager) &&
tools.isBitAttivoESelez(rec.visibility,
shared_consts.VISIB_ONLYIF_VERIFIED, isVerified))
) { ) {
rec.active_mem = true; rec.active_mem = true;
if (true) { if (true) {
@@ -3419,6 +3574,8 @@ class Telegram {
this.isMenu(recuser, msg, recdb.value, true); this.isMenu(recuser, msg, recdb.value, true);
return shared_consts.RIS_OK; return shared_consts.RIS_OK;
} }
} else if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) {
return recdb.value;
} }
} }
@@ -3432,6 +3589,59 @@ class Telegram {
} }
async getParseModeByMenu(idapp, recuser, msg, testo, lang) {
try {
let parse_mode = 'HTML';
if (recuser) {
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
if (recdb.idapp === idapp && recdb.lang === lang &&
recdb.label.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) {
return 'Markdown'
} else {
return parse_mode;
}
}
}
}
}
return '';
} catch (e) {
return '';
}
}
async getArrBottInlineByMenu(idapp, recuser, msg, testo, lang) {
try {
let arr_bott_inline = [];
if (recuser) {
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
if (recdb.idapp === idapp && recdb.lang === lang &&
recdb.label.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_BOTTONI_INLINE) {
const jsonString = '[{"text": "primo", "callback_data": "1"}, {"text": "sec", "callback_data": "2"}]';
const jsonObject = JSON.parse(jsonString);
let myobj = JSON.parse(recdb.value);
arr_bott_inline.push(myobj);
}
}
}
}
}
return arr_bott_inline;
} catch (e) {
console.error(e);
return [];
}
}
async getKeyboard(id, menu, lang) { async getKeyboard(id, menu, lang) {
let keyb = null; let keyb = null;
@@ -3473,9 +3683,11 @@ class Telegram {
return 0; return 0;
if (process.env.LOCALE === '1') { if (process.env.LOCALE === '1') {
if (id !== ADMIN_IDTELEGRAM_TEST) if (id !== ADMIN_IDTELEGRAM_TEST) {
text = '[Msg da inviare ipoteticamente a : ' + id + ']' + '\n' + text;
id = '12429864'; id = '12429864';
} }
}
if (!!msg_id) { if (!!msg_id) {
return this.modificaMsg(chat_id, msg_id, text); return this.modificaMsg(chat_id, msg_id, text);
@@ -3508,7 +3720,7 @@ class Telegram {
} }
try { try {
console.log('<<< SEND MSG TELEGRAM: >>> ', text.substring(0, 100)); console.log('<<< SEND MSG TELEGRAM: >>> [id=', id, ']', text.substring(0, 100));
text = text.replace(/<br>/g, '\n'); text = text.replace(/<br>/g, '\n');
text = text.replace(/<br\/>/g, '\n'); text = text.replace(/<br\/>/g, '\n');
text = text.replace(/<div>/g, ''); text = text.replace(/<div>/g, '');
@@ -3522,13 +3734,15 @@ class Telegram {
// text = text.replace(/<\/div>/g, ''); // text = text.replace(/<\/div>/g, '');
text = text.replace(/&nbsp;/g, ' '); text = text.replace(/&nbsp;/g, ' ');
if (!form) { if (!form) {
form = { form = {
'parse_mode': 'HTML', 'parse_mode': opt && opt.parse_mode ? opt.parse_mode : 'HTML',
'message_id': msg_id, 'message_id': msg_id,
'reply_markup': { 'reply_markup': {
'resize_keyboard': true, 'resize_keyboard': true,
'keyboard': await this.getKeyboard(id, menu, mylang), 'keyboard': await this.getKeyboard(id, menu, mylang),
'keyboard_inline': (opt && opt.keyboard_inline) ? opt.keyboard_inline : undefined,
}, },
}; };
} }
@@ -3599,7 +3813,10 @@ class Telegram {
async sendMsgLog(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) { async sendMsgLog(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) {
const rec = this.getRecInMemById(id); const rec = this.getRecInMemById(id);
const username = rec ? rec.username_bo : ''; let username = rec ? rec.username_bo : '';
if (!username) {
}
console.log('Msg inviato a ', username, '(', id, ')', text); console.log('Msg inviato a ', username, '(', id, ')', text);
return await this.sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec); return await this.sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec);
@@ -3889,6 +4106,7 @@ if (true) {
userDest: '', userDest: '',
groupId: 0, groupId: 0,
circuitId: '', circuitId: '',
groupname: '',
}; };
const datastr = callbackQuery.data; const datastr = callbackQuery.data;
@@ -3901,6 +4119,7 @@ if (true) {
userDest: dataarr[2] ? dataarr[2] : '', userDest: dataarr[2] ? dataarr[2] : '',
groupId: dataarr[3] ? parseInt(dataarr[3]) : '', groupId: dataarr[3] ? parseInt(dataarr[3]) : '',
circuitId: dataarr[4] ? dataarr[4] : '', circuitId: dataarr[4] ? dataarr[4] : '',
groupname: dataarr[5] ? dataarr[5] : '',
}; };
} }
} }
@@ -3966,7 +4185,7 @@ if (true) {
if (changed) { if (changed) {
const req = tools.getReqByPar(user.idapp, username_action); const req = tools.getReqByPar(user.idapp, username_action);
await User.setFriendsCmd(req, user.idapp, data.username, userDest.username, shared_consts.FRIENDSCMD.SETFRIEND, null, true); // await User.setFriendsCmd(req, user.idapp, data.username, userDest.username, shared_consts.FRIENDSCMD.SETFRIEND, null, true);
await User.setaportador_solidario(user.idapp, data.username, userDest.username); await User.setaportador_solidario(user.idapp, data.username, userDest.username);
@@ -3976,6 +4195,8 @@ if (true) {
await local_sendMsgTelegram(user.idapp, data.username, msgOrig); await local_sendMsgTelegram(user.idapp, data.username, msgOrig);
await local_sendMsgTelegram(user.idapp, data.userDest, msgDest); await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
// Invia questo msg anche all'Admin
await local_sendMsgTelegramToTheAdmin(user.idapp, msgDest, msg, data.userDest);
} }
} else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.REGISTRATION) { } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.REGISTRATION) {
@@ -4018,27 +4239,29 @@ if (true) {
} }
} }
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) { } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_FIDO) {
if (circuit) { if (circuit) {
cmd = shared_consts.CIRCUITCMD.SET; cmd = shared_consts.CIRCUITCMD.SETFIDO;
const foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(user.idapp, data.username, circuit.name);
if (!foundIfAlreadyCircuit) {
// Aggiungilo nel Circuito // Aggiungilo nel Circuito
await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action); // await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
} // Abiglitagli il Fido
await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
} }
} else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_CIRCUIT) { } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
if (circuit) { if (circuit) {
cmd = shared_consts.CIRCUITCMD.REFUSE_REQ; cmd = shared_consts.CIRCUITCMD.REFUSE_REQ;
const foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(user.idapp, data.username, circuit.name); let foundIfAlreadyCircuit = false;
if (data.groupname) {
foundIfAlreadyCircuit = await MyGroup.ifCircuitAlreadyInGroup(user.idapp, data.groupname, circuit.name);
} else {
foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(user.idapp, data.username, circuit.name);
}
if (foundIfAlreadyCircuit) { if (foundIfAlreadyCircuit) {
// Rimuovilo nel Circuito // Rimuovilo nel Circuito
await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action); await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
} }
} }
@@ -4069,7 +4292,25 @@ if (true) {
await local_sendMsgTelegram(user.idapp, data.userDest, msgDest); await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
} }
} }
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
if (userDest) {
cmd = shared_consts.FRIENDSCMD.SETHANDSHAKE;
const foundIfAlreadyFriend = await User.isMyHandShake(user.idapp, data.userDest, data.username);
if (!foundIfAlreadyFriend) {
// Aggiungilo nelle HandShake
const req = tools.getReqByPar(user.idapp, username_action);
const ris = await User.setFriendsCmd(req, user.idapp, data.userDest, data.username, cmd);
} }
}
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.ENTRA_RIS_ITALIA) {
url = '';
bot.answerCallbackQuery(callbackQuery.id, { url });
} }
} }
} catch (e) { } catch (e) {

File diff suppressed because it is too large Load Diff

View File

@@ -16,6 +16,7 @@ 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 { Reaction } = require('../models/reaction');
const { Contribtype } = require('../models/contribtype'); const { Contribtype } = require('../models/contribtype');
const { PaymentType } = require('../models/paymenttype'); const { PaymentType } = require('../models/paymenttype');
const { Discipline } = require('../models/discipline'); const { Discipline } = require('../models/discipline');
@@ -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 = '';
@@ -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) {
@@ -285,7 +297,9 @@ 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 = '';
@@ -365,6 +379,7 @@ module.exports = {
{ {
username: 1, username: 1,
'profile.teleg_id': 1, 'profile.teleg_id': 1,
'profile.notifs': 1,
}, },
).lean(); ).lean();
@@ -372,10 +387,25 @@ module.exports = {
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;
let sendmsg = false;
if (params.typenotif === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
if (!usernotifprofile || (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_FAVORITE_ADDED))) {
sendmsg = true;
}
} else {
sendmsg = true;
}
if (sendmsg) {
if (params.sendreally) { if (params.sendreally) {
if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) { if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) {
const myparam = { ...params }; const myparam = { ...params };
@@ -395,7 +425,7 @@ module.exports = {
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;
} }
@@ -412,8 +442,10 @@ module.exports = {
} }
} }
} }
}
if (nummsgsent > 0) { if (nummsgsent > 0) {
if (nummsgsent != numrec && (numrec !== 1))
console.log('FINE Invio Messaggi ! Inviati Totali: ', nummsgsent, 'su', numrec); console.log('FINE Invio Messaggi ! Inviati Totali: ', nummsgsent, 'su', numrec);
} }
@@ -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,18 +140,47 @@ 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'],
@@ -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: [
@@ -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,12 +478,19 @@ 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,
}, },
@@ -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