85 Commits

Author SHA1 Message Date
Surya Paolo
0c2a8ecef5 AITools prime cose 2024-01-30 14:00:37 +01:00
Surya Paolo
aeabf96efe agiornamento, sistemazioni varie PCB 2024-01-23 00:10:40 +01:00
Surya Paolo
e4504bcf9e regNameSurnameMandatory
askUSernameTelegramToTheReg
@ davanti all'username
2024-01-19 23:38:08 +01:00
Surya Paolo
dbcdbd689b fix order non si vedeva.. e msg login errato 2024-01-17 21:49:59 +01:00
Surya Paolo
f6a0876178 fix problema sul caricamento della home da offline... 2024-01-17 20:30:07 +01:00
Surya Paolo
1ef3103a9d risolto qtaminima "|" era sbagliato, corretto: product.minBuyQty || 1 2024-01-17 11:13:13 +01:00
Surya Paolo
d7122af70e ciao corretto 2024-01-16 23:09:04 +01:00
Surya Paolo
3d1a330fa2 Poter inserire un Ordine anche per un altra persona... (Modalità Cassa) 2024-01-16 23:00:10 +01:00
Surya Paolo
a2c9dcb38c gasordine 2024-01-16 17:09:55 +01:00
Surya Paolo
d22e808626 aggio gasordine 2024-01-16 16:56:39 +01:00
Surya Paolo
9265e9bfb3 fix_ismanager 2024-01-16 11:22:22 +01:00
Surya Paolo
504e9fd88c fix2 2024-01-16 11:17:48 +01:00
Surya Paolo
4b9fe4d267 fix 2024-01-16 11:16:31 +01:00
Surya Paolo
d81f533ecb fix totqta 2024-01-16 10:49:20 +01:00
Surya Paolo
65d75cb2c5 aggio 2024-01-16 09:05:02 +01:00
Surya Paolo
212f895650 corretto 2024-01-15 22:46:38 +01:00
Surya Paolo
3183825137 possibilità di modificare un ordine, e anche i totali 2024-01-15 22:19:26 +01:00
Surya Paolo
79ca364e84 product 2024-01-13 16:21:07 +01:00
Surya Paolo
7bf549569d - edit campi prodotti
- edit ordini
2024-01-13 00:28:53 +01:00
Surya Paolo
c63e345285 subcatprod 2024-01-12 13:02:59 +01:00
Surya Paolo
9b4a9dbf28 aggio modif 2024-01-10 20:44:43 +01:00
Surya Paolo
a71c487697 email da inviare ai clienti ... 2024-01-09 23:57:30 +01:00
Surya Paolo
3dfb990620 aggiorna 2024-01-09 15:31:59 +01:00
Surya Paolo
4cdc4f7de1 pcb 2024-01-09 08:38:00 +01:00
Surya Paolo
7ea6c2a76b aggio numtransaction 2024-01-09 08:34:28 +01:00
Surya Paolo
db81980046 Corretto il pagato
- fix Group Add link
2024-01-07 17:27:20 +01:00
Surya Paolo
fb16a1729e menu RIS 2024-01-07 16:03:39 +01:00
Surya Paolo
d7ae8baec4 inserimento in Movimenti del Circuito 2024-01-04 15:43:13 +01:00
Surya Paolo
b754492b41 - abilitato circuits e groups 2024-01-03 23:46:31 +01:00
Surya Paolo
0aaa331b3f addOrderToMovement 2024-01-03 23:19:15 +01:00
Surya Paolo
66e4c577c7 addtocash using sendcoins Circuit 2024-01-03 15:46:42 +01:00
Surya Paolo
75ef581635 update 2024-01-02 15:39:29 +01:00
Surya Paolo
4e0c18f47c ++ Cassa - parte 1 2024-01-02 15:24:44 +01:00
Surya Paolo
3fb78ff39a - migliorata grafica prodotti 2023-12-31 14:34:01 +01:00
Surya Paolo
6313476d54 - migliorie grafiche 2023-12-30 23:58:35 +01:00
Surya Paolo
b6204c7612 - Uscita PRIMA VERSIONE PiuCheBuono.app 2023-12-30 21:33:59 +01:00
Surya Paolo
ade9c149c5 - preordinabili corretti + altro 2023-12-29 21:17:17 +01:00
Surya Paolo
633b9a2d8c aggiornato prodotti e scontistica 2023-12-29 15:19:15 +01:00
Surya Paolo
3d1dddba39 - poster 2023-12-29 01:27:47 +01:00
Surya Paolo
db7724cca4 - aggiunta campi Gas data + fix 2023-12-28 23:53:11 +01:00
Surya Paolo
5afe9dd1e2 - aggiunta campi Gas data + fix 2023-12-28 23:48:03 +01:00
Surya Paolo
c001587702 - filtro se GAS o Prodotti 2023-12-28 21:00:02 +01:00
Surya Paolo
ca6d29414a - Email Ordine da template HTML 2023-12-28 15:53:00 +01:00
Surya Paolo
f23047bcd5 - Aggiornamento template mail (tramite i campi in HTML)
- Aggiornato Carrello
2023-12-28 00:50:35 +01:00
Surya Paolo
15d831eecc - Categorie
- ProductInfo
2023-12-27 02:58:15 +01:00
Surya Paolo
f0495d93b3 Seleziona l'ordine GAS e compare sulla email 2023-12-24 00:55:49 +01:00
Surya Paolo
0eb287db06 - Creazione pagina Home logout
- Nuovo Gasordine
- Visualizzazione GAS / BOTTEGA
2023-12-21 15:21:24 +01:00
Surya Paolo
322bfb9738 Merge branch 'Dev_PDB1' of ssh://risosrv:5522/~/repository/freeplanet_serverside into Dev_PDB1 2023-12-21 10:58:18 +01:00
Surya Paolo
428a5ca0e9 modif 2023-12-21 10:58:15 +01:00
Surya Paolo
000e900f48 ++GasOrdini 2023-12-21 02:23:52 +01:00
Surya Paolo
2ab4bd4e2a Corretto incongruenze OrdersCart 2023-12-21 01:34:33 +01:00
Surya Paolo
7af909d2be Aggiornamento modifiche preOrdini 2023-12-20 21:56:15 +01:00
Surya Paolo
0e1fc359a0 Aggiornamento modifiche preOrdini 2023-12-20 21:52:17 +01:00
Surya Paolo
d00c7eccc8 Corretto l'url delle immagini dei prodotti ! 2023-12-18 16:37:26 +01:00
Surya Paolo
7e7d7ca6b4 Aggiungi il codice alla cassa in automatico 2023-12-18 15:21:07 +01:00
Surya Paolo
a3913a4575 corretto totali in attesa 2023-12-18 13:04:38 +01:00
Surya Paolo
7628fb97fc Carrello con scontistica aggiornata 2023-12-18 12:11:12 +01:00
Surya Paolo
56b5bac5f0 Merge branch 'Dev_PDB1' of ssh://risosrv:5522/~/repository/freeplanet_serverside into Dev_PDB1 2023-12-18 08:34:51 +01:00
Surya Paolo
e7021e1f14 aaa 2023-12-18 08:32:03 +01:00
Surya Paolo
139d7ea33c Risolto problema blocco 2023-12-18 08:02:28 +01:00
Surya Paolo
50d610b1b1 aggiornamento... 2023-12-17 19:19:04 +01:00
Surya Paolo
c71f4af370 Abilitazione del BOT 2023-12-17 16:20:44 +01:00
Surya Paolo
4290895a97 aggiornamento scontistica, corretto errori 2023-12-16 18:40:17 +01:00
Surya Paolo
ab3a31d4fb Scontistica- Parte 1 2023-12-16 00:51:03 +01:00
Surya Paolo
1ca72118f1 lista ordini aggiornata 2023-12-15 23:36:43 +01:00
Surya Paolo
4d9eccd1ae Corretto Ordini e visualizzazione dei Totali 2023-12-15 21:50:21 +01:00
Surya Paolo
05ec283882 import dati prodotti + fornitore + produttore 2023-12-15 00:57:14 +01:00
Surya Paolo
ea2b7095c9 aggiornamento ordini 2023-12-14 15:20:21 +01:00
Surya Paolo
d0bf7e1b6a aggiornato stockQta quando l'ordine viene evaso 2023-12-14 00:55:07 +01:00
Surya Paolo
fcdd826c54 Gestione Ordini: evaso... 2023-12-13 19:17:53 +01:00
Surya Paolo
a2bd4f6e97 aggio query 2023-12-12 15:42:41 +01:00
Surya Paolo
5f3c8a65ea corretto abiltiazione fiducia concessa 2023-12-12 00:56:40 +01:00
Surya Paolo
caadbaae5f aggio2 2023-12-11 20:48:52 +01:00
Surya Paolo
296b7b4fb8 modif 2023-12-11 19:06:22 +01:00
Surya Paolo
ff81ab7be3 dev 2023-12-11 11:25:16 +01:00
Surya Paolo
8ce4f66c55 a1p 2023-12-11 10:10:52 +01:00
Surya Paolo
daacde7455 aggiornamento visualizzazione Ordini e Carrello 2023-12-09 19:38:23 +01:00
Surya Paolo
023ba26003 aggiornamento Indici 2023-12-09 11:55:58 +01:00
Surya Paolo
502ed32c42 - Installazione primo Sito Web del server
- Creazione prima pagina Home
2023-12-09 00:19:40 +01:00
Surya Paolo
74c4a829b0 Creazione Sito Web da pagina 2023-12-08 14:07:32 +01:00
Surya Paolo
f7bcb0c361 modif 2023-12-07 11:28:01 +01:00
Surya Paolo
72a7e3fa37 modif 2023-12-07 11:27:30 +01:00
Surya Paolo
4871c2d868 Aggiornata Chiave Segreta per accesso SIGNCODE.
- Inserito autenticazione MongoDB ai database.
-PCB: Aggiunto altri campi a products
2023-12-07 08:34:24 +01:00
Surya Paolo
d5bc76335f - Entri in Circuito Italia solo se hai il fido nel circuito provinciale
- Aggiunta Zona, oltre alla provincia, per visualizzare i vari circuiti della prov
2023-12-06 00:41:50 +01:00
Surya Paolo
6edba03eff Versione 1.0.21 - RIS ITALIA 2023-12-02 15:23:35 +01:00
136 changed files with 6023 additions and 1180 deletions

BIN
.DS_Store vendored

Binary file not shown.

38
.env.dev.pcb Normal file
View File

@@ -0,0 +1,38 @@
DATABASE=test_PiuCheBuono
UDB=paofreeplanet
PDB=mypassword@1A
SEND_EMAIL=0
SEND_EMAIL_ORDERS=1
PORT=3000
appTelegram_TEST=["1","13"]
appTelegram=["1","13"]
DOMAIN=mongodb://localhost:27017/
AUTH_MONGODB=true
MONGODB_USER=admin
MONGODB_PWD=mypwadmin@1A
ENABLE_PUSHNOTIFICATION=1
URLBASE_APP1=https://localhost
PORT_APP1=8080
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
HTTPS_LOCALHOST=true
DEBUG=0
DEBUG=0
TESTING_ON=1
LOCALE=1
DELAY_SENDEMAIL=2000
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
PATH_CERT_KEY=localhost.key
PATH_SERVER_CRT=localhost.crt
PATH_SSL_ROOT_PEM=root.pem
PATH_SSL_CHAIN_PEM=chain.pem
GCM_API_KEY=""
PROD=0
PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=Askb38v23jjDFaoskBOWj92axXCQ
FTPSERVER_HOST=139.162.166.31
FTPSERVER_PORT=21
FTPSERVER_USER=ftpusrsrv_
FTPSERVER_PWD=ftpmypwd@1A_
AUTH_NEW_SITES=123123123

38
.env.dev.riso Normal file
View File

@@ -0,0 +1,38 @@
DATABASE=test_FreePlanet
UDB=paofreeplanet
PDB=mypassword@1A
SEND_EMAIL=0
SEND_EMAIL_ORDERS=1
PORT=3000
appTelegram_TEST=["1","13"]
appTelegram=["1","13"]
DOMAIN=mongodb://localhost:27017/
AUTH_MONGODB=true
MONGODB_USER=admin
MONGODB_PWD=mypwadmin@1A
ENABLE_PUSHNOTIFICATION=1
URLBASE_APP1=https://localhost
PORT_APP1=8080
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
HTTPS_LOCALHOST=true
DEBUG=0
DEBUG=0
TESTING_ON=1
LOCALE=1
DELAY_SENDEMAIL=2000
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
PATH_CERT_KEY=localhost.key
PATH_SERVER_CRT=localhost.crt
PATH_SSL_ROOT_PEM=root.pem
PATH_SSL_CHAIN_PEM=chain.pem
GCM_API_KEY=""
PROD=0
PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=Askb38v23jjDFaoskBOWj92axXCQ
FTPSERVER_HOST=139.162.166.31
FTPSERVER_PORT=21
FTPSERVER_USER=ftpusrsrv_
FTPSERVER_PWD=ftpmypwd@1A_
AUTH_NEW_SITES=123123123

38
.env.development Normal file
View File

@@ -0,0 +1,38 @@
DATABASE=test_FreePlanet
UDB=paofreeplanet
PDB=mypassword@1A
SEND_EMAIL=0
SEND_EMAIL_ORDERS=1
PORT=3000
appTelegram_TEST=["1","13"]
appTelegram=["1","13"]
DOMAIN=mongodb://localhost:27017/
AUTH_MONGODB=true
MONGODB_USER=admin
MONGODB_PWD=mypwadmin@1A
ENABLE_PUSHNOTIFICATION=1
URLBASE_APP1=https://localhost
PORT_APP1=8080
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
HTTPS_LOCALHOST=true
DEBUG=0
DEBUG=0
TESTING_ON=1
LOCALE=1
DELAY_SENDEMAIL=2000
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
PATH_CERT_KEY=localhost.key
PATH_SERVER_CRT=localhost.crt
PATH_SSL_ROOT_PEM=root.pem
PATH_SSL_CHAIN_PEM=chain.pem
GCM_API_KEY=""
PROD=0
PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=Askb38v23jjDFaoskBOWj92axXCQ
FTPSERVER_HOST=139.162.166.31
FTPSERVER_PORT=21
FTPSERVER_USER=ftpusrsrv_
FTPSERVER_PWD=ftpmypwd@1A_
AUTH_NEW_SITES=123123123

32
.env.prod.pcb Normal file
View File

@@ -0,0 +1,32 @@
DATABASE=PiuCheBuono
UDB=paofreeplanet
PDB=suerteFreePlanet@1A
SEND_EMAIL=1
SEND_EMAIL_ORDERS=1
PORT=3000
appTelegram_TEST=["17"]
appTelegram=["17"]
ENABLE_PUSHNOTIFICATION=1
DIRECTORY_SERVER=freeplanet_serverside
SERVERDIR_WEBSITE=www.freeplanet_server
PORT_APP1="0"
DOMAIN=mongodb://localhost:32001/
AUTH_MONGODB=1
MONGODB_USER=admin
MONGODB_PWD=mypwadminREAL@1A
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
DEBUG=0
LOCALE=0
DELAY_SENDEMAIL=1000
VAPI_KEY_SUBJECT="mailto:surya@riso.app"
PUBLIC_VAPI_KEY="BJgo8XR_upbnbMLWgCAUELo6DK7dRXffYAnFOxbaMMz5favBgcQBKT-eISqouO-jRad4Sw8l5nd2wCF6KorGiTc"
PRIVATE_VAPI_KEY="LVpFDJuKscdHuQr5pe20dFuYuWX1-ZRb6x72PP-Pp4I"
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
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNVZZ

32
.env.test.pcb Normal file
View File

@@ -0,0 +1,32 @@
DATABASE=test_PiuCheBuono
UDB=paofreeplanet
PDB=suerteFreePlanet@1A
SEND_EMAIL=1
SEND_EMAIL_ORDERS=1
PORT=3001
appTelegram_TEST=["17"]
appTelegram=["17"]
ENABLE_PUSHNOTIFICATION=1
DIRECTORY_SERVER=freeplanet_serverside
SERVERDIR_WEBSITE=test.freeplanet_server
PORT_APP1="0"
DOMAIN=mongodb://localhost:32002/
AUTH_MONGODB=1
MONGODB_USER=admin
MONGODB_PWD=mypwadmin@1A
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
DEBUG=0
LOCALE=0
DELAY_SENDEMAIL=1000
VAPI_KEY_SUBJECT="mailto:surya@riso.app"
PUBLIC_VAPI_KEY="BJgo8XR_upbnbMLWgCAUELo6DK7dRXffYAnFOxbaMMz5favBgcQBKT-eISqouO-jRad4Sw8l5nd2wCF6KorGiTc"
PRIVATE_VAPI_KEY="LVpFDJuKscdHuQr5pe20dFuYuWX1-ZRb6x72PP-Pp4I"
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
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV

View File

@@ -8,7 +8,10 @@ DIRECTORY_SERVER=freeplanet_serverside
SERVERDIR_WEBSITE=test.freeplanet_server
PORT_APP1="0"
DOMAIN=mongodb://localhost:27018/
SIGNCODE=abc123
AUTH_MONGODB=1
MONGODB_USER=admin
MONGODB_PWD=mypwadmin@1A
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
DEBUG=0
LOCALE=0
DELAY_SENDEMAIL=1000
@@ -23,3 +26,4 @@ PATH_SSL_CHAIN_PEM=chain.pem
PROD=0
PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=iUUb38v23jjDFaosWj92axkBOXCQ
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV

1
.gitignore vendored
View File

@@ -1,6 +1,5 @@
node_modules/
.env.test
.env.development
.env.production
.env.production.bak
ESEMPI/

25
.vscode/launch.json vendored
View File

@@ -11,7 +11,9 @@
"runtimeArgs": [
"--inspect=9229" // Use "--inspect=0.0.0.0:9229" for remote debugging
],
"args": ["${workspaceFolder}/src/server/server.js"], // Replace with your entry file
"args": [
"${workspaceFolder}/src/server/server.js"
], // Replace with your entry file
"cwd": "${workspaceFolder}",
"autoAttachChildProcesses": true,
"console": "integratedTerminal",
@@ -32,7 +34,9 @@
"runtimeArgs": [
"--trace-warnings" // Use "--inspect=0.0.0.0:9229" for remote debugging
],
"args": ["${workspaceFolder}/src/server/server.js"], // Replace with your entry file
"args": [
"${workspaceFolder}/src/server/server.js"
], // Replace with your entry file
"cwd": "${workspaceFolder}",
"autoAttachChildProcesses": true,
"console": "integratedTerminal",
@@ -42,23 +46,6 @@
"NODE_ENV": "development",
"TESTING_ON": "1"
},
},
{
"name": "Server Debug",
"request": "launch",
"runtimeArgs": [
"run-script",
"start"
],
"runtimeExecutable": "npm",
"skipFiles": [
"<node_internals>/**"
],
"env": {
"NODE_ENV":"development",
"TESTING_ON":"1"
},
"type": "node"
},
{
"name": "ServerSide",

View File

@@ -1,3 +1,7 @@
{
"search.useIgnoreFiles": false
"search.useIgnoreFiles": false,
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/node_modules/**": true
},
}

18
deploynode_on_prod_pcb.sh Executable file
View File

@@ -0,0 +1,18 @@
#!/bin/bash
source ./.env.prod.pcb
echo "Sincronizzazione in corso PCB PRODUZIONE ... /var/www/$SERVERDIR_WEBSITE/"
echo ""
rsync -avz -e 'ssh -p 8822' css pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 8822' docs pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 8822' emails pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 8822' images pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 8822' plugins pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 8822' sass pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 8822' src pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/
rsync -avz -e 'ssh -p 8822' .env.prod.pcb pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/.env.production
rsync -avz -e 'ssh -p 8822' package.json pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/package.json
echo "Sincronizzazione TERMINATA! - SERVER PCB!"

19
deploynode_on_test_pcb.sh Executable file
View File

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

0
docs/prova.txt Normal file
View File

View File

@@ -4,7 +4,10 @@ module.exports = {
name: "FreePlanetServerSide",
script: "./src/server/server.js",
ignore_watch : ["node_modules"],
interpreter: "/root/.nvm/versions/node/v16.19.0/bin/node",
watch: false,
//autorestart: true,
instances: 1,
env: {
"PORT": 3000,
"NODE_ENV": "development",
@@ -17,9 +20,9 @@ module.exports = {
"PORT": 3000,
"NODE_ENV": "production",
},
log_file: "combined.outerr.log",
error_file: "err.log",
out_file: "out.log",
log_file: "logs/combined.outerr.log",
error_file: "logs/err.log",
out_file: "logs/out.log",
merge_logs: true,
log_date_format: "YYYY-MM-DD HH:mm:ss.SSSS Z"
}

View File

@@ -19,17 +19,40 @@ html
}
body(yahoofix, style="background: #ffffff")
- var baseimg = baseurl + '/statics/'
- var baseimg = baseurl + '/'
span(id='body_style', style='display:block')
table(cellpadding="10", cellspacing="0", width="600", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
if (orders.items && orders.items.length > 0)
- var mystorehouse = orders.items[0].order.storehouse
else
- var mystorehouse = null
tr
td(class="emailContainer", valign="top")
- var mioheader = mystorehouse.email_html_header
if (mioheader)
p!= mioheader
- var mioname = name
if (!mioname)
- var mioname = user.username
p Ciao #{mioname},
if (orders.items[0].order.quantitypreordered > 0)
- var miomakeorder = mystorehouse.email_html_GAS_makeorder
else
- var miomakeorder = mystorehouse.email_html_makeorder
if (miomakeorder)
p!= miomakeorder
else
p Ti arriverà una email quando i prodotti saranno disponibili per poterli venire a ritirare.
p Il pagamento, se non diversamente comunicato, potrai farlo direttamente in sede.
p Ciao #{username},
p Ti confermiamo che hai appena inviato un'ordine di prenotazione dei seguenti prodotti:
tr
td(class="whitespace", height="10")
@@ -39,12 +62,19 @@ html
- var note = orders.note
- var index = 0
each product in orders.items
- var descr = product.order.product.name
- var img = product.order.product.img
- var price = product.order.price
- var after_price = product.order.after_price
- var qty = product.order.quantity
each rec in orders.items
- var descr = rec.order.product.productInfo.name
- var img = rec.order.product.productInfo.img
- var price = rec.order.price
- var after_price = rec.order.after_price
- var TotalPriceProduct = rec.order.TotalPriceProduct
if (rec.order.gasordine)
- var gasordine = rec.order.gasordine.name
else
- var gasordine = ''
- var qty = rec.order.quantity
- var qtypreordered = rec.order.quantitypreordered
- index = index + 1
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
@@ -60,24 +90,40 @@ html
td(class="column", valign="top")
table(cellpadding="0", cellspacing="0", summary="", border="0")
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Gas Ordine: #{gasordine}
p &nbsp;
tr
td(class="sectionContentTitle boldhigh", valign="top")
p #{descr}
tr
td(class="sectionContent", valign="top")
p Prezzo: #{price} € #{after_price}
tr
if (qty > 0)
td(class="sectionContent", valign="top")
p Quantità: #{qty}
if (qtypreordered > 0)
td(class="sectionContent", valign="top")
p Quantità Prenotata: #{qtypreordered}
tr
td(class="sectionContent", valign="top")
p Totale: #{TotalPriceProduct} €
if (note)
p Note Aggiuntive: #{note}
p.sectionContentTitle.boldhigh.sectionTotal Totale Ordine: #{totalPrice} €
tr
td(class="whitespace", height="10")
p Ti arriverà una email quando i prodotti saranno disponibili per poterli venire a ritirare.
p Il pagamento potrai farlo direttamente in sede.
tr
td
- var miofooter = mystorehouse.email_html_footer
if (miofooter)
p!= miofooter
else
p Grazie Mille
table.footer(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")

View File

@@ -28,7 +28,12 @@ html
tr
td(class="emailContainer", valign="top")
p Ciao #{name},
- var mioname = name
if (!mioname)
- var mioname = user.username
p Ciao #{mioname},
p L'ordine è stato Cancellato.
p Se è stato un errore, procedi a ripetere l'Ordine, ripartendo dalla lista prodotti.
p Grazie Mille

View File

@@ -1,80 +0,0 @@
doctype html
html
head
title Ordine Completato
//- import css/scss stylesheets
//- these file names will be replace by gulp with proper css file paths
link(rel="stylesheet", href="../sass/basic.scss")
link(rel="stylesheet", href="../sass/one/styles.scss")
//- embdedded css allowed, but not sass
style.
.red {
background-color: #E84C50;
}
.full-width {
width: 100%;
}
body(yahoofix, style="background: #ffffff")
- var baseimg = baseurl + '/statics/'
span(id='body_style', style='display:block')
table(cellpadding="10", cellspacing="0", width="600", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
tr
td(class="emailContainer", valign="top")
p Ciao #{name},
p L'ordine n. #{ordernumber} è stato Completato correttamente !
p Grazie Mille per aver contribuito a far crescere la Comunità
table.footer(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
tr
td.firma
p!= dataemail.firma
tr
td.disclaimer
p!= dataemail.disclaimer_out
tr
td.bottom
p!= dataemail.disc_bottom_out
tr
td(class="whitespace", height="10")
p &nbsp;
style(type="text/css").
html, body {
padding: 0;
margin: 0;
}
p {
font-size: 1rem;
}
.divbtn {
display: flex;
align-items: center;
justify-content: center;
}
.btn-lg {
padding: 5px;
margin: 5px;
font-size: 26px;
cursor: pointer;
color: white;
background: #027be3 !important;
border-radius: 28px;
}

View File

@@ -1 +0,0 @@
=`Ordine n. ${ordernumber} Completato`

View File

@@ -0,0 +1,168 @@
doctype html
html
head
title Ordine n. #{ordernumber} Consegnato
//- import css/scss stylesheets
//- these file names will be replace by gulp with proper css file paths
link(rel="stylesheet", href="../sass/basic.scss")
link(rel="stylesheet", href="../sass/one/styles.scss")
//- embdedded css allowed, but not sass
style.
.red {
background-color: #E84C50;
}
.full-width {
width: 100%;
}
body(yahoofix, style="background: #ffffff")
- var baseimg = baseurl + '/';
span(id='body_style', style='display:block')
table(cellpadding="10", cellspacing="0", width="600", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
if (orders.items && orders.items.length > 0)
- var mystorehouse = orders.items[0].order.storehouse
else
- var mystorehouse = null
tr
td(class="emailContainer", valign="top")
- var mioheader = mystorehouse.email_html_header
if (mioheader)
p!= mioheader
else
p Ciao #{name},
p L'ordine n. #{ordernumber} è stato Consegnato correttamente !
if (orders.items[0].order.quantitypreordered > 0)
- var miomakeorder = mystorehouse.email_html_GAS_order_consegnato
else
- var miomakeorder = mystorehouse.email_html_order_consegnato
if (miomakeorder)
p!= miomakeorder
- var totalPrice = orders.totalPrice
- var note = orders.note
- var index = 0
each rec in orders.items
- var descr = rec.order.product.productInfo.name
- var img = rec.order.product.productInfo.img
- var price = rec.order.product.price
- var after_price = rec.order.product.after_price
if (rec.order.gasordine)
- var gasordine = rec.order.gasordine.name
else
- var gasordine = ''
- var qty = rec.order.product.quantity
- var qtypreordered = rec.order.quantitypreordered
- var TotalPriceProduct = rec.order.TotalPriceProduct
- index = index + 1
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
tr
td(class="column", valign="center" width="40")
p.boldhigh #{index}.
td(class="column sectionArticleImage", valign="top" width="150")
table(cellpadding="0", cellspacing="0", summary="", border="0")
tr
td
img(src=baseimg + img, alt="", width="150" height="150")
td(class="column", valign="top")
table(cellpadding="0", cellspacing="0", summary="", border="0")
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Gas Ordine: #{gasordine}
p &nbsp;
tr
td(class="sectionContentTitle boldhigh", valign="top")
p #{descr}
tr
td(class="sectionContent", valign="top")
p Prezzo: #{price} € #{after_price}
if (qty > 0)
tr
td(class="sectionContent", valign="top")
p Quantità: #{qty}
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Quantità Prenotata: #{qtypreordered}
tr
td(class="sectionContent", valign="top")
p Totale: #{TotalPriceProduct} €
if (note)
p Note Aggiuntive: #{note}
p.sectionContentTitle.boldhigh.sectionTotal Totale Ordine: #{totalPrice} €
tr
td(class="whitespace", height="10")
tr
td
- var miofooter = mystorehouse.email_html_footer
if (miofooter)
p!= miofooter
else
p Grazie Mille
table.footer(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
tr
td.firma
p!= dataemail.firma
tr
td.disclaimer
p!= dataemail.disclaimer_out
tr
td.bottom
p!= dataemail.disc_bottom_out
tr
td(class="whitespace", height="10")
p &nbsp;
style(type="text/css").
html, body {
padding: 0;
margin: 0;
}
p {
font-size: 1rem;
}
.divbtn {
display: flex;
align-items: center;
justify-content: center;
}
.btn-lg {
padding: 5px;
margin: 5px;
font-size: 26px;
cursor: pointer;
color: white;
background: #027be3 !important;
border-radius: 28px;
}

View File

@@ -1,7 +1,7 @@
doctype html
html
head
title Ordine Confermato
title Ordine n. #{ordernumber} Confermato
//- import css/scss stylesheets
//- these file names will be replace by gulp with proper css file paths
@@ -19,32 +19,59 @@ html
}
body(yahoofix, style="background: #ffffff")
- var baseimg = baseurl + '/statics/'
- var baseimg = baseurl + '/';
span(id='body_style', style='display:block')
table(cellpadding="10", cellspacing="0", width="600", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
if (orders.items && orders.items.length > 0)
- var mystorehouse = orders.items[0].order.storehouse
else
- var mystorehouse = null
tr
td(class="emailContainer", valign="top")
p Ciao #{name},
p L'ordine dei seguenti prodotti è stato Confermato:
- var mioheader = mystorehouse.email_html_header
if (mioheader)
p!= mioheader
- var mioname = name
if (!mioname)
- var mioname = user.username
p Ciao #{mioname},
if (orders.items[0].order.quantitypreordered > 0)
- var miordconfirmed = mystorehouse.email_html_GAS_order_confirmed
else
- var miordconfirmed = mystorehouse.email_html_order_confirmed
if (miordconfirmed)
p!= miordconfirmed
else
p Puoi pertanto venire a ritirarli direttamente in sede, negli orari che ti sono stati indicati.
tr
td(class="whitespace", height="10")
p &nbsp;
- var totalPrice = orders.totalPrice
- var note = orders.note
- var index = 0
each product in orders.items
- var descr = product.order.product.name
- var img = product.order.product.img
- var price = product.order.price
- var after_price = product.order.after_price
- var qty = product.order.quantity
each rec in orders.items
- var descr = rec.order.product.productInfo.name
- var img = rec.order.product.productInfo.img
- var price = rec.order.product.price
- var after_price = rec.order.product.after_price
if (rec.order.gasordine)
- var gasordine = rec.order.gasordine.name
else
- var gasordine = ''
- var qty = rec.order.product.quantity
- var qtypreordered = rec.order.quantitypreordered
- var TotalPriceProduct = rec.order.TotalPriceProduct
- index = index + 1
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
@@ -60,23 +87,42 @@ html
td(class="column", valign="top")
table(cellpadding="0", cellspacing="0", summary="", border="0")
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Gas Ordine: #{gasordine}
p &nbsp;
tr
td(class="sectionContentTitle boldhigh", valign="top")
p #{descr}
tr
td(class="sectionContent", valign="top")
p Prezzo: #{price} € #{after_price}
if (qty > 0)
tr
td(class="sectionContent", valign="top")
p Quantità: #{qty}
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Quantità Prenotata: #{qtypreordered}
tr
td(class="sectionContent", valign="top")
p Totale: #{TotalPriceProduct} €
if (note)
p Note Aggiuntive: #{note}
p.sectionContentTitle.boldhigh.sectionTotal Totale Ordine: #{totalPrice} €
tr
td(class="whitespace", height="10")
p Puoi pertanto venire a ritirarli direttamente in sede.
tr
td
- var miofooter = mystorehouse.email_html_footer
if (miofooter)
p!= miofooter
else
p Grazie Mille
table.footer(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")

View File

@@ -0,0 +1,173 @@
doctype html
html
head
title Ordine n. #{ordernumber} Consegnato
//- import css/scss stylesheets
//- these file names will be replace by gulp with proper css file paths
link(rel="stylesheet", href="../sass/basic.scss")
link(rel="stylesheet", href="../sass/one/styles.scss")
//- embdedded css allowed, but not sass
style.
.red {
background-color: #E84C50;
}
.full-width {
width: 100%;
}
body(yahoofix, style="background: #ffffff")
- var baseimg = baseurl + '/';
span(id='body_style', style='display:block')
table(cellpadding="10", cellspacing="0", width="600", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
if (orders.items && orders.items.length > 0)
- var mystorehouse = orders.items[0].order.storehouse
else
- var mystorehouse = null
tr
td(class="emailContainer", valign="top")
- var mioheader = mystorehouse.email_html_header
if (mioheader)
p!= mioheader
- var mioname = name
if (!mioname)
- var mioname = user.username
p Ciao #{mioname},
p L'ordine n. #{ordernumber} è stato Consegnato correttamente 📦 !
p Grazie per averci scelto 🙏🏻 e alla prossima !
p &nbsp;
if (orders.items[0].order.quantitypreordered > 0)
- var miomakeorder = mystorehouse.email_html_GAS_order_consegnato
else
- var miomakeorder = mystorehouse.email_html_order_consegnato
if (miomakeorder)
p!= miomakeorder
- var totalPrice = orders.totalPrice
- var note = orders.note
- var index = 0
each rec in orders.items
- var descr = rec.order.product.productInfo.name
- var img = rec.order.product.productInfo.img
- var price = rec.order.product.price
- var after_price = rec.order.product.after_price
if (rec.order.gasordine)
- var gasordine = rec.order.gasordine.name
else
- var gasordine = ''
- var qty = rec.order.product.quantity
- var qtypreordered = rec.order.quantitypreordered
- var TotalPriceProduct = rec.order.TotalPriceProduct
- index = index + 1
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
tr
td(class="column", valign="center" width="40")
p.boldhigh #{index}.
td(class="column sectionArticleImage", valign="top" width="150")
table(cellpadding="0", cellspacing="0", summary="", border="0")
tr
td
img(src=baseimg + img, alt="", width="150" height="150")
td(class="column", valign="top")
table(cellpadding="0", cellspacing="0", summary="", border="0")
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Gas Ordine: #{gasordine}
p &nbsp;
tr
td(class="sectionContentTitle boldhigh", valign="top")
p #{descr}
tr
td(class="sectionContent", valign="top")
p Prezzo: #{price} € #{after_price}
if (qty > 0)
tr
td(class="sectionContent", valign="top")
p Quantità: #{qty}
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Quantità Prenotata: #{qtypreordered}
tr
td(class="sectionContent", valign="top")
p Totale: #{TotalPriceProduct} €
if (note)
p Note Aggiuntive: #{note}
p.sectionContentTitle.boldhigh.sectionTotal Totale Ordine: #{totalPrice} €
tr
td(class="whitespace", height="10")
tr
td
- var miofooter = mystorehouse.email_html_footer
if (miofooter)
p!= miofooter
else
p Grazie Mille
table.footer(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
tr
td(class="whitespace", height="10")
p &nbsp;
tr
td.firma
p!= dataemail.firma
tr
td.disclaimer
p!= dataemail.disclaimer_out
tr
td.bottom
p!= dataemail.disc_bottom_out
tr
td(class="whitespace", height="10")
p &nbsp;
style(type="text/css").
html, body {
padding: 0;
margin: 0;
}
p {
font-size: 1rem;
}
.divbtn {
display: flex;
align-items: center;
justify-content: center;
}
.btn-lg {
padding: 5px;
margin: 5px;
font-size: 26px;
cursor: pointer;
color: white;
background: #027be3 !important;
border-radius: 28px;
}

View File

@@ -0,0 +1 @@
=`Ordine n. ${ordernumber} Consegnato`

View File

@@ -11,15 +11,16 @@
-}
- var urlcal = baseurl + '/calendario-eventi/'
- var imginstagram = baseurl + '/statics/images/images/footer-instagram-icon.png'
- var imgtwitter = baseurl + '/statics/images/images/footer-twitter-icon.png'
- var imgyoutube = baseurl + '/statics/images/images/footer-youtube-icon.png'
- var imgfb = baseurl + '/statics/images/images/footer-facebook-icon.png'
- var baseimg = baseurl + '/statics/'
- var imginstagram = baseurl + '/images/images/footer-instagram-icon.png'
- var imgtwitter = baseurl + '/images/images/footer-twitter-icon.png'
- var imgyoutube = baseurl + '/images/images/footer-youtube-icon.png'
- var imgfb = baseurl + '/images/images/footer-facebook-icon.png'
- var baseimg = baseurl + '/'
doctype html
html
- if (dataemail.title)
head
title Calendario Eventi
title dataemail.subject
//- import css/scss stylesheets
//- these file names will be replace by gulp with proper css file paths
@@ -37,20 +38,15 @@ html
}
body(yahoofix)
span(id='body_style', style='display:block')
table(class="preheader", cellpadding="0", cellspacing="0", width="100%")
tr
td.webversion
p non vedi le immagini?&nbsp;
a(href=urlcal) Apri il Calendario
table(class="topHeader", cellpadding="0", cellspacing="0", width="100%")
- if (dataemail.height_logo)
tr
td
table(cellpadding="0", cellspacing="0", align="center", summary="")
tr
td.logoContainer
a(href=baseurl, title='logo')
img.logo(src=baseurl+"/statics/images/logo.png", height=dataemail.height_logo)
img.logo(src=baseurl+"/images/logo.png", height=dataemail.height_logo)
tr
td.testomail
@@ -201,10 +197,6 @@ html
td(class="whitespace", height="20")
p &nbsp;
tr
td(class="whitespace", height="20")
p &nbsp;
// Social Media
table.socialMedia(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
tr

View File

@@ -93,3 +93,44 @@ 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
Dom 17/12 ORE 15:38: USER [admin]: prova
Dom 17/12 ORE 16:18: USER [admin]: vai al sito
Dom 17/12 ORE 16:19: USER [admin]: vai al sito
Dom 17/12 ORE 16:19: USER [admin]: il mio profilo
Dom 17/12 ORE 16:19: USER [admin]: prova
Dom 17/12 ORE 16:19: USER [admin]: link da condividere
Sab 30/12 ORE 20:06: USER [admin]: gruppo di acquisto per le arance:
produttore:
🍊sicilia frutta express (catania)
la piccola azienda a conduzione familiare di giovanni si trova in provincia di catania (sicilia), i frutti vengono prodotti rispettando i principi della biodinamica infatti non viene utilizzato nulla di chimico (niente irrorazioni) e la concimazione avviene tramite concimi naturali (letame).
⚠️ offerta sconto valida solo fino al 3 gennaio 2024, raggiungendo 100 kg totali di ordini di arance:
i prezzi sono compresi di spese di spedizione e di gestione.
🍊 arance tarocco spremuta: 1,20 € / kg
🥑 avocado: 7,80 € / kg
🍋 limoni: 2,40 € / kg
👉🏻 entra sul gruppo telegram piu che buono
per le prenotazioni potete registratevi sul nuovo sito:
👉🏻 piu che buono - gas e bottega (piuchebuono.app)
come funziona:
- registratevi su piuchebuono.app, verificate la email.
- accedete e poi cliccate su "gruppo di acquisto".
- cliccate sul carrello verde 🛒 per aggiungere i kg che desiderate.
- per finire: cliccare su "procedi all'ordine" e confermate.
Dom 21/01 ORE 19:00: USER [paoloar77]: 👉🏻 indietro

View File

@@ -25,3 +25,7 @@ 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)!
Sab 02/12 ORE 14:15: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
✅ SuryaArena è stato Abilitato correttamente (da paoloar77)!
Dom 21/01 ORE 19:00: 🤖: Da Sùrya (Paolo) undefined (paoloar77):
👉🏻 indietro

View File

@@ -117,3 +117,15 @@ Mer 29/11 ORE 17:14: [<b>Circuito RIS Italia</b>]: Inviate Monete da SuryaArena
Saldi:
SuryaArena: -13 RIS]
paoloar77: 13 RIS]
Gio 04/01 ORE 14:00: [<b>Euro</b>]: Inviate Monete da PaoloRiso a piuchebuono 44.4 € [causale: Pagato Ordine n.101]
Saldi:
PaoloRiso: -44.4 €]
piuchebuono: 44.4 €]
Dom 07/01 ORE 16:22: [<b>Euro</b>]: Inviate Monete da PaoloRiso a 44.4 € [causale: Pagato Ordine n.101]
Saldi:
PaoloRiso: -44.4 €]
: 44.4 €]
Dom 07/01 ORE 16:24: [<b>Euro</b>]: Inviate Monete da PaoloRiso a 44.4 € [causale: Pagato Ordine n.101]
Saldi:
PaoloRiso: -88.8 €]
: 88.8 €]

View File

@@ -14,7 +14,7 @@
"test-watch": "nodemon --exec 'npm test'"
},
"engines": {
"node": "^16.19.0"
"node": "^18.19.0"
},
"author": "Paolo Arena",
"license": "MIT",

View File

@@ -2,7 +2,7 @@
body, #body_style {
margin: 0;
padding: 0;
background: #E9F2F9;
background: #E9F2F9 !important;
color: #5b656e;
}

View File

@@ -10,6 +10,7 @@ var file = `.env.${node_env}`;
// GLOBALI (Uguali per TUTTI)
process.env.LINKVERIF_REG = '/vreg';
process.env.LINK_REQUEST_NEWPASSWORD = '/requestnewpwd';
process.env.ADD_NEW_SITE = '/addNewSite';
process.env.LINK_UPDATE_PASSWORD = '/updatepassword';
process.env.LINK_UPDATE_PWD = '/updatepwd';
process.env.LINK_CHECK_UPDATES = '/checkupdates';

View File

@@ -11,7 +11,7 @@ mongoose.plugin(schema => {
mongoose.set('debug', false);
const options = {
let options = {
// user: process.env.UDB,
// pass: process.env.PDB,
// useMongoClient: true,
@@ -38,21 +38,35 @@ const options = {
// keepAliveInitialDelay: 300000 // keepAliveInitialDelay is the number of milliseconds to wait before initiating keepAlive on the socket.
};
if (process.env.AUTH_MONGODB === '1') {
options.auth = {
authSource: "admin",
poolSize: 10,
user: process.env.MONGODB_USER,
password: process.env.MONGODB_PWD,
};
}
if (options.auth && options.auth.user) {
console.log('MongoDb con Authenticazione:', options.auth.user, '******');
} else {
console.log('### MongoDb SENZA Authenticazione !!! ');
}
const db = mongoose.connection;
// mongoose.connect(process.env.MONGODB_URI + '?authSource=admin', { options })
// 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);
connectionUrl = process.env.MONGODB_URI;
console.log('Connessione a ' + connectionUrl + ' in corso...');
mongoose.connect(connectionUrl, options);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log('*** CONNESSIONE EFFETTUATA ! ' + process.env.MONGODB_URI + ' db: ' + process.env.DATABASE)
console.log('*** CONNESSIONE EFFETTUATA ! ' + connectionUrl + ' db: ' + process.env.DATABASE)
});

View File

@@ -18,9 +18,9 @@
"<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 !",
"✅ You have accepted %s' Friendship request!": "✅ Hai accettato la richiesta di Amicizia 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) !",
"HANDSHAKE_SET": "<strong>%s</strong> ha comunicato che ti conosce personalmente e ha Fiducia in te (Stretta di mano).",
"HANDSHAKE_CONFIRMED": "🤝 Hai contraccambiato la stretta di mano di <strong>%s</strong>!",
"HANDSHAKE_ACCEPTED": "🤝 <strong>%s</strong> ha contraccambiato la tua stretta di mano !",
"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_REMOVED": "❌ l'utente %s è stato rimosso del Gruppo %s (da parte di %s)",
@@ -43,10 +43,10 @@
"FRIEND_UNBLOCKED_TO_ME": "Sei stato riattivato da %s",
"FRIEND_UNBLOCKED": "E' stato riattivato %s da %s.",
"FRIEND_UNBLOCKED_YOU": "Hai riattivato %s.",
"CIRCUIT_ACCEPT_NEWENTRY": "❇️👥 🧍‍♂️ Abilita fido a %s nel '%s':",
"CIRCUIT_ACCEPT_NEWENTRY_BYGROUP": "❇️👥 🧍‍♂️ Abilita fido nel Circuito al gruppo %s:",
"CIRCUIT_ACCEPT_NEWENTRY": "❇️👥 🧍‍♂️ Abilita Fiducia a %s nel '%s':",
"CIRCUIT_ACCEPT_NEWENTRY_BYGROUP": "❇️👥 🧍‍♂️ Abilita Fiducia 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_REQUEST_TO_ENTER": "%s è entrato nel %s (con %s iscritti) ed è in attesa di essere abilitato alla Fiducia\n🙎🏻 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)",
@@ -58,12 +58,12 @@
"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 %s da parte di %s",
"CIRCUIT_ELIMINATO": "Il %s è stato eliminato da parte di %s",
"FIDO_IMPOSTATO_ADMINS_CIRCUIT": "✅ l'utente %s è stato abilitato al Fido (%s RIS) sul '%s' (da parte di %s)",
"FIDO_IMPOSTATO_ADMINS_CIRCUIT_MYGROUP": "✅ il Conto di Gruppo %s è stato abilitato al Fido fino a -%s sul '%s' (da parte di %s)",
"FIDO_IMPOSTATO_ADMINS_CIRCUIT": "✅ l'utente %s è stato abilitato alla Fiducia (%s RIS) sul '%s' (da parte di %s)",
"FIDO_IMPOSTATO_ADMINS_CIRCUIT_MYGROUP": "✅ il Conto di Gruppo %s è stato abilitato alla Fiducia fino a -%s sul '%s' (da parte di %s)",
"ACCETTATO_NOTIFICA_ADMINS_CIRCUIT": "✅ l'utente %s è stato accettato a far parte del '%s' (da parte di %s)",
"ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP": "✅ il Conto di Gruppo %s è stato accettato a far parte del '%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",
"FIDO_IMPOSTATO": "✅ Ti è stata attivata la possibilità di utilizzare il fido (Fiducia Concessa) fino a %s RIS da %s sul '%s'.",
"FIDO_IMPOSTATO": "✅ Ti è stata attivata la possibilità di utilizzare la Fiducia Concessa fino a %s RIS da %s sul '%s'.",
"CIRCUIT_ACCEPTED_YOU": "✅ Hai accettato %s a far parte del '%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": "❌ l'utente %s è stato rimosso del %s (da parte di %s)",
@@ -97,7 +97,7 @@
"STATUS_SENT": "Inviato",
"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",
"FIDOCONCESSO_VARIATO": "[%s] l'utente %s ha variato la Fiducia Concessa 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",

View File

@@ -30,6 +30,9 @@ const AccountSchema = new Schema({
idapp: {
type: String,
},
numtransactions: {
type: Number,
},
username: {
type: String,
},
@@ -232,6 +235,11 @@ AccountSchema.statics.addtoSaldo = async function (myaccount, amount, mitt) {
myaccount.totTransato = 0;
}
myaccount.totTransato += Math.abs(amount);
if (!myaccount.numtransactions)
myaccount.numtransactions = 0;
myaccount.numtransactions++;
myaccount.date_updated = new Date();
myaccountupdate.saldo = myaccount.saldo;
@@ -272,8 +280,8 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp,
const { Circuit } = require('../models/circuit');
if (username === undefined)
return false;
// if (username === undefined)
// return false;
let myquery = {
idapp,
@@ -308,6 +316,7 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp,
fidoConcesso: 0,
qta_maxConcessa: 0,
totTransato: 0,
numtransactions: 0,
totTransato_pend: 0,
});
@@ -636,7 +645,7 @@ AccountSchema.statics.updateQtaMax = async function (idapp, username, groupname,
else
risult = await Account.updateOne({ idapp, username, circuitId }, { $set: paramstoupdate });
return risult;
return risult && risult.nModified > 0;
};
AccountSchema.statics.getAccountsCircuitiNazionali = async function (idapp) {
@@ -725,9 +734,8 @@ AccountSchema.statics.removeAdminOfAccount = async function (idapp, username, ci
// Rimuovi l'account
AccountSchema.statics.removeAccount = async function (accountId) {
const { Circuit } = require('../models/circuit');
return await Circuit.deleteOne({ _id: accountId});
return await Account.deleteOne({ _id: accountId});
};
AccountSchema.statics.updateSaldoAndTransato_AllAccounts = async function (idapp) {
@@ -742,4 +750,8 @@ AccountSchema.statics.updateSaldoAndTransato_AllAccounts = async function (idapp
const Account = mongoose.model('Account', AccountSchema);
Account.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Account };

View File

@@ -64,4 +64,8 @@ AdTypeSchema.statics.executeQueryTable = function(idapp, params) {
const AdType = mongoose.model('AdType', AdTypeSchema);
AdType.createIndexes((err) => {
if (err) throw err;
});
module.exports = {AdType};

View File

@@ -64,4 +64,8 @@ AdTypeGoodSchema.statics.executeQueryTable = function(idapp, params) {
const AdTypeGood = mongoose.model('AdTypeGood', AdTypeGoodSchema);
AdTypeGood.createIndexes((err) => {
if (err) throw err;
});
module.exports = {AdTypeGood};

View File

@@ -122,4 +122,8 @@ bookingSchema.statics.findAllDistinctByBooking = function (idapp) {
const Booking = mongoose.model('Booking', bookingSchema);
Booking.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Booking };

View File

@@ -66,6 +66,135 @@ BotSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
};
BotSchema.statics.generateBotMenuRecords = async function (idapp) {
try {
let arrrec = [
{
"page": 1,
"index": 1,
"riga": 1,
"active": true,
"label": "Vai al Sito",
"type": 3,
"value": "{host}",
"visibility": 0,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 1,
"riga": 2,
"active": true,
"label": "Il mio Profilo",
"type": 3,
"value": "{host}/my/{username}",
"visibility": 1,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 1,
"riga": 3,
"active": true,
"label": "Link da Condividere",
"type": 2,
"value": "{host}/registrati/{username}",
"visibility": 1,
idapp,
"lang": "it",
"main": true,
},
{
"page": 1,
"index": 2,
"riga": 1,
"active": true,
"label": "🔮 Help",
"type": 4,
"value": "",
"visibility": 0,
idapp,
"lang": "it",
"main": true,
},
{
"page": 1,
"index": 1,
"riga": 3,
"active": true,
"label": "💁‍♀️ Admin",
"type": 4,
"value": "",
"visibility": 5,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 2,
"riga": 2,
"active": true,
"label": "Imposta Foto Profilo",
"type": 4,
"value": "🖼 SetPicProfile",
"visibility": 1,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 2,
"riga": 3,
"active": true,
"label": "🛠 Strumenti",
"type": 1,
"value": "2",
"visibility": 1,
idapp,
"lang": "it",
"main": true,
},
{
"page": 2,
"index": 1,
"riga": 1,
"active": true,
"label": "🔑 Cambio Password",
"type": 4,
"value": "🔑 SetResetPwd",
"visibility": 1,
idapp,
"lang": "it",
},
{
"page": 2,
"index": 1,
"riga": 2,
"active": true,
"label": "👉🏻 Indietro",
"type": 1,
"value": "1",
"visibility": 1,
idapp,
"lang": "it",
}];
const ris = await MyBot.insertMany(arrrec);
return ris;
} catch (e) {
console.error('Err:', e);
}
}
BotSchema.statics.findAllIdApp = async function (idapp) {
const Bot = this;
@@ -76,4 +205,8 @@ BotSchema.statics.findAllIdApp = async function(idapp) {
const MyBot = mongoose.model('Bot', BotSchema);
MyBot.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MyBot };

View File

@@ -76,4 +76,8 @@ CalZoomSchema.statics.getNextZoom = async function (idapp) {
const CalZoom = mongoose.model('CalZoom', CalZoomSchema);
CalZoom.createIndexes((err) => {
if (err) throw err;
});
module.exports = { CalZoom };

View File

@@ -1,9 +1,14 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
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 Order = require('../models/order');
const CartSchema = new Schema({
idapp: {
@@ -12,6 +17,7 @@ const CartSchema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: 'User' },
totalQty: { type: Number, default: 0 },
totalPrice: { type: Number, default: 0 },
totalPriceCalc: { type: Number, default: 0 },
department: {
type: String, ref: 'Department',
},
@@ -39,6 +45,8 @@ module.exports.findAllIdApp = async function (idapp, userId) {
module.exports.getCartByUserId = async function (uid, idapp) {
try {
const Order = require('../models/order');
let query = { userId: uid, idapp };
const mycart = await Cart.findOne(query).lean();
@@ -81,6 +89,7 @@ module.exports.updateCartByUserId = function (userId, newCart, callback) {
items: newCart.items,
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc,
userId: userId,
},
},
@@ -99,6 +108,8 @@ module.exports.updateCartByCartId = async function (cartId, newCart) {
const items = newCart.items;
const totalQty = newCart.totalQty;
const totalPrice = newCart.totalPrice;
const totalPriceCalc = newCart.totalPriceCalc;
const note = newCart.note;
const modify_at = new Date();
@@ -106,8 +117,10 @@ module.exports.updateCartByCartId = async function (cartId, newCart) {
$set: {
items,
totalPrice,
totalPriceCalc,
totalQty,
modify_at,
note,
modify_at: new Date(),
},
}, { new: false }).lean().then((ris) => {
return ris;
@@ -126,3 +139,7 @@ module.exports.createCart = async function (newCart) {
return await newCart.save();
};
Cart.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -1,127 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const { ObjectID } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CashSchema = new Schema({
idapp: {
type: String,
},
creatorUserId: {
type: String,
},
idCashCategory: {
type: String
},
idSubCashCategory: {
type: String
},
type: { // CashType: TYPE_IN, TYPE_OUT
type: Number
},
date_created: {
type: Date
},
date_payment: {
type: Date
},
descr: {
type: String,
},
price: {
type: Number
},
quantity: {
type: Number
},
total: {
type: Number
},
fromWalletUserId: { // walletCommonCash or any Member
type: String,
},
toWalletUserId: { // walletCommonCash or any Member
type: String,
},
walletStatus: { // WalletFinalStatusType: None: 0, InCommonCash: 1, InMyWallet : 2
type: Number,
},
walletTemporaryToUserId: { // WalletCommonCash
type: String,
},
walletCashId: {
type: String,
},
internal: {
type: Boolean,
default: false,
},
extra: {
type: Boolean,
default: false,
},
notes: {
type: String
},
confirmed: {
type: Boolean,
default: false,
},
});
var Cash = module.exports = mongoose.model('Cash', CashSchema);
module.exports.getFieldsForSearch = function () {
return []
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Cash.find(myfind);
};
module.exports.getAllCash = function (query, sort, callback) {
Cash.find(query, null, sort, callback)
}
module.exports.getCashByUserId = function (userId, sort, callback) {
Cash.find({ userId }, null, sort, callback)
}
module.exports.getCashByID = function (id, callback) {
Cash.findById(id, callback);
}
module.exports.createCash = async function (Cash) {
const CashModel = new Cash(Cash);
return await CashModel.save(Cash)
.then((ris) => {
if (!!ris)
return ris._id;
return null;
});
}
// const Cash = mongoose.model('Cash', CashSchema);
// module.exports = { Cash };

View File

@@ -28,6 +28,10 @@ const CashCategorySchema = new Schema({
var CashCategory = module.exports = mongoose.model('CashCategory', CashCategorySchema);
CashCategory.createIndexes((err) => {
if (err) throw err;
});
module.exports.getFieldsForSearch = function () {
return []
};
@@ -66,3 +70,4 @@ module.exports.createCashCategory = async function (CashCategory) {
return null;
});
}

View File

@@ -69,3 +69,7 @@ module.exports.createCashSubCategory = async function (CashSubCategory) {
return null;
});
}
module.exports.createIndexes((err) => {
if (err) throw err;
});

61
src/server/models/catai.js Executable file
View File

@@ -0,0 +1,61 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CatAISchema = new Schema({
_id: {
type: Number,
},
name: {
type: String,
},
img: {
type: String,
},
icon: {
type: String,
},
color: {
type: String,
},
});
CatAISchema.statics.getAllCategories = function (callback) {
CatAI.find(callback)
}
CatAISchema.statics.getCatAIById = function (id, callback) {
CatAI.findById(id, callback);
}
CatAISchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
CatAISchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
CatAISchema.statics.findAllIdApp = async function (idapp) {
const myfind = {};
return await CatAI.find(myfind).sort({ name: 1 });
};
const CatAI = mongoose.model('CatAI', CatAISchema);
CatAI.createIndexes((err) => {
if (err) throw err;
});
module.exports = CatAI;

View File

@@ -50,4 +50,9 @@ CategorySchema.statics.findAllIdApp = async function (idapp) {
const Category = mongoose.model('Category', CategorySchema);
Category.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Category };

View File

@@ -80,4 +80,8 @@ CatGrpSchema.statics.executeQueryTable = function (idapp, params) {
const CatGrp = mongoose.model('CatGrp', CatGrpSchema);
CatGrp.createIndexes((err) => {
if (err) throw err;
});
module.exports = { CatGrp };

62
src/server/models/catprod.js Executable file
View File

@@ -0,0 +1,62 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CatProdSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
},
img: {
type: String,
},
icon: {
type: String,
},
color: {
type: String,
},
});
CatProdSchema.statics.getAllCategories = function (callback) {
CatProd.find(callback)
}
CatProdSchema.statics.getCatProdById = function (id, callback) {
CatProd.findById(id, callback);
}
CatProdSchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
CatProdSchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
CatProdSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await CatProd.find(myfind).sort({ name: 1 });
};
const CatProd = mongoose.model('CatProd', CatProdSchema);
CatProd.createIndexes((err) => {
if (err) throw err;
});
module.exports = CatProd;

View File

@@ -43,5 +43,9 @@ CfgServerSchema.statics.findAllIdApp = async function(idapp) {
const CfgServer = mongoose.model('CfgServer', CfgServerSchema);
CfgServer.createIndexes((err) => {
if (err) throw err;
});
module.exports = {CfgServer};

View File

@@ -84,9 +84,6 @@ const CircuitSchema = new Schema({
totCircolante: {
type: Number,
},
showAlways: {
type: Boolean,
},
totTransato: {
type: Number,
},
@@ -227,6 +224,10 @@ const CircuitSchema = new Schema({
type: Number,
default: 0,
},
ignoreLimits: {
type: Boolean,
default: false,
},
});
CircuitSchema.pre('save', async function (next) {
@@ -669,6 +670,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
const esisteDest = await Account.isExistAccountByUsernameAndCircuitId(idapp, extrarec.dest, circuittable._id, extrarec.groupdest, extrarec.contoComDest);
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);
@@ -694,6 +696,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
const circolantePrec = this.getCircolanteSingolaTransaz(accountorigTable, accountdestTable);
if (!circuittable.ignoreLimits) {
// Check if Sender has enough money
if (accountorigTable.saldo - myqty < -accountorigTable.fidoConcesso) {
ris.cansend = false;
@@ -704,11 +707,12 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
ris.cansend = false;
ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_QTAMAX', extrarec.dest);
}
}
if (!onlycheck) {
// Add a Transaction !
if (ris.cansend) {
ris.rec = await Movement.addMov(idapp, accountorigTable, accountdestTable, myqty, extrarec.causal, extrarec.notifId);
ris.rec = await Movement.addMov(idapp, accountorigTable, accountdestTable, myqty, extrarec.causal, extrarec.notifId, extrarec.idOrdersCart);
}
if (ris.cansend && ris.rec) {
@@ -1110,7 +1114,7 @@ CircuitSchema.statics.getListCircuitsByUsername = async function (idapp, usernam
if (account.groupname === '') {
mystr += '\n👉🏻 ' + account.circuit.name + '\n';
mystr += ' [Saldo: ' + account.saldo + ' RIS, ';
mystr += ' Fido: ' + account.fidoConcesso + ' RIS, ';
mystr += ' Fiducia: ' + account.fidoConcesso + ' RIS, ';
mystr += ' Transato: ' + account.totTransato + ' RIS]';
}
}
@@ -1121,7 +1125,7 @@ CircuitSchema.statics.getListCircuitsByUsername = async function (idapp, usernam
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 += ' Fiducia: ' + account.fidoConcesso + ' RIS, ';
mystr += ' Transato: ' + account.totTransato + ' RIS]';
}
}
@@ -1161,12 +1165,15 @@ CircuitSchema.statics.SetDefMinMaxCollettivi = async function (idapp, valmin, va
CircuitSchema.statics.setFido = async function (idapp, username, circuitName, groupname) {
mycircuit = await Circuit.findOne({ idapp, name: circuitName });
try {
mycircuit = await Circuit.findOne({ idapp, name: circuitName }).lean();
if (mycircuit) {
const circuitId = mycircuit._id;
let account = null;
let fido = 0;
let qtamax = 0;
let variato = false;
let variato2 = false;
if (mycircuit.showAlways) {
@@ -1178,7 +1185,7 @@ CircuitSchema.statics.setFido = async function (idapp, username, circuitName, gr
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)
account = accountsuser.find((account) => account.circuit.strProv === myuser.profile.resid_province && ((account.circuit.card === myuser.profile.resid_card) || !myuser.profile.resid_card))
if (!account && accountsuser.length > 0) {
// Se non lo trovo, prendo il primo in cui sono entrato !
account = accountsuser[0];
@@ -1194,7 +1201,7 @@ CircuitSchema.statics.setFido = async function (idapp, username, circuitName, gr
}
} else {
// Se non ho Circuiti locali, non applico il Fido !
return false;
return null;
}
} else {
@@ -1207,18 +1214,47 @@ CircuitSchema.statics.setFido = async function (idapp, username, circuitName, gr
if (account) {
if (qtamax > 0) {
await Account.updateQtaMax(idapp, username, groupname, circuitId, qtamax);
variato = 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 { qta_maxConcessa: qtamax, fidoConcesso: fido, changed: variato || (ris && ris.nModified > 0) };
}
}
}
return false;
} catch (e) {
console.error('Err:', e);
}
return null;
};
CircuitSchema.statics.addMovementByOrdersCart = async function (ordersCart, usernameDest, groupDest) {
const { User } = require('../models/user');
const idapp = ordersCart.idapp;
let extrarec = {
causal: 'Pagato Ordine n.' + ordersCart.numorder,
circuitname: 'Euro',
idOrdersCart: ordersCart._id,
qty: ordersCart.totalPrice,
dest: usernameDest,
groupdest: groupDest,
contoComDest: '',
};
const usernameOrig = await User.getUsernameById(idapp, ordersCart.userId);
return this.sendCoins(false, idapp, usernameOrig, extrarec);
};
const Circuit = mongoose.model('Circuit', CircuitSchema);
Circuit.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Circuit };

View File

@@ -201,4 +201,8 @@ CitySchema.statics.findAllIdApp = async function(idapp) {
const City = mongoose.model('City', CitySchema);
City.createIndexes((err) => {
if (err) throw err;
});
module.exports = {City};

View File

@@ -52,4 +52,8 @@ ContribtypeSchema.statics.findAllIdApp = async function (idapp) {
const Contribtype = mongoose.model('Contribtype', ContribtypeSchema);
Contribtype.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Contribtype };

View File

@@ -26,6 +26,10 @@ const departmentSchema = new Schema({
var Department = module.exports = mongoose.model('Department', departmentSchema);
module.exports.createIndexes((err) => {
if (err) throw err;
});
module.exports.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string },
{ field: 'username', type: tools.FieldType.string }

View File

@@ -106,4 +106,8 @@ DisciplineSchema.statics.DuplicateAllRecords = async function (idapporig, idappd
const Discipline = mongoose.model('Discipline', DisciplineSchema);
Discipline.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Discipline };

View File

@@ -332,6 +332,9 @@ ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) {
const ExtraList = mongoose.model('ExtraList', ExtraListSchema);
ExtraList.createIndexes((err) => {
if (err) throw err;
});
module.exports = { ExtraList };

View File

@@ -64,4 +64,8 @@ GallerySchema.statics.findAllIdApp = async function (idapp) {
const Gallery = mongoose.model('Gallery', GallerySchema);
Gallery.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Gallery };

80
src/server/models/gasordine.js Executable file
View File

@@ -0,0 +1,80 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const gasordineSchema = new Schema({
active: {
type: Boolean,
},
idapp: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
referente: {
type: String,
},
city: {
type: String,
},
img: {
type: String,
},
dataora_chiusura_ordini: {
type: Date,
},
data_arrivo_merce: {
type: Date,
},
dataora_ritiro: {
type: Date,
},
dataora_termine_pagamento: {
type: Date,
},
});
var Gasordine = module.exports = mongoose.model('Gasordine', gasordineSchema);
module.exports.getFieldsForSearch = function () {
return [
{field: 'name', type: tools.FieldType.string},
{field: 'description', type: tools.FieldType.string},
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Gasordine.find(myfind);
};
module.exports.getGasordineByID = function (id, callback) {
Gasordine.findById(id, callback);
}
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -80,4 +80,8 @@ GoodSchema.statics.executeQueryTable = function (idapp, params) {
const Good = mongoose.model('Good', GoodSchema);
Good.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Good };

View File

@@ -415,4 +415,8 @@ GraduatoriaSchema.statics.getPosizioneInGraduatoria = async function (idapp, ind
const Graduatoria = mongoose.model('Graduatoria', GraduatoriaSchema);
Graduatoria.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Graduatoria };

View File

@@ -47,3 +47,6 @@ module.exports.findAllIdApp = async function (idapp) {
return await Group.find(myfind);
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -228,3 +228,6 @@ module.exports.calculateHoursTodo = async function (idtodo) {
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -0,0 +1,59 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// A1P
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const inventariogmSchema = new Schema({
idapp: {
type: String,
},
});
var Inventariogm = module.exports = mongoose.model('Inventariogm', inventariogmSchema);
inventariogmSchema.index({ idapp: 1 });
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getInventariogmByCode = function (idapp, code) {
return Inventariogm.findAllIdApp(idapp, code);
}
module.exports.getInventariogmById = async function (id) {
const arrris = await Inventariogm.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
module.exports.findAllIdApp = async function (idapp) {
const Inventariogm = this;
const myfind = { idapp, deleted: false };
return await Inventariogm.find(myfind, (err, arrrec) => {
return arrrec;
});
};

View File

@@ -196,3 +196,7 @@ module.exports.findAllIdApp = async function(idapp) {
return arrrec;
});
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -196,3 +196,7 @@ module.exports.findAllIdApp = async function (idapp) {
return arrrec
});
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -73,4 +73,8 @@ LevelSchema.statics.executeQueryTable = function(idapp, params) {
const Level = mongoose.model('Level', LevelSchema);
Level.createIndexes((err) => {
if (err) throw err;
});
module.exports = {Level};

View File

@@ -121,4 +121,8 @@ MailingListSchema.statics.findByHash = function (idapp, hash) {
const MailingList = mongoose.model('MailingList', MailingListSchema);
MailingList.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MailingList };

View File

@@ -36,6 +36,7 @@ const MovementSchema = new Schema({
accountToId: {
type: String,
},
idOrdersCart: { type: Schema.Types.ObjectId, ref: 'OrdersCart' },
causal_table: {
type: String,
},
@@ -56,6 +57,10 @@ const MovementSchema = new Schema({
expiringDate: {
type: Date,
},
confirmed: {
type: Boolean,
default: false,
},
});
MovementSchema.statics.findAllIdApp = async function (idapp) {
@@ -90,7 +95,7 @@ MovementSchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, 0, params);
};
MovementSchema.statics.addMov = async function (idapp, accountFromIdTable, accountToIdTable, amount, causal, notifId) {
MovementSchema.statics.addMov = async function (idapp, accountFromIdTable, accountToIdTable, amount, causal, notifId, idOrdersCart) {
try {
// Only positive values
@@ -98,11 +103,11 @@ MovementSchema.statics.addMov = async function (idapp, accountFromIdTable, accou
let mymov = await Movement.create(
{
_id: new ObjectID().toString(),
idapp,
transactionDate: new Date(),
accountFromId: accountFromIdTable._id,
accountToId: accountToIdTable._id,
idOrdersCart,
amount,
causal,
residual: 0,
@@ -693,4 +698,8 @@ MovementSchema.statics.checkIfCoinsAlreadySent = async function (notifId) {
const Movement = mongoose.model('Movement', MovementSchema);
Movement.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Movement };

View File

@@ -125,4 +125,8 @@ MsgTemplateSchema.statics.findAllIdApp = async function (idapp) {
const MsgTemplate = mongoose.model('MsgTemplate', MsgTemplateSchema);
MsgTemplate.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MsgTemplate };

View File

@@ -378,4 +378,8 @@ MyBachecaSchema.statics.getCompleteRecord = function (idapp, id) {
const MyBacheca = mongoose.model('MyBacheca', MyBachecaSchema);
MyBacheca.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MyBacheca };

View File

@@ -210,4 +210,8 @@ MyElemSchema.statics.findAllIdApp = async function (idapp) {
const MyElem = mongoose.model('MyElem', MyElemSchema);
MyElem.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MyElem };

View File

@@ -276,4 +276,8 @@ if (tools.INITDB_FIRSTIME) {
const MyEvent = mongoose.model('MyEvent', MyEventSchema);
MyEvent.createIndexes((err) => {
if (err) throw err;
});
module.exports = {MyEvent};

View File

@@ -348,4 +348,8 @@ MyGoodSchema.statics.getProject = function () {
const MyGood = mongoose.model('MyGood', MyGoodSchema);
MyGood.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MyGood };

View File

@@ -346,7 +346,7 @@ MyGroupSchema.statics.getInfoGroupByGroupname = async function (idapp, groupname
return null;
}
return ris;
return null;
};
@@ -507,9 +507,26 @@ MyGroupSchema.statics.addCircuitFromGroup = async function (idapp, groupname, ci
// Rimuovo il Circuito all'interno del Gruppo
MyGroupSchema.statics.removeCircuitFromGroup = async function (idapp, groupname, circuitname) {
return await this.updateOne({ idapp, groupname },
const ris = await this.updateOne({ idapp, groupname },
{ $pull: { 'mycircuits': { circuitname: { $in: [circuitname] } } } });
const circuitId = await Circuit.getCircuitIdByName(idapp, circuitname);
let remove = false;
// Se il mio account non è stato utilizzato, allora lo cancello anche questo
const myaccount = await Account.getAccountByUsernameAndCircuitId(idapp, username, circuitId, false, false, groupname, '');
if (myaccount && myaccount.totTransato === 0) {
remove = true;
} else {
remove = true;
}
if (remove) {
await Account.removeAccount(myaccount._id);
}
};
MyGroupSchema.statics.getQueryReceiveRISGroups = function (idapp, hours) {
@@ -626,4 +643,8 @@ MyGroupSchema.statics.setReceiveRisGroup = async function (idapp, groupname) {
const MyGroup = mongoose.model('MyGroup', MyGroupSchema);
MyGroup.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MyGroup };

View File

@@ -348,4 +348,8 @@ MyHospSchema.statics.getProject = function () {
const MyHosp = mongoose.model('MyHosp', MyHospSchema);
MyHosp.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MyHosp };

View File

@@ -218,4 +218,8 @@ MyPageSchema.statics.findInternalPages = async function (idapp) {
const MyPage = mongoose.model('MyPage', MyPageSchema);
MyPage.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MyPage };

View File

@@ -354,4 +354,8 @@ MySkillSchema.statics.getCompleteRecord = function (idapp, id) {
const MySkill = mongoose.model('MySkill', MySkillSchema);
MySkill.createIndexes((err) => {
if (err) throw err;
});
module.exports = { MySkill };

View File

@@ -170,4 +170,8 @@ NewstosentSchema.statics.isActivated = async function (_id) {
const Newstosent = mongoose.model('Newstosent', NewstosentSchema);
Newstosent.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Newstosent };

View File

@@ -118,4 +118,8 @@ OperatorSchema.statics.findAllIdApp = function (idapp) {
const Operator = mongoose.model('Operator', OperatorSchema);
Operator.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Operator };

View File

@@ -43,4 +43,8 @@ OpzEmailSchema.statics.findAllIdApp = async function (idapp) {
const OpzEmail = mongoose.model('OpzEmail', OpzEmailSchema);
OpzEmail.createIndexes((err) => {
if (err) throw err;
});
module.exports = { OpzEmail };

View File

@@ -1,7 +1,8 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
@@ -18,23 +19,19 @@ const orderSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
status: {
type: Number,
},
idProduct: {
type: String
},
idProducer: {
type: String
},
idStorehouse: {
type: String
},
idProduct: { type: Schema.Types.ObjectId, ref: 'Product' },
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
idStorehouse: { type: Schema.Types.ObjectId, ref: 'StoreHouse' },
idScontisticas: [{ type: Schema.Types.ObjectId, ref: 'Scontistica' }],
idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' },
idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine' },
price: {
type: Number
type: Number,
default: 0,
},
after_price: {
type: String
@@ -46,7 +43,55 @@ const orderSchema = new Schema({
type: String
},
quantity: {
type: Number
type: Number,
default: 0,
},
quantitypreordered: {
type: Number,
default: 0,
},
TotalPriceProduct: {
type: Number,
default: 0,
},
TotalPriceProductCalc: {
type: Number,
default: 0,
},
confermato: { // e quindi è stato tolto dal magazzino (aggiornando il campo stockQty)
type: Boolean,
default: false,
},
date_confermato: {
type: Date
},
pagato: {
type: Boolean,
default: false,
},
date_pagato: {
type: Date
},
consegnato: {
type: Boolean,
default: false,
},
date_consegnato: {
type: Date
},
spedito: {
type: Boolean,
default: false,
},
date_spedito: {
type: Date
},
ricevuto: {
type: Boolean,
default: false,
},
date_ricevuto: {
type: Date
},
weight: {
type: Number
@@ -72,18 +117,27 @@ const orderSchema = new Schema({
date_delivered: {
type: Date
},
notes: {
note: {
type: String
}
},
modify_at: {
type: Date
},
});
var Order = module.exports = mongoose.model('Order', orderSchema);
module.exports.createIndexes((err) => {
if (err) throw err;
});
module.exports.getFieldsForSearch = function () {
return []
};
module.exports.executeQueryTable = function (idapp, params) {
const tools = require('../tools/general');
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
@@ -92,26 +146,93 @@ module.exports.findAllIdApp = async function (idapp) {
const query = [
{ $match: { idapp } },
{ "$addFields": { "myidProd": { "$toObjectId": "$idProduct" } } },
{ "$addFields": { "myidProducer": { "$toObjectId": "$idProducer" } } },
{
$lookup: {
from: 'products',
localField: 'myidProd',
localField: 'idProduct',
foreignField: '_id',
as: 'product'
}
},
{
$lookup: {
from: 'productinfos',
localField: 'product.idProduct',
foreignField: '_id',
as: 'product.productInfo'
}
},
{
$unwind: {
path: '$product.productInfo',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'producers',
localField: 'myidProducer',
localField: 'product.idProducer',
foreignField: '_id',
as: 'producer'
}
},
{ $unwind: '$product' },
{ $unwind: '$producer' },
{
$lookup: {
from: 'providers',
localField: 'product.idProvider',
foreignField: '_id',
as: 'provider'
}
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine'
}
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
{ 'gasordine': { $exists: false } },
{ 'gasordine.active': true }
]
}
},
{
$lookup: {
from: 'scontisticas',
localField: 'product.idScontisticas',
foreignField: '_id',
as: 'scontistica'
}
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$unwind: {
path: '$producer',
preserveNullAndEmptyArrays: true,
},
},
{
$unwind: {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
},
];
return await Order.aggregate(query)
@@ -132,34 +253,158 @@ module.exports.getOrderByID = function (id, callback) {
}
module.exports.createOrder = async function (order) {
const orderModel = new Order(order);
return await orderModel.save(order)
try {
if (order.idGasordine === '') {
order.idGasordine = undefined;
}
Order.updateTotals(order);
return await Order.create(order)
.then((ris) => {
if (!!ris)
return ris._id;
return null;
});
} catch (e) {
console.error('err', e);
}
}
module.exports.updateStatusOrders = async function (arrOrders, status) {
for (const order of arrOrders) {
let ret = await Order.updateOne({ _id: order.order._id }, { $set: { status } });
}
}
module.exports.updateStatusOrdersElements = async function (arrOrders, myelements) {
for (const order of arrOrders) {
const ret = await Order.findOneAndUpdate({ _id: order.order._id }, { $set: myelements });
}
}
module.exports.updateOrderByParams = async function (idOrder, paramstoupdate) {
const ris = await Order.findOneAndUpdate({ _id: idOrder }, { $set: paramstoupdate });
let myorder = await Order.findOne({ _id: idOrder }).lean();
if (paramstoupdate && !paramstoupdate.hasOwnProperty('TotalPriceProduct')) {
this.updateTotals(myorder);
await Order.findOneAndUpdate({ _id: idOrder }, { $set: myorder });
}
return myorder;
}
module.exports.updateTotals = function (order) {
try {
if (!order) {
return;
}
let mypricecalc = 0;
order.TotalPriceProduct = 0;
order.TotalPriceProductCalc = 0;
order.modify_at = new Date();
// Calcolo Sconto
let sconti_da_applicare = [];
if (order.scontisticas) {
let qtadascontare = order.quantity + order.quantitypreordered
let qtanonscontata = 0
while (qtadascontare > 0) {
let scontoapplicato = null
for (const sconto of order.scontisticas.filter((rec) => !rec.cumulativo)) {
if (qtadascontare >= sconto.qta) {
scontoapplicato = sconto
scontoapplicato.qtadascontare = sconto.qta
}
}
if (scontoapplicato && scontoapplicato.qtadascontare > 0) {
sconti_da_applicare.push(scontoapplicato)
qtadascontare -= scontoapplicato.qtadascontare
} else {
qtanonscontata = qtadascontare
qtadascontare = 0
}
}
/*for (const sconto of order.scontisticas.filter((rec) => rec.cumulativo)) {
if ((sconto.qta % order.quantity) === 0) {
sconti_da_applicare.push(sconto)
}
}*/
if (sconti_da_applicare.length > 0) {
for (const sconto of sconti_da_applicare) {
if (sconto.perc_sconto > 0) {
mypricecalc += (sconto.qtadascontare * order.price) * (1 - (sconto.perc_sconto / 100))
} else {
mypricecalc += sconto.price
}
}
}
if (qtanonscontata > 0) {
mypricecalc += order.price * qtanonscontata;
}
} else {
mypricecalc = (order.price * order.quantity) + (order.price * order.quantitypreordered);
}
order.TotalPriceProductCalc += mypricecalc;
order.TotalPriceProduct += mypricecalc;
return order;
} catch (e) {
console.error('Err:', e);
}
}
module.exports.getTotalOrderById = async function (id) {
const query = [
{ $match: { _id: ObjectID(id) } },
{ "$addFields": { "myidProd": { "$toObjectId": "$idProduct" } } },
{ "$addFields": { "myidProducer": { "$toObjectId": "$idProducer" } } },
{ "$addFields": { "myidStore": { "$toObjectId": "$idStorehouse" } } },
{
$lookup: {
from: 'products',
localField: 'myidProd',
localField: 'idProduct',
foreignField: '_id',
as: 'product'
}
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'productinfos',
localField: 'product.idProductInfo',
foreignField: '_id',
as: 'product.productInfo'
}
},
{
$unwind: {
path: '$product.productInfo',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'producers',
localField: 'myidProducer',
localField: 'product.idProducer',
foreignField: '_id',
as: 'producer'
}
@@ -167,14 +412,192 @@ module.exports.getTotalOrderById = async function (id) {
{
$lookup: {
from: 'storehouses',
localField: 'myidStore',
localField: 'idStorehouse',
foreignField: '_id',
as: 'storehouse'
}
},
{ $unwind: '$product' },
{ $unwind: '$producer' },
{ $unwind: '$storehouse' },
{
$lookup: {
from: 'providers',
localField: 'product.idProvider',
foreignField: '_id',
as: 'provider'
}
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine'
}
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
{ 'gasordine': { $exists: false } },
{ 'gasordine.active': true }
]
}
},
{
$lookup: {
from: 'scontisticas',
localField: 'product.idScontisticas',
foreignField: '_id',
as: 'scontisticas'
}
},
{
$unwind: {
path: '$producer',
preserveNullAndEmptyArrays: true,
},
},
{
$unwind: {
path: '$storehouse',
preserveNullAndEmptyArrays: true,
},
},
{
$unwind: {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'orders',
let: { productId: '$product._id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT]
},
{
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60
]
}]
}
]
}
]
}
},
},
{
$group: {
_id: null,
totalQty: { $sum: '$quantity' },
}
}
],
as: 'productOrders'
}
},
{
$lookup: {
from: 'orders',
let: { productId: '$product._id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT]
},
{
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60
]
}]
}
]
}
]
}
}
},
{
$group: {
_id: null,
totalQtyPreordered: { $sum: '$quantitypreordered' }
}
}
],
as: 'productPreOrders'
}
},
{
$addFields: {
'product.QuantitaOrdinateInAttesa': {
$ifNull: [
{
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
},
0
]
},
'product.QuantitaPrenotateInAttesa': {
$ifNull: [
{
$cond: {
if: { $isArray: '$productPreOrders' },
then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] },
else: 0
}
},
0
]
},
},
},
{
$addFields: {
'product.quantityAvailable': {
$subtract: ["$product.stockQty", "$product.QuantitaOrdinateInAttesa"],
},
'product.bookableAvailableQty': {
$subtract: ["$product.maxbookableGASQty", "$product.QuantitaPrenotateInAttesa"],
}
}
},
{
$unset: 'productOrders'
},
{
$unset: 'productPreOrders'
},
];
return await Order.aggregate(query);

View File

@@ -6,8 +6,20 @@ const shared_consts = require('../tools/shared_nodejs');
const Order = require('../models/order');
var { User } = require('../models/user');
const Storehouse = require('../models/storehouse');
const Provider = require('../models/provider');
const Gasordine = require('../models/gasordine');
const Product = require('../models/product');
const ProductInfo = require('../models/productInfo');
const { Circuit } = require('../models/circuit');
const CartClass = require('../modules/Cart')
const Cart = require('../models/cart');
const tools = require('../tools/general');
const { ObjectID } = require('mongodb');
const OrdersCartSchema = new Schema({
@@ -15,9 +27,12 @@ const OrdersCartSchema = new Schema({
type: String
},
numorder: { type: Number },
numord_pers: { type: Number },
userId: { type: Schema.Types.ObjectId, ref: 'User' },
totalQty: { type: Number, default: 0 },
totalQtyPreordered: { type: Number, default: 0 },
totalPrice: { type: Number, default: 0 },
totalPriceCalc: { type: Number, default: 0 },
department: {
type: String, ref: 'Department'
},
@@ -31,24 +46,83 @@ const OrdersCartSchema = new Schema({
type: Number,
Default: 0,
},
confermato: { // e quindi è stato tolto dal magazzino (aggiornando il campo stockBloccatiQty)
type: Boolean,
default: false,
},
date_confermato: {
type: Date
},
pagato: {
type: Boolean,
default: false,
},
date_pagato: {
type: Date
},
spedito: {
type: Boolean,
default: false,
},
date_spedito: {
type: Date
},
consegnato: { // e quindi è stato tolto dal magazzino (aggiornando il campo stockQty e stockBloccatiQty)
type: Boolean,
default: false,
},
date_consegnato: {
type: Date
},
preparato: {
type: Boolean,
default: false,
},
date_preparato: {
type: Date
},
ricevuto: {
type: Boolean,
default: false,
},
date_ricevuto: {
type: Date
},
note: {
type: String
},
note_per_gestore: {
type: String
},
note_per_admin: {
type: String
},
modify_at: {
type: Date
},
created_at: {
type: Date
},
completed_at: {
type: Date
deleted: {
type: Boolean,
default: false,
},
});
var OrdersCart = module.exports = mongoose.model('OrdersCart', OrdersCartSchema);
function fixupdated(myrec) {
return myrec;
/*if (myrec) {
if (myrec.totalPriceCalc === undefined) {
myrec.totalPriceCalc = myrec.totalPrice;
}
}
return myrec;*/
}
module.exports.findAllIdApp = async function (idapp, userId) {
const myfind = { idapp, userId };
const myfind = { idapp, userId, deleted: false };
return await await OrdersCart.find(myfind);
};
@@ -63,20 +137,29 @@ module.exports.getFieldsForSearch = function () {
};
module.exports.getNewNumOrder = async function (uid, idapp) {
let query = { userId: uid, idapp }
let numorder = 1;
module.exports.getLastNumOrder = async function (idapp) {
let query = { idapp, deleted: false }
let numorder = 100;
let numorderrec = await OrdersCart.find(query).sort({ numorder: -1 }).limit(1);
if (numorderrec.length <= 0)
numorder = 1;
else
numorder = numorderrec[0].numorder;
if (numorder) {
numorder++
} else {
numorder = 1;
}
if (numorderrec && numorderrec.length > 0)
numorder = numorderrec[0].numorder;
else
numorder = 100;
return numorder;
};
module.exports.getLastNumOrdPers = async function (uid, idapp) {
let query = { userId: uid, idapp, deleted: false }
let numorder = 1;
let numorderrec = await OrdersCart.find(query).sort({ numord_pers: -1 }).limit(1);
if (numorderrec && numorderrec.length > 0)
numorder = numorderrec[0].numord_pers;
else
numorder = 0;
return numorder;
@@ -97,132 +180,182 @@ module.exports.getStatusCartByUserId = async function (uid, idapp, numorder) {
return shared_consts.OrderStatus.NONE
}
module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) {
let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
module.exports.getRecCartByUserId = async function (uid, idapp, numorder) {
let query = { userId: uid, idapp, status: { $lt: shared_consts.OrderStatus.CHECKOUT_SENT } }
let myorderscart = null;
if (numorder > 0) {
query = { userId: uid, idapp, numorder, status: { $lt: shared_consts.OrderStatus.CHECKOUT_SENT } }
}
myorderscart = await OrdersCart.findOne(query).lean();
return myorderscart
}
module.exports.getOrdersCartById = async function (id) {
let query = { _id: ObjectID(id) };
const arrris = await OrdersCart.getOrdersCartByQuery(query);
let myrec = arrris && arrris.length > 0 ? arrris[0] : null;
myrec = fixupdated(myrec);
return myrec;
}
module.exports.getOrdersCartByQuery = async function (query) {
let myorderscart = await OrdersCart.find(query)
.populate('items.order')
.populate({
path: 'items.order',
populate: {
path: 'idProduct',
model: 'Product',
populate: {
path: 'idProductInfo',
model: 'ProductInfo'
}
}
})
.populate({
path: 'items.order',
populate: {
path: 'idProducer',
model: 'Producer'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idProvider',
model: 'Provider'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idGasordine',
model: 'Gasordine'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idStorehouse',
model: 'Storehouse'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idScontisticas',
model: 'Scontistica'
}
})
.populate({
path: 'userId',
model: 'User',
select: '_id name surname username profile email lang'
})
.lean();
myorderscart = myorderscart.map(order => {
order.user = order.userId;
order.userId = order.user._id;
order.items = order.items.map(item => {
if (item.order) {
try {
if (item.order.idProduct) {
item.order.idProduct.productInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo : { ...item.order.idProduct.idProductInfo };
item.order.idProduct.idProductInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo._id : '';
}
item.order.product = { ...item.order.idProduct };
item.order.idProduct = item.order.product ? item.order.product._id : '';
item.order.producer = item.order.idProducer;
item.order.idProducer = item.order.producer ? item.order.producer._id : '';
item.order.storehouse = item.order.idStorehouse;
item.order.idStorehouse = item.order.storehouse ? item.order.storehouse._id : '';
item.order.provider = item.order.idProvider;
item.order.idProvider = item.order.provider ? item.order.provider._id : '';
item.order.gasordine = item.order.idGasordine;
item.order.idGasordine = item.order.gasordine ? item.order.gasordine._id : '';
item.order.scontisticas = item.order.scontisticas;
item.order.idScontisticas = item.order.idScontisticas ? item.order.idScontisticas._id : '';
} catch (e) {
console.error('Err: ', e);
}
}
return item;
});
return order;
});
myorderscart = fixupdated(myorderscart);
return myorderscart;
}
module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder, filterStatus) {
try {
let query = { idapp, deleted: false }
let myorderscart = null;
if (numorder > 0) {
query.numorder = numorder;
}
if (uid !== 'ALL') {
if (uid !== 'ALL' && !!uid) {
query.userId = uid;
}
myorderscart = await OrdersCart.find(query).lean();
for (let ind = 0; ind < myorderscart.length; ind++) {
for (const idkey in myorderscart[ind].items) {
try {
let idorder = myorderscart[ind].items[idkey]._id.toString();
const myorder = myorderscart[ind].items[idkey].order;
if (!!myorder) {
idorder = myorderscart[ind].items[idkey].order._id.toString();
}
myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId);
const myord = await Order.getTotalOrderById(idorder);
if (myord.length > 0) {
myorderscart[ind].items[idkey].order = myord[0];
}
} catch (e) {
console.log('err', e);
}
}
if (filterStatus) {
query.status = { $gte: shared_consts.OrderStatus.CHECKOUT_SENT };
}
/* if (!!mycart) {
for (const idkey in mycart.items) {
try {
idorder = mycart.items[idkey]._id.toString();
const myorder = mycart.items[idkey].order;
if (!!myorder) {
idorder = mycart.items[idkey].order._id.toString();
}
const myord = await Order.getTotalOrderById(idorder);
if (myord.length > 0) {
mycart.items[idkey]._doc.order = myord[0];
}
} catch (e) {
console.log('err', e);
}
}
return mycart;
}*/
myorderscart = await OrdersCart.getOrdersCartByQuery(query);
/*transform: function(doc, populated) {
// Rinomina 'idProduct' a 'product' nei risultati della popolazione
populated.product = populated.idProduct;
delete populated.idProduct;
return populated;
},*/
return myorderscart
} catch (e) {
console.error('Err:', e);
}
// return null;
}
module.exports.getOrdersCartByDepartmentId = async function (depId, idapp) {
let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
const myorderscart = await OrdersCart.find(query).lean();
for (let ind = 0; ind < myorderscart.length; ind++) {
for (const idkey in myorderscart[ind].items) {
try {
let idorder = myorderscart[ind].items[idkey]._id.toString();
const myorder = myorderscart[ind].items[idkey].order;
if (!!myorder) {
idorder = myorderscart[ind].items[idkey].order._id.toString();
}
myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId);
const myord = await Order.getTotalOrderById(idorder);
if (myord.length > 0) {
myorderscart[ind].items[idkey].order = myord[0];
}
} catch (e) {
console.log('err', e);
}
}
}
return myorderscart
// return null;
}
module.exports.getOrderById = async function (Id, idapp) {
let query = { _id: Id, idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
const myorderscart = await OrdersCart.find(query).lean();
for (let ind = 0; ind < myorderscart.length; ind++) {
for (const idkey in myorderscart[ind].items) {
try {
let idorder = myorderscart[ind].items[idkey]._id.toString();
const myorder = myorderscart[ind].items[idkey].order;
if (!!myorder) {
idorder = myorderscart[ind].items[idkey].order._id.toString();
}
myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId);
const myord = await Order.getTotalOrderById(idorder);
if (myord.length > 0) {
myorderscart[ind].items[idkey].order = myord[0];
}
} catch (e) {
console.log('err', e);
}
}
}
return myorderscart
// return null;
}
module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) {
let query = { id: id }
let query = {
id,
deleted: false,
}
OrdersCart.find(query, function (err, c) {
if (err) throw err
//exist cart in databse
if (c.length > 0) {
OrdersCart.findOneAndUpdate(
return OrdersCart.findOneAndUpdate(
{ _id: id },
{
$set: {
items: newOrdersCart.items,
totalQty: newOrdersCart.totalQty,
totalQtyPreordered: newOrdersCart.totalQtyPreordered,
totalPrice: newOrdersCart.totalPrice,
totalPriceCalc: newOrdersCart.totalPriceCalc ? newOrdersCart.totalPriceCalc : newOrdersCart.totalPrice,
userId: userId,
status: newOrdersCart.status,
numorder: newOrdersCart.numorder,
numord_pers: newOrdersCart.numord_pers,
note: newOrdersCart.note,
modify_at: new Date(),
}
@@ -232,15 +365,459 @@ module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) {
)
} else {
//no cart in database
newOrdersCart.save(callback)
return newOrdersCart.save(callback)
}
})
}
module.exports.setFieldInOrdersById = async function (objtoset, myOrderCart) {
try {
let ris2 = null;
// Imposta su tutti i singoli prodotti ordinati (Order)
for (const recitem of myOrderCart.items) {
ris2 = await Order.findOneAndUpdate(
{ _id: recitem.order._id },
{
$set: objtoset
},
{ new: false }
)
// console.log('ris', ris2);
}
const ris = await OrdersCart.findOneAndUpdate(
{ _id: myOrderCart._id },
{
$set: objtoset
},
{ new: false }
)
} catch (e) {
console.log('Err', e);
}
}
module.exports.deleteRecsInOrdersById = async function (myOrderCart) {
try {
let ris2 = null;
// Imposta su tutti i singoli prodotti ordinati (Order)
for (const recitem of myOrderCart.items) {
ris2 = await Order.findOneAndRemove({ _id: recitem.order._id })
}
const ris = await OrdersCart.findOneAndRemove({ _id: myOrderCart._id })
} catch (e) {
console.log('Err', e);
}
}
module.exports.setConsegnatoById = async function (value, myOrderCart) {
let objtoset = {
consegnato: value,
date_consegnato: new Date(),
};
return await OrdersCart.setFieldInOrdersById(objtoset, myOrderCart);
}
module.exports.setPreparatoById = async function (value, myOrderCart) {
let objtoset = {
preparato: value,
date_preparato: new Date(),
};
return await OrdersCart.setFieldInOrdersById(objtoset, myOrderCart);
}
module.exports.setSpeditoById = async function (value, myOrderCart) {
let objtoset = {
spedito: value,
date_spedito: new Date(),
};
return await OrdersCart.setFieldInOrdersById(objtoset, myOrderCart);
}
module.exports.setPagatoById = async function (value, myOrderCart) {
let objtoset = {
pagato: value,
date_pagato: new Date(),
};
if (!value) {
objtoset.date_pagato = null;
}
return await OrdersCart.setFieldInOrdersById(objtoset, myOrderCart);
}
module.exports.setConsegnatoById = async function (value, myOrderCart) {
let objtoset = {
consegnato: value,
date_consegnato: new Date(),
};
return await OrdersCart.setFieldInOrdersById(objtoset, myOrderCart);
}
module.exports.setConfermatoById = async function (value, myOrderCart) {
let objtoset = {
confermato: value,
date_confermato: new Date(),
};
return await OrdersCart.setFieldInOrdersById(objtoset, myOrderCart);
}
module.exports.setRicevutoById = async function (value, myOrderCart) {
let objtoset = {
ricevuto: value,
date_ricevuto: new Date(),
};
return await OrdersCart.setFieldInOrdersById(objtoset, myOrderCart);
}
module.exports.deleteReally = async function (value, myOrderCart) {
return await OrdersCart.deleteRecsInOrdersById(myOrderCart);
}
module.exports.createOrdersCart = async function (newOrdersCart) {
return await newOrdersCart.save()
}
module.exports.addOrderToMovement = async function (myOrderCart, usernameStore, groupnameStore, req) {
try {
if (myOrderCart) {
const mymov = await Circuit.addMovementByOrdersCart(myOrderCart, usernameStore, groupnameStore);
return mymov;
}
return null;
} catch (e) {
console.error('Err', e);
}
}
module.exports.checkQtaIfIsLow_SendAlert = async function (idapp, idProduct) {
try {
const telegrambot = require('../telegram/telegrambot');
const isLow = await Product.isLowQuantityInStockById(idProduct);
const instock = await Product.getInStockById(idProduct);
const myprod = await Product.getProductById(idProduct);
if (isLow && myprod) {
let msg = `Il Prodotto '${myprod.productInfo.name}' è rimasto a ${instock} quantità !`;
await telegrambot.sendMsgTelegramToTheManagers(idapp, msg);
}
} catch (e) {
console.error('Err;', e);
}
}
module.exports.updateMagazzinoOrdineInLavorazione = async function (idorderscart) {
try {
const myorderscart = await OrdersCart.findOne({ _id: idorderscart }).populate('items.order').lean();
if (myorderscart) {
for (const idkey in myorderscart.items) {
let order = myorderscart.items[idkey].order;
if (!order.confermato) { // Se ancora non è stato confermato:
let update = {
$inc: {
bookedQtyOrdered: order.quantity,
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
update = {
$inc: {
bookedGASQtyOrdered: order.quantitypreordered,
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
await OrdersCart.checkQtaIfIsLow_SendAlert(myorderscart.idapp, order.idProduct)
}
}
}
} catch (e) {
console.error('Err', e);
}
}
module.exports.updateStockQtaDalMagazzinoOrdineConfermato = async function (idorderscart) {
try {
const myorderscart = await OrdersCart.findOne({ _id: idorderscart }).populate('items.order').lean();
if (myorderscart) {
for (const idkey in myorderscart.items) {
let order = myorderscart.items[idkey].order;
if (!order.confermato) { // Se ancora non è stato confermato:
let update = {
$inc: {
stockQty: -order.quantity,
stockBloccatiQty: order.quantity,
bookedQtyConfirmed: order.quantity,
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
update = {
$inc: {
maxbookableGASQty: -order.quantitypreordered,
bookableGASBloccatiQty: order.quantitypreordered,
bookedGASQtyConfirmed: order.quantitypreordered,
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
}
}
}
} catch (e) {
console.error('Err', e);
}
}
module.exports.updateStockBloccatiQtaDalMagazzinoOrdineConsegnato = async function (idorderscart) {
try {
const myorderscart = await OrdersCart.findOne({ _id: idorderscart }).populate('items.order').lean();
if (myorderscart) {
for (const idkey in myorderscart.items) {
let order = myorderscart.items[idkey].order;
if (!order.consegnato) {
let update = {
$inc: {
stockBloccatiQty: -order.quantity
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
update = {
$inc: {
bookableGASBloccatiQty: -order.quantitypreordered
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
}
}
}
} catch (e) {
console.error('Err', e);
}
}
module.exports.updateStockQtaPerCancellazioneOrdine = async function (idorderscart) {
try {
const myorderscart = await OrdersCart.findOne({ _id: idorderscart }).populate('items.order').lean();
if (myorderscart) {
for (const idkey in myorderscart.items) {
let order = myorderscart.items[idkey].order;
let update = {};
let fieldstoUpdate = {};
if (order.consegnato) {
// Se l'ordine era stato già Consegnato, allora non fare niente !
return false;
} else {
if (order.confermato) { // Se l'ordine era stato confermato, allora rimetti le Qta in Magazzino
fieldstoUpdate = {
...fieldstoUpdate,
stockQty: order.quantity,
stockBloccatiQty: -order.quantity,
bookedQtyConfirmed: -order.quantity,
}
}
fieldstoUpdate = {
...fieldstoUpdate,
bookedQtyOrdered: -order.quantity,
}
update = {
$inc: fieldstoUpdate,
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
// --------------
fieldstoUpdate = {};
if (order.confermato) { // Se l'ordine era stato confermato, allora rimetti le Qta in Magazzino
fieldstoUpdate = {
...fieldstoUpdate,
maxbookableGASQty: order.quantitypreordered,
bookableGASBloccatiQty: -order.quantitypreordered,
bookedGASQtyConfirmed: -order.quantitypreordered,
}
}
fieldstoUpdate = {
...fieldstoUpdate,
bookedGASQtyOrdered: -order.quantitypreordered,
}
update = {
$inc: fieldstoUpdate,
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
}
}
}
} catch (e) {
console.error('Err', e);
}
}
module.exports.getStorehouseByOrdersCart = function (ordersCart) {
return ordersCart && ordersCart.items && ordersCart.items.length > 0 && ordersCart.items[0].order.storehouse
? ordersCart.items[0].order.storehouse
: null
}
module.exports.getUsernameStorehouseActual = async function (ordersCart) {
const storehouse = OrdersCart.getStorehouseByOrdersCart(ordersCart);
return storehouse
? storehouse.username
: null
}
module.exports.getGroupnameStorehouseActual = async function (ordersCart) {
const storehouse = OrdersCart.getStorehouseByOrdersCart(ordersCart);
return storehouse
? storehouse.groupname
: null
}
module.exports.updateCmd = async function (ordersCart, status, value, req, options) {
let myOrderCart = await OrdersCart.getOrdersCartById(ordersCart._id);
// let myOrderCart = await OrdersCart.findOne({ _id: ordersCart._id })
// .populate('items.order').lean();
const usernameStore = await OrdersCart.getUsernameStorehouseActual(myOrderCart);
const groupnameStore = await OrdersCart.getGroupnameStorehouseActual(myOrderCart);
try {
if (!!myOrderCart) {
const id = myOrderCart._id;
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
if (value) {
await OrdersCart.updateMagazzinoOrdineInLavorazione(id);
}
} else if (status === shared_consts.OrderStatus.ORDER_CONFIRMED) {
// Aggiorna anche il Magazzino, togliendo le quantità in Stock e aggiungendole su quelle bloccate
if (value) {
await OrdersCart.updateStockQtaDalMagazzinoOrdineConfermato(id);
}
ris = await OrdersCart.setConfermatoById(value, myOrderCart);
} else if (status === shared_consts.OrderStatus.PAYED) {
if (value) {
if (!myOrderCart.pagato) { // Se ancora non è stato confermato:
await OrdersCart.addOrderToMovement(myOrderCart, usernameStore, groupnameStore, req);
ris = await OrdersCart.setPagatoById(value, myOrderCart);
}
}
} else if (status === shared_consts.OrderStatus.PREPARED) {
ris = await OrdersCart.setPreparatoById(value, myOrderCart);
} else if (status === shared_consts.OrderStatus.DELIVERED) { // Consegnato
if (value) {
await OrdersCart.updateStockBloccatiQtaDalMagazzinoOrdineConsegnato(id);
}
ris = await OrdersCart.setConsegnatoById(value, myOrderCart);
} else if (status === shared_consts.OrderStatus.SHIPPED) {
ris = await OrdersCart.setSpeditoById(value, myOrderCart);
} else if (status === shared_consts.OrderStatus.RECEIVED) {
ris = await OrdersCart.setRicevutoById(value, myOrderCart);
} else if (status === shared_consts.OrderStatus.PREPARED) {
ris = await OrdersCart.setPreparatoById(value, myOrderCart);
} else if (status === shared_consts.OrderStatus.CANCELED) {
await OrdersCart.updateStockQtaPerCancellazioneOrdine(id)
} else if (status === shared_consts.OrderStatus.DELETE_REALLY) {
await OrdersCart.updateStockQtaPerCancellazioneOrdine(id)
ris = await OrdersCart.deleteReally(value, myOrderCart);
}
if (status !== shared_consts.OrderStatus.DELETE_REALLY) {
await OrdersCart.setFieldInOrdersById({ status }, myOrderCart);
myOrderCart = await OrdersCart.getOrdersCartById(ordersCart._id)
}
// myOrderCart = await OrdersCart.findOne({ _id: idorderscart });
return myOrderCart;
}
} catch (e) {
console.error('Err:', e)
}
}
OrdersCartSchema.pre('save', async function (next) {
try {
@@ -276,3 +853,95 @@ OrdersCartSchema.pre('save', async function (next) {
console.error(e.message);
}
});
module.exports.updateOrdersCartByParams = async function (idOrdersCart, paramstoupdate) {
const ris = await OrdersCart.findOneAndUpdate({ _id: idOrdersCart }, { $set: paramstoupdate });
let myorderscart = await OrdersCart.getOrdersCartById(idOrdersCart);
return myorderscart;
}
module.exports.updateOrdersCartTotals = async function (idOrdersCart, update) {
try {
let orderscart = await OrdersCart.getOrdersCartById(idOrdersCart);
if (orderscart) {
let newOrdersCart = CartClass.constructByCart(orderscart);
await newOrdersCart.updatecarttotals(false);
if (update) {
await OrdersCart.findOneAndUpdate({ _id: idOrdersCart }, {
$set: {
totalPrice: newOrdersCart.totalPrice,
totalPriceCalc: newOrdersCart.totalPriceCalc,
totalQty: newOrdersCart.totalQty,
note: newOrdersCart.note,
modify_at: new Date(),
},
}
)
}
orderscart = await OrdersCart.getOrdersCartById(idOrdersCart);
return orderscart;
}
} catch (e) {
console.error('err', e);
}
};
module.exports.getmsgorderTelegram = async function (ordersCart) {
try {
const statusstr = shared_consts.getStatusStr(ordersCart.status);
let msg = '🟢✍️ Ordine n. ' + ordersCart.numorder
msg += '<br>Stato: ' + statusstr;
msg += '<br>🙎🏻‍♂️ ' + tools.getNomeCognomeEUserNameByUser(ordersCart.user)
if (ordersCart.note)
msg += '<br>Note: ' + ordersCart.note;
msg += '<br><br>Lista Prodotti: (🍊🥑🍋)';
for (const ord of ordersCart.items) {
msg += '<br>';
let qtystr = ''
let qtynum = 0
if (ord.order.quantity > 0)
qtynum += ord.order.quantity;
if (ord.order.quantitypreordered > 0)
qtynum += ord.order.quantitypreordered;
qtystr += qtynum + ' ' + tools.getUnitsMeasure(ord.order.product.productInfo.unit, true);
if (ord.order.quantitypreordered > 0)
qtystr += ' Pre-Ordinati';
msg += '✅ [' + qtystr + '] ' + ord.order.product.productInfo.name + ' a ' + ord.order.price + '€ ' + (ord.order.after_price ? ord.order.after_price : '') + '<br>Totale = ' + ord.order.TotalPriceProduct + '€';
}
msg += '<br>';
let totqta = ordersCart.totalQty + ordersCart.totalQtyPreordered;
msg += '<br>Totale Prodotti: ' + totqta;
msg += '<br>Totale Ordine: ' + ordersCart.totalPrice + ' € 💰';
return msg;
} catch (e) {
console.error('Err', e);
}
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -45,4 +45,8 @@ PaymentTypeSchema.statics.findAllIdApp = async function (idapp) {
const PaymentType = mongoose.model('Paymenttype', PaymentTypeSchema);
PaymentType.createIndexes((err) => {
if (err) throw err;
});
module.exports = { PaymentType };

View File

@@ -57,4 +57,8 @@ PermissionSchema.statics.findAllIdApp = async function () {
const Permission = mongoose.model('Permission', PermissionSchema);
Permission.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Permission };

View File

@@ -100,3 +100,7 @@ module.exports.getProducerByID = function (id, callback) {
// const Producer = mongoose.model('Producer', producerSchema);
// module.exports = { Producer };
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -3,9 +3,22 @@ const Schema = mongoose.Schema;
const tools = require('../tools/general');
const Producer = require('../models/producer');
const Storehouse = require('../models/storehouse');
const Provider = require('../models/provider');
const CatProd = require('../models/catprod');
const SubCatProd = require('../models/subcatprod');
const Gasordine = require('../models/gasordine');
const Scontistica = require('../models/scontistica');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// A1P
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
@@ -18,28 +31,18 @@ const productSchema = new Schema({
},
active: {
type: Boolean,
default: true,
},
idProducer: {
type: String
},
idProductInfo: { type: Schema.Types.ObjectId, ref: 'ProductInfo' },
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
idStorehouses: [
{ type: Schema.Types.ObjectId, ref: 'Storehouse' }
],
code: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
department: {
type: String, ref: 'Department'
},
category: {
type: Array,
},
idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine' },
idScontisticas: [
{ type: Schema.Types.ObjectId, ref: 'Scontistica' }
],
idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' },
prezzo_ivato: { // Con IVA
type: Number
},
@@ -47,62 +50,131 @@ const productSchema = new Schema({
type: Number
},
price: {
type: Number
type: Number,
required: true,
},
price_acquistato: {
type: Number,
required: true,
},
after_price: {
type: String
},
color: {
type: String
minBuyQty: { // quantità minima acquistabile
type: Number,
default: 1,
required: true,
},
size: {
type: String
minStepQty: { // step quantità acquistabile
type: Number,
default: 1,
required: true,
},
weight: {
type: Number
maxBookableSinglePersQty: { // quantità massima Pre-ordinabile (singolarmente)
type: Number,
default: 0,
},
unit: {
type: Number
stockQty: { // in magazzino
type: Number,
default: 0,
},
quantityAvailable: {
type: Number
stockBloccatiQty: { // Prenotati Bloccati
type: Number,
default: 0,
},
bookedQtyOrdered: { // Quantità Prenotate ordinate (in Lavorazione)
type: Number,
default: 0,
},
bookedQtyConfirmed: { // Quantità Prenotate Confermate Totali
type: Number,
default: 0,
},
// GAS:
qtyToReachForGas: { // Quantità minima da raggiungere per fare l'ordine GAS
type: Number,
default: 0,
},
maxbookableGASQty: { // Quantità massima (ancora disponibile) Ordine GAS prenotabile (Complessivamente tra tutti gli ordini)
type: Number,
default: 0,
},
bookedGASQtyOrdered: { // Quantità Ordine GAS Prenotate Totali
type: Number,
default: 0,
},
bookedGASQtyConfirmed: { // Quantità Ordine GAS Confermate Totali
type: Number,
default: 0,
},
bookableGASBloccatiQty: { // Quantità Prenotate Bloccate GAS
type: Number,
default: 0,
},
quantityLow: { //Soglia disponibilità bassa
type: Number
type: Number,
default: 0,
},
visibilityProductOutOfStock: { // Visibilità prodotto "esaurito"
type: Boolean
type: Boolean,
default: false,
},
canBeShipped: { // è spedibile
type: Boolean
type: Boolean,
default: false,
},
canBeBuyOnline: { // è acquistabile online
type: Boolean
type: Boolean,
default: false,
},
stars: {
type: Number
type: Number,
default: 0,
},
dateAvailableFrom: {
type: Date
},
icon: {
note: {
type: String,
},
img: {
producer_name: {
type: String,
},
img2: {
provider_name: {
type: String,
},
img3: {
magazzino_name: {
type: String,
},
cat_name: {
type: String,
},
subcat_name: {
type: String,
},
sconto1: {
type: String,
},
sconto2: {
type: String,
},
gas_name: {
type: String,
},
});
var Product = module.exports = mongoose.model('Product', productSchema);
productSchema.index({ idapp: 1 });
module.exports.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
@@ -110,27 +182,188 @@ module.exports.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp, code) {
let myfind = { idapp, active: true };
module.exports.getProductByCode = function (idapp, code) {
return Product.findAllIdApp(idapp, code);
}
module.exports.getProductById = async function (id) {
const arrris = await Product.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
module.exports.getInStockById = async function (id) {
const myprod = await Product.findOne({ _id: id });
if (myprod) {
let instock = 0;
if (myprod.idGasordine) {
instock = myprod.maxbookableGASQty;
} else {
instock = myprod.stockQty;
}
return instock
}
return null;
}
module.exports.isLowQuantityInStockById = async function (id) {
const instock = await Product.getInStockById(id);
const myprod = await Product.findOne({ _id: id });
if (instock) {
return (instock <= (myprod.quantityLow + 1));
}
return false;
}
module.exports.findAllIdApp = async function (idapp, code, id, all) {
let myfind = {};
let myqueryadd = {};
let query = [];
try {
if (idapp) {
myfind = { idapp };
}
if (!all) {
myfind = { ...myfind, active: true }
}
if (code) {
myfind = { ...myfind, code }
}
if (id) {
myqueryadd = {
$addFields: {
myId1: {
$toObjectId: id,
},
},
}
myfind = {
$expr: {
$eq: ["$_id", "$myId1"],
},
}
query.push(myqueryadd);
}
// DA TOGLIEREE
// myfind = { ...myfind, code: '4012824406094' };
// return await Product.find(myfind);
const query = [
query.push(
{ $match: myfind },
{ "$addFields": { "myidProd": { "$toObjectId": "$idProducer" } } },
{
$lookup: {
from: 'producers',
localField: 'myidProd',
localField: 'idProducer',
foreignField: '_id',
as: 'producer'
}
},
{ $unwind: '$producer' },
{
$unwind: {
path: '$producer',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'productinfos',
localField: 'idProductInfo',
foreignField: '_id',
as: 'productInfo'
}
},
{
$unwind: {
path: '$productInfo',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine'
}
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
{ 'gasordine.active': true }, // Include documents where gasordines.active is true
{ 'gasordine': { $exists: false } } // Include documents where gasordines array doesn't exist
]
}
},
{
$group: {
_id: '$_id',
gasordine: { $first: '$gasordine' },
originalFields: { $first: '$$ROOT' } // Preserve all existing fields
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: ['$originalFields', { gasordine: '$gasordine' }]
}
}
},
{
$unwind: {
path: '$producer',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'providers',
localField: 'idProvider',
foreignField: '_id',
as: 'provider'
}
},
{
$unwind: {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'catprods',
localField: 'idCatProds',
foreignField: '_id',
as: 'catprods'
}
},
{
$lookup: {
from: 'subcatprods',
localField: 'idSubCatProds',
foreignField: '_id',
as: 'subcatprods'
}
},
{
$lookup: {
from: 'scontisticas',
localField: 'idScontisticas',
foreignField: '_id',
as: 'scontisticas'
}
},
{
$lookup: {
from: 'storehouses',
@@ -139,12 +372,149 @@ module.exports.findAllIdApp = async function (idapp, code) {
as: 'storehouses'
}
},
];
{
$lookup: {
from: 'orders',
let: { productId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT]
},
{
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60
]
}]
}
]
}
]
}
}
},
{
$group: {
_id: null,
totalQty: { $sum: '$quantity' },
}
}
],
as: 'productOrders'
}
},
{
$lookup: {
from: 'orders',
let: { productId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT]
},
{
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60
]
}]
}
]
}
]
}
}
},
{
$group: {
_id: null,
totalQtyPreordered: { $sum: '$quantitypreordered' }
}
}
],
as: 'productPreOrders'
}
},
{
$addFields: {
QuantitaOrdinateInAttesa: {
$ifNull: [
{
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
},
0
]
},
QuantitaPrenotateInAttesa: {
$ifNull: [
{
$cond: {
if: { $isArray: '$productPreOrders' },
then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] },
else: 0
}
},
0
]
},
},
},
{
$addFields: {
quantityAvailable: {
$subtract: ["$stockQty", "$QuantitaOrdinateInAttesa"],
},
bookableAvailableQty: {
$subtract: ["$maxbookableGASQty", "$QuantitaPrenotateInAttesa"],
}
}
},
{
$unset: 'productOrders'
},
{
$unset: 'productPreOrders'
},
{
$sort: {
'productInfo.name': 1 // 1 for ascending order, -1 for descending order
}
},
);
// console.log('query=', query);
let ris = await Product.aggregate(query)
// console.table('ris', ris);
return ris;
} catch (e) {
console.error('E', e);
}
};
@@ -156,7 +526,7 @@ module.exports.getProductByDepartment = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
module.exports.getProductByCategory = function (query, sort, callback) {
module.exports.getProductByCatProd = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
@@ -164,19 +534,15 @@ module.exports.getProductByTitle = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
module.exports.getProductByCode = function (idapp, code) {
return Product.findOne({ idapp, code })
}
module.exports.filterProductByDepartment = function (department, callback) {
let regexp = new RegExp(`^${department}$`, 'i')
var query = { department: { $regex: regexp } };
Product.find(query, callback)
}
module.exports.filterProductByCategory = function (category, callback) {
let regexp = new RegExp(`^${category}$`, 'i')
var query = { category: { $regex: regexp } };
module.exports.filterProductByCatProd = function (catprod, callback) {
let regexp = new RegExp(`^${catprod}$`, 'i')
var query = { catprod: { $regex: regexp } };
Product.find(query, callback);
}
@@ -190,9 +556,266 @@ module.exports.getProductByID = function (id, callback) {
Product.findById(id, callback);
}
module.exports.updateProductInOrder = async function (order) {
if (order.product)
order.product = await Product.getProductById(order.product._id);
return order;
}
module.exports.createIndexes((err) => {
if (err) throw err;
});
module.exports.convertAfterImportALLPROD = async function (idapp, dataObjects) {
const arrprod = await Product.find({ idapp }).lean();
for (const prod of arrprod) {
await this.singlerecconvert_AfterImport_AndSave(prod);
}
};
module.exports.getArrCatProds = async function (idapp, cosa) {
try {
let addquery = {};
let arr = [];
if (cosa === shared_consts.PROD.GAS) {
addquery = { idapp, idGasordine: { $exists: true, $ne: null, $type: 'objectId' } }
} else if (cosa === shared_consts.PROD.BOTTEGA) {
addquery = {
idapp, $or: [
{ idGasordine: { $exists: false } },
{ idGasordine: { $exists: true, $eq: null } }
]
}
} else {
addquery = { idapp };
}
let myquery = [
{ $match: addquery },
{
$lookup: {
from: "productinfos",
localField: "idProductInfo",
foreignField: "_id",
as: "productInfo",
},
},
{
$lookup: {
from: "catprods",
localField: "productInfo.idCatProds",
foreignField: "_id",
as: "category"
}
},
{ $unwind: "$category" },
{ $group: { _id: "$category._id", name: { $first: "$category.name" } } },
{ $sort: { name: 1 } }
];
arr = await Product.aggregate(myquery, (err, result) => {
if (err) {
console.error(err);
// Gestisci l'errore come desideri
return [];
} else {
const uniqueCategories = result.map(category => category.name);
// console.log(uniqueCategories);
return uniqueCategories;
// Ora uniqueCategories contiene l'array delle categorie univoche utilizzate in tutti i prodotti con active = true
}
});
return arr;
} catch (e) {
console.error('err', e);
return [];
}
// const Product = mongoose.model('Product', ProductSchema);
}
// module.exports = { Product };
// PROVA
module.exports.singlerecconvert_AfterImport_AndSave = async function (idapp, prod, isnuovo) {
let setta = false;
try {
let objtoset = {}
let rec = null
// Impostazioni Base:
if (isnuovo) {
objtoset = {
idapp,
// minBuyQty: 1,
// minStepQty: 1,
maxBookableSinglePersQty: 0,
bookedGASQtyOrdered: 0,
bookableGASBloccatiQty: 0,
bookedGASQtyConfirmed: 0,
// qtyToReachForGas: 0,
// maxbookableGASQty: 0,
}
}
if (prod.producer_name) {
// Cerca il produttore
let recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean();
if (!recproducer) {
// Non esiste questo produttore, quindi lo creo !
recproducer = new Producer({ idapp, name: prod.producer_name });
ris = await recproducer.save();
recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean();
}
if (recproducer) {
objtoset = {
...objtoset,
idProducer: recproducer._id,
}
setta = true;
}
}
if (prod.magazzino_name) {
// Cerca il produttore
let recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean();
if (!recstorehouse) {
// Non esiste questo produttore, quindi lo creo !
recstorehouse = new Storehouse({ idapp, name: prod.magazzino_name });
ris = await recstorehouse.save();
recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean();
}
if (recstorehouse) {
objtoset = {
...objtoset,
idStorehouses: [recstorehouse._id],
}
setta = true;
}
}
if (prod.provider_name) {
// Cerca il produttore
let recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean();
if (!recprovider) {
recprovider = new Provider({ idapp, name: prod.provider_name });
// Non esiste questo produttore, quindi lo creo !
ris = await recprovider.save();
recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean();
}
if (recprovider) {
objtoset = {
...objtoset,
idProvider: recprovider._id,
}
setta = true;
}
}
if (prod.gas_name) {
// Cerca il GAS
rec = await Gasordine.findOne({ idapp, name: prod.gas_name }).lean();
if (!rec) {
rec = new Gasordine({ idapp, name: prod.gas_name, active: true });
// Non esiste questo GAS, quindi lo creo !
ris = await rec.save();
rec = await Gasordine.findOne({ idapp, name: prod.gas_name }).lean();
}
if (rec) {
objtoset = {
...objtoset,
idGasordine: rec._id,
}
setta = true;
}
}
let arrsconti = []
if (prod.sconto1) {
// Cerca la scontistica
let recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto1 }).lean();
if (!recscontistica) {
recscontistica = new Scontistica({ idapp, code: prod.sconto1 });
// Non esiste questa scontistica, quindi lo creo !
ris = await recscontistica.save();
recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto1 }).lean();
}
if (recscontistica) {
arrsconti.push(recscontistica);
}
}
if (prod.sconto2) {
// Cerca la scontistica
let recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto2 }).lean();
if (!recscontistica) {
recscontistica = new Scontistica({ idapp, code: prod.sconto2 });
// Non esiste questa scontistica, quindi lo creo !
ris = await recscontistica.save();
recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto2 }).lean();
}
if (recscontistica) {
arrsconti.push(recscontistica);
}
}
if (arrsconti.length > 0) {
objtoset = {
...objtoset,
idScontisticas: arrsconti,
}
setta = true;
}
// Aggiorna il prezzo ?
const aggiornaprezzo = false;
if (aggiornaprezzo) {
// cerca il prodotto
const myprodinput = dataObjects.find((rec) => rec._id === prod._id)
if (myprodinput) {
objtoset = {
...objtoset,
price: myprodinput.price,
}
}
}
if (!tools.isObjectEmpty(objtoset)) {
ris = await Product.findOneAndUpdate({ _id: ObjectID(prod._id) }, { $set: objtoset })
const objDelete = {
cat_name: 1,
subcat_name: 1,
producer_name: 1,
provider_name: 1,
magazzino_name: 1,
sconto1: 1,
sconto2: 1,
gas_name: 1,
};
ris = await Product.updateOne({ _id: ObjectID(prod._id) }, { $unset: objDelete })
if (ris) {
console.log('ris', ris);
}
// const campodarimuovere = 'producer_name';
// await Product.findOneAndUpdate({ _id: prod._id }, { $unset: { [campodarimuovere]: 1 } })
}
} catch (e) {
console.error('Err', e);
}
}

166
src/server/models/productInfo.js Executable file
View File

@@ -0,0 +1,166 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const productInfoSchema = new Schema({
idapp: {
type: String,
},
department: {
type: String, ref: 'Department'
},
code: {
type: String,
unique: true,
required: true,
},
codice_EAN: {
type: String,
},
barcode: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd' }],
idSubCatProds: [{ type: Schema.Types.ObjectId, ref: 'SubCatProd' }],
color: {
type: String
},
size: {
type: String
},
weight: {
type: Number
},
vegan: {
type: Boolean
},
unit: {
type: Number,
default: 0,
},
icon: {
type: String,
},
img: {
type: String,
},
link: {
type: String,
},
img2: {
type: String,
},
img3: {
type: String,
},
ingredienti: {
type: String,
},
valori_nutrizionali: {
type: String,
},
note: {
type: String,
},
});
var productInfo = module.exports = mongoose.model('ProductInfo', productInfoSchema);
module.exports.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp, code, id) {
let myfind = {};
let myqueryadd = {};
let query = [];
try {
if (idapp)
myfind = { idapp };
if (code) {
myfind = { ...myfind, code }
}
if (id) {
myqueryadd = {
$addFields: {
myId1: {
$toObjectId: id,
},
},
}
myfind = {
$expr: {
$eq: ["$_id", "$myId1"],
},
}
query.push(myqueryadd);
}
query.push(
{ $match: myfind },
{
$lookup: {
from: 'catprods',
localField: 'idCatProds',
foreignField: '_id',
as: 'catprods'
}
},
{
$lookup: {
from: 'subcatprods',
localField: 'idSubCatProds',
foreignField: '_id',
as: 'subcatprods'
}
},
{
$sort: {
name: 1 // 1 for ascending order, -1 for descending order
}
},
);
let ris = await productInfo.aggregate(query)
return ris;
} catch (e) {
console.error('E', e);
}
};
module.exports.getProductByCode = function (idapp, code) {
return productInfo.findAllIdApp(idapp, code);
}
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -428,5 +428,9 @@ ProjectSchema.pre('save', function (next) {
var Project = mongoose.model('Projects', ProjectSchema);
Project.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Project };

64
src/server/models/provider.js Executable file
View File

@@ -0,0 +1,64 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const providerSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
referent: {
type: String,
},
address: {
type: String,
},
city: {
type: String,
},
region: {
type: String,
},
img: {
type: String,
},
website: {
type: String,
},
});
var Provider = module.exports = mongoose.model('Provider', providerSchema);
module.exports.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Provider.find(myfind);
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -127,4 +127,8 @@ ProvinceSchema.statics.findAllIdApp = async function(idapp) {
const Province = mongoose.model('Province', ProvinceSchema);
Province.createIndexes((err) => {
if (err) throw err;
});
module.exports = {Province};

86
src/server/models/queryai.js Executable file
View File

@@ -0,0 +1,86 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// const CatAI = require('./catai');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const QueryAISchema = new Schema({
idapp: {
type: String,
},
descr: {
type: String,
},
catAI: { type: Schema.Types.ObjectId, ref: 'CatAI' },
query: {
type: String,
},
ask: [
{
descr: {
type: String,
},
value: {
type: Number,
},
}
],
buttons: [
{
type: String, //ButtonCodeAction
},
],
output_type: {
type: String,
},
icon: {
type: String,
},
img: {
type: String,
},
});
QueryAISchema.statics.findAllIdApp = async function (idapp) {
const QueryAI = this;
const query = [
{ $sort: { descr: 1 } }
];
return await QueryAI
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
QueryAISchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
QueryAISchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const QueryAI = mongoose.model('QueryAI', QueryAISchema);
QueryAI.createIndexes((err) => {
if (err) throw err;
});
module.exports = { QueryAI };

View File

@@ -189,10 +189,10 @@ reactionSchema.statics.updateReactionsCounts = async function () {
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,
numseen: ris.myreact.numseen ?? 0,
numfav: ris.myreact.numfav ?? 0,
numbook: ris.myreact.numbook ?? 0,
numattend: ris.myreact.numattend ?? 0,
}
})
}
@@ -433,4 +433,8 @@ reactionSchema.statics.removeBookmark = async function (
const Reaction = mongoose.model('Reaction', reactionSchema);
Reaction.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Reaction };

View File

@@ -0,0 +1,62 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const scontisticaSchema = new Schema({
idapp: {
type: String,
},
code: {
type: String,
},
description: {
type: String,
},
qta: {
type: Number,
},
perc_sconto: {
type: Number,
},
price: {
type: Number,
},
comulativo: {
type: Boolean,
default: false,
},
});
var Scontistica = module.exports = mongoose.model('Scontistica', scontisticaSchema);
module.exports.getFieldsForSearch = function () {
return [
{ field: 'code', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string }
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Scontistica.find(myfind);
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -42,4 +42,8 @@ searchSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) {
const Search = mongoose.model('Search', searchSchema);
Search.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Search };

View File

@@ -80,4 +80,8 @@ SectorGoodSchema.statics.executeQueryTable = function (idapp, params) {
const SectorGood = mongoose.model('SectorGood', SectorGoodSchema);
SectorGood.createIndexes((err) => {
if (err) throw err;
});
module.exports = { SectorGood };

View File

@@ -109,4 +109,8 @@ sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username
const SendMsg = mongoose.model('SendMsg', sendmsgSchema);
SendMsg.createIndexes((err) => {
if (err) throw err;
});
module.exports = { SendMsg };

View File

@@ -357,6 +357,7 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
let circuitname = '';
let numuserincircuit = 0;
try {
circuitname = recnotif.paramsObj.circuitnameDest;
username_action = recnotif.paramsObj.username_action
username_mittente = recnotif.paramsObj.sender ? recnotif.paramsObj.sender : username_action
myorig = recnotif.paramsObj.extrarec.grouporig;
@@ -364,7 +365,6 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
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) {
@@ -1220,4 +1220,8 @@ sendNotifSchema.statics.checkIfAlreadyExist = async function (idapp, tag, idpost
const SendNotif = mongoose.model('SendNotif', sendNotifSchema);
SendNotif.createIndexes((err) => {
if (err) throw err;
});
module.exports = { SendNotif: SendNotif };

View File

@@ -178,4 +178,8 @@ SettingsSchema.statics.getKeyNum = async function (idapp, key, mydefault) {
const Settings = mongoose.model('Settings', SettingsSchema);
Settings.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Settings };

View File

@@ -47,3 +47,6 @@ module.exports.findAllIdApp = async function (idapp) {
return await ShareWithUs.find(myfind);
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -1,13 +1,15 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
mongoose.set('debug', false);
const { ObjectID } = require('mongodb');
const _ = require('lodash');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
@@ -62,6 +64,12 @@ const SiteSchema = new Schema({
telegram_key_test: {
type: String,
},
load_process_telegram: {
type: Boolean,
},
load_process_telegram_test: {
type: String,
},
teleg_cfg: {
type: String,
},
@@ -103,44 +111,51 @@ const SiteSchema = new Schema({
},
confpages: {
font: { type: String, default: '' },
col_toolbar: { type: String },
col_bgfooter: { type: String },
show_darkopt: { type: Boolean, default: true },
showButtHome: { type: Boolean },
showProfile: { type: Boolean },
showUserMenu: { type: Boolean },
showRegButton: { type: Boolean },
enableReg: { type: Boolean },
showNL: { type: Boolean },
showMsgs: { type: Boolean },
showNotif: { type: Boolean },
showCoins: { type: Boolean },
showNameSurname: { type: Boolean },
showCompetenze: { type: Boolean },
showConnected: { type: Boolean },
bookingEvents: { type: Boolean },
enableEcommerce: { type: Boolean },
enableGroups: { type: Boolean },
enableCircuits: { type: Boolean },
enableProj: { type: Boolean },
enableTodos: { type: Boolean },
enableRegByBot: { type: Boolean },
enableRegMultiChoice: { type: Boolean },
enableDebugOn: { type: Boolean },
enabledRegNeedTelegram: { type: Boolean },
showViewEventi: { type: Boolean },
showViewGroups: { type: Boolean },
showViewCircuits: { type: Boolean },
showViewUsers: { type: Boolean },
showViewBooking: { type: Boolean },
showViewProfile: { type: Boolean },
enablePwa: { type: Boolean },
col_toolbar: { type: String, default: '' },
col_bgfooter: { type: String, default: '' },
show_darkopt: { type: Boolean, default: false },
showButtHome: { type: Boolean, default: false },
showProfile: { type: Boolean, default: false },
showUserMenu: { type: Boolean, default: true },
showiscrittiMenu: { type: Boolean, default: false },
showRegButton: { type: Boolean, default: false },
enableReg: { type: Boolean, default: false },
showNL: { type: Boolean, default: false },
sendNewsletter: { type: Boolean, default: false },
showMsgs: { type: Boolean, default: false },
showNotif: { type: Boolean, default: false },
showCoins: { type: Boolean, default: false },
showRIS: { type: Boolean, default: false },
showMenuCoins: { type: Boolean, default: false },
showNameSurname: { type: Boolean, default: false },
showCompetenze: { type: Boolean, default: false },
showConnected: { type: Boolean, default: false },
bookingEvents: { type: Boolean, default: false },
enableEcommerce: { type: Boolean, default: false },
enableAI: { type: Boolean, default: false },
enableGroups: { type: Boolean, default: false },
enableCircuits: { type: Boolean, default: false },
enableProj: { type: Boolean, default: false },
enableTodos: { type: Boolean, default: false },
enableRegByBot: { type: Boolean, default: false },
enableRegMultiChoice: { type: Boolean, default: false },
enableDebugOn: { type: Boolean, default: false },
enabledRegNeedTelegram: { type: Boolean, default: false },
showViewEventi: { type: Boolean, default: false },
showViewGroups: { type: Boolean, default: false },
showViewCircuits: { type: Boolean, default: false },
showViewUsers: { type: Boolean, default: false },
showViewBooking: { type: Boolean, default: false },
showViewProfile: { type: Boolean, default: false },
showViewCart: { type: Boolean, default: false },
showViewOrders: { type: Boolean, default: false },
enablePwa: { type: Boolean, default: false },
lang: {
type: Number,
default: 0,
},
videoPromo: { type: String },
PDFPromo: { type: String },
videoPromo: { type: String, default: '' },
PDFPromo: { type: String, default: '' },
},
confsite: {
options: { // ConfSite
@@ -149,7 +164,7 @@ const SiteSchema = new Schema({
},
},
policy: {
show: { type: Boolean },
show: { type: Boolean, default: false },
owneremail: { type: String },
siteName: { type: String },
ownerDataName: { type: String },
@@ -160,18 +175,21 @@ const SiteSchema = new Schema({
country: { type: String },
},
contacts: {
facebook: { type: String },
instagram: { type: String },
whatsapp: { type: String },
whatsapp_home: { type: Boolean },
telegram: { type: String },
youtube: { type: String },
email: { type: String },
address: { type: String },
map: { type: String },
info2: { type: String },
cell: { type: String },
facebook: { type: String, default: '' },
instagram: { type: String, default: '' },
whatsapp: { type: String, default: '' },
whatsapp_home: { type: Boolean, default: false },
telegram: { type: String, default: '' },
youtube: { type: String, default: '' },
email: { type: String, default: '' },
address: { type: String, default: '' },
map: { type: String, default: '' },
info2: { type: String, default: '' },
cell: { type: String, default: '' },
},
ecomm: {
enablePreOrders: { type: Boolean, default: false },
}
});
var Site = module.exports = mongoose.model('Site', SiteSchema);
@@ -211,7 +229,6 @@ module.exports.executeQueryTable = async function (idapp, params, userreq) {
}
};
module.exports.findAll = async function () {
@@ -224,7 +241,7 @@ module.exports.findAll = async function () {
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp, active: true };
let myfind = { idapp, active: true };
let rec = await Site.findOne(myfind).lean();
if (rec) {
@@ -235,7 +252,124 @@ module.exports.findAllIdApp = async function (idapp) {
// rec.confsite = {};
return rec;
} else {
myfind = { name: 'local' };
let rec = await Site.findOne(myfind).lean();
if (!rec) {
const mysite = new Site();
mysite.name = 'local';
await mysite.save();
mysite.idapp = idapp;
return mysite;
} else {
return rec;
}
}
return {};
};
module.exports.generateNewSite_IdApp = async function (idapp, params, createpage) {
const { MyPage } = require('../models/mypage');
let ris = null;
try {
if (idapp) {
ris = await Site.find({ idapp: idapp.toString(), host: params.host });
} else {
for (let idapp = 20; idapp <= 100; idapp++) {
ris = await Site.find({ idapp: idapp.toString(), host: params.host });
break;
}
}
if (ris && ris.length === 0) {
const paramSite = _.pick(params, ['name', 'host', 'email']);
let mysite = new Site(paramSite);
mysite.active = true;
mysite.idapp = idapp.toString();
mysite.adminemail = params.email;
const ris = await mysite.save();
if (createpage) {
// 1. Crea Pagina principale HOME - Loggato
let myp = new MyPage({
order: 10,
idapp: mysite.idapp,
path: 'home',
active: true,
title: 'Home',
});
let rispag = await myp.save();
// 2. Crea Pagina principale HOME - Non Loggato
myp = new MyPage({
order: 10,
idapp: mysite.idapp,
path: 'home_logout',
active: true,
title: 'Home NoLoggato',
});
rispag = await myp.save();
}
if (ris)
return mysite.idapp;
else
return '';
}
} catch (e) {
console.error(e);
}
return '';
};
module.exports.createFirstUserAdmin = async function () {
const { User } = require('../models/user');
const telegrambot = require('../telegram/telegrambot');
try {
let arrSite = await Site.find({ idapp: { $exists: true } }).lean();
for (const mysite of arrSite) {
if (mysite.idapp > 0) {
const numusers = await User.countDocuments({ idapp: mysite.idapp });
if (numusers === 0) {
// Non esistono utenti, quindi creo quello di Admin
const utenteadmin = { idapp: '13', username: telegrambot.ADMIN_USER_SERVER };
const newuser = new User(utenteadmin);
newuser._id = new ObjectID();
newuser.idapp = mysite.idapp;
newuser.profile.mygroups = [];
newuser.profile.mycircuits = [];
await newuser.save();
}
}
}
} catch (e) {
console.error('Error ', e);
}
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -78,4 +78,8 @@ SkillSchema.statics.executeQueryTable = function (idapp, params) {
const Skill = mongoose.model('Skill', SkillSchema);
Skill.createIndexes((err) => {
if (err) throw err;
});
module.exports = { Skill };

View File

@@ -75,4 +75,8 @@ StatusSkillSchema.statics.executeQueryTable = function (idapp, params) {
const StatusSkill = mongoose.model('StatusSkill', StatusSkillSchema);
StatusSkill.createIndexes((err) => {
if (err) throw err;
});
module.exports = { StatusSkill };

View File

@@ -18,6 +18,13 @@ const storehouseSchema = new Schema({
},
name: {
type: String,
required: true,
},
username: {
type: String,
},
groupname: {
type: String,
},
description: {
type: String,
@@ -40,6 +47,38 @@ const storehouseSchema = new Schema({
website: {
type: String,
},
email_html_header: {
type: String,
default: '',
},
email_html_footer: {
type: String,
default: '',
},
email_html_makeorder: {
type: String,
default: '',
},
email_html_order_confirmed: {
type: String,
default: '',
},
email_html_order_consegnato: {
type: String,
default: '',
},
email_html_GAS_makeorder: {
type: String,
default: '',
},
email_html_GAS_order_confirmed: {
type: String,
default: '',
},
email_html_GAS_order_consegnato: {
type: String,
default: '',
},
});
var Storehouse = module.exports = mongoose.model('Storehouse', storehouseSchema);
@@ -59,3 +98,6 @@ module.exports.findAllIdApp = async function (idapp) {
return await Storehouse.find(myfind);
};
module.exports.createIndexes((err) => {
if (err) throw err;
});

65
src/server/models/subcatprod.js Executable file
View File

@@ -0,0 +1,65 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const SubCatProdSchema = new Schema({
idapp: {
type: String,
},
idCatProd: {
type: String,
},
name: {
type: String,
},
img: {
type: String,
},
icon: {
type: String,
},
color: {
type: String,
},
});
SubCatProdSchema.statics.getAllCategories = function (callback) {
SubCatProd.find(callback)
}
SubCatProdSchema.statics.getSubCatProdById = function (id, callback) {
SubCatProd.findById(id, callback);
}
SubCatProdSchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
SubCatProdSchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
SubCatProdSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await SubCatProd.find(myfind).sort({ name: 1 });
};
const SubCatProd = mongoose.model('SubCatProd', SubCatProdSchema);
SubCatProd.createIndexes((err) => {
if (err) throw err;
});
module.exports = SubCatProd;

Some files were not shown because too many files have changed in this diff Show More