-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_methods.cjs
More file actions
1206 lines (1016 loc) · 40.1 KB
/
db_methods.cjs
File metadata and controls
1206 lines (1016 loc) · 40.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs');
//const db = require('./db.json');
const jwt = require('jsonwebtoken')
const secret = 'sdjkfh8923yhjdksbfma@#*(&@*!^#&@bhjb2qiuhesdbhjdsfg839ujkdhfjk'
const { MongoClient, ObjectId } = require("mongodb");
const uri =
"mongodb://127.0.0.1:27017";
let dbName = "";
const setServerConfig = (server) => {
dbName = server.db_name;
}
const client = new MongoClient(uri);
//crea nuovo utente e lo mette nel db
const createUser = async (name,surname,pass,email) =>{
try{
const database = client.db(dbName);
const users = database.collection('users');
let userinfo = await users.findOne({'email': email})
if(userinfo == null){
let user = {}
user.name = name
user.surname = surname
user.password = pass
user.email = email
user.isGoogleAccount = false
user.verified = true
//user.verified = false
let result = await users.insertOne(user);
_id = result.insertedId.toString();
//initUserData(_id);
//fakeInit(_id);
return 1; //user settato
}else{
return 0; //user esistente
}
} catch (err){
console.log(err)
return err
}
}
const createGoogleUser = async (payload, fullInfo) =>{
try{
const database = client.db(dbName);
const users = database.collection('users');
let userinfo = await users.findOne({'email': payload.email})
if(userinfo == null){
let user = {}
user.name = payload.given_name;
user.surname = payload.family_name;
user.password = undefined;
user.email = payload.email
user.isGoogleAccount = true
user.verified = true
let x = await users.insertOne(user);
if(fullInfo == true){
return ({id: x.insertedId, name: user.name, email: user.email})
} else return x.insertedId; //user settato
} else {
if(fullInfo == true){
return ({id: userinfo._id, name: userinfo.name, email: userinfo.email})
} else return userinfo._id; //user esistente
}
} catch (err){
return err
}
}
const checkEmail = (len, users, newemail) =>{
for (let i = 0; i<len; i++){
if (users[i].email == newemail){
return 0; //codice 0 = utente esiste già
}
}
return 1; //utente non esiste ancora
}
//torna la lista di utenti
const getUser = async (emailToCheck) => {
try{
const database = client.db(dbName);
const users = database.collection('users');
const user = await users.findOne({"email": emailToCheck});
return user;
}catch (err){
return err
}
}
const verifyEmail = async (email) => {
try {
const database = client.db(dbName);
const users = database.collection('users');
const user = await users.findOne({ email: email });
if (user == null) return 0
if (user.verified == true){
return 2
}
await users.updateOne({ email: email }, { $set: { verified: true } });
return 1
} catch (err) {
console.error(err);
return 0
}
};
/* const getUserInfo = (identificatore) =>{ //identificatore: id o email, info: informazione da recuperare;
const len = db.len;
const users = db.users;
if (typeof identificatore == "number") return users[i];
for (let i = 0; i<len; i++){
if (users[i].identificatore == emailToCheck){
return users[i]; //codice 0 = utente esiste già
}
}
return undefined;
} */
const verifyToken = (req, res, next) =>{
const token = req.cookies['auth-token'];
if(!token) return res.status(401).redirect('/casper/');
try{
const verified = jwt.verify(token, secret);
req.user = verified;
next();
}catch (err){
res.status(400).redirect('/casper/')
}
}
const isLogged = (req) =>{
const token = req.cookies['auth-token'];
if(!token) return false;
else return true
}
const userInfo = async (req) =>{ //ritorna tutte le informazioni dell'utente
try{
const database = client.db(dbName);
const users = database.collection('users');
const token = jwt.decode(req.cookies['auth-token']);
const user = await users.findOne({"_id": new ObjectId(`${token.id}`)});
return user;
}catch (err){
return err
}
}
const getUsersId = async () => {
try {
const database = client.db(dbName);
const collection = database.collection('automations');
// Trova tutti i documenti e ottieni solo i user_id distinti
const users = await collection.distinct("user_id");
return users.map(user_id => ({ id: user_id }));
} catch (error) {
console.error('Error getting active users:', error);
return [];
}
};
const getProblems = async (userId) => {
try {
const database = client.db(dbName);
const conflicts = database.collection('problems');
const userConflicts = await conflicts.findOne({ 'user_id': userId });
if (!userConflicts) return []; // Se non ci sono conflitti, restituisci un array vuoto
return userConflicts['problems'];
} catch (err) {
console.log('error in db_methonds - getProblems');
console.log(err);
return err;
}
};
const removeProblems = async (userId) => {
try {
const database = client.db(dbName);
const problems = database.collection('problems');
const goals = database.collection('goals');
const improvementSolutions = database.collection('improvement_solutions');
// Elimina il documento con il campo user_id uguale a userId
const result = await problems.deleteOne({ user_id: userId });
const goalsResult = await goals.deleteOne({ user_id: userId });
const improvementSolutionsResult = await improvementSolutions.deleteOne({ user_id: userId });
console.log("User ID:", userId);
console.log(`Deleted ${improvementSolutionsResult.deletedCount} document(s) from improvement solutions collection.`);
return { problems: result, goals: goalsResult, improvementSolutions: improvementSolutionsResult };
} catch (err) {
console.log('error in db_methods - removeProblems');
console.log(err);
return err;
}
};
const getAutomationsStates = async (userId) => {
try {
const database = client.db(dbName);
const automations = database.collection('rules_state');
const userAutomations = await automations.findOne({ 'user_id': userId });
if (!userAutomations) return []; // Se non ci sono automazioni, restituisci un array vuoto
return userAutomations['automation_data'];
} catch (err) {
console.log('error in db_methods - getAutomationsStates');
console.log(err);
return err;
}
};
const getProblemsGoals = async (userId) => {
try {
const database = client.db(dbName);
const conflictsGoal = database.collection('goals');
const userConflictsGoal = await conflictsGoal.findOne({ 'user_id': userId });
if (!userConflictsGoal) return []; // Se non ci sono conflitti, restituisci un array vuoto
// Combine all goal types into a single array
let allGoals = [];
// Iterate through all possible goal types
const goalTypes = ["security", "well-being", "energy", "health"];
for (const goalType of goalTypes) {
if (userConflictsGoal[goalType] && Array.isArray(userConflictsGoal[goalType])) {
allGoals = allGoals.concat(userConflictsGoal[goalType]);
}
}
return allGoals;
} catch (err) {
console.log('error in db_methonds - getProblemsGoal');
console.log(err);
return [];
}
};
const getAutomations=async (userId) => {
try {
const database = client.db(dbName);
const automations = database.collection('automations');
const userAutomations = await automations.findOne({ 'user_id': userId }); // Sistemare nel caso non ci siano automazioni
if (!userAutomations) return []; // Se non ci sono automazioni, restituisci null o un array vuoto
return userAutomations['automation_data'];
} catch (err) {
console.log('error in getAutomationsByUserId');
console.log(err);
return []
//return err;
}
};
const saveConfiguration = async (userId, data, auth) => {
try {
const database = client.db(dbName);
const config = database.collection('config');
if (config.findOne({ 'user_id': userId })) {
await config.updateOne({ 'user_id': userId }, {$set: { 'config': data, 'auth': auth }}, { upsert: true });
}else{
await config.insertOne({ 'user_id': userId, 'config': data, 'auth': auth });
}
} catch (err) {
console.log('error in saveConfiguration db_methods');
console.log(err);
return err;
}
}
const getConfiguration = async (userId) => {
try {
const database = client.db(dbName);
const config = database.collection('config');
let conf = await config.findOne({ 'user_id': userId })
if (conf) {
return conf
}else{
return false
}
} catch (err) {
console.log('error in getConfiguration db_methods');
console.log(err);
return err;
}
}
const saveSelectedConfiguration = async (userId, data) => {
try {
const database = client.db(dbName);
const config = database.collection('config');
const query = {
user_id: userId,
'config': {
$elemMatch: {
'e': { $in: data }
}
}
};
// Aggiungi proiezione per filtrare solo gli elementi corrispondenti
const projection = {
'selected': {
$filter: {
input: '$config',
as: 'item',
cond: { $in: ['$$item.e', data] }
}
}
};
const userConfig = await config.findOne(query, { projection });
await config.updateOne({ 'user_id': userId }, { $set: { 'selected': userConfig.selected } }, { upsert: true });
} catch (err) {
console.log('error in saveSelectedConfiguration db_methods');
console.log(err);
return err;
}
}
const saveAutomations = async (userId, automationsData) => {
//saves all automations to DB
try {
const database = client.db(dbName);
const automations = database.collection('automations');
// Aggiorna o inserisce le automazioni per l'utente specificato
await automations.updateOne(
{ 'user_id': userId },
{
$set: {
'user_id': userId,
'automation_data': automationsData
}
},
{ upsert: true }
);
return true;
} catch (err) {
console.log('error in saveAutomations');
console.log(err);
return false;
}
};
const saveRulesStates= async (userId, automationsData) => {
//saves all automations to DB
try {
const database = client.db(dbName);
const automations_state = database.collection('rules_state');
// Aggiorna o inserisce le automazioni per l'utente specificato
await automations_state.updateOne(
{ 'user_id': userId },
{
$set: {
'user_id': userId,
'automation_data': automationsData
}
},
{ upsert: true }
);
return true;
} catch (err) {
console.log('error in saveRulesStates');
console.log(err);
return false;
}
};
const saveAutomation = async (userId, automationId, config) => {
//saves a single automation to DB
try {
const database = client.db(dbName);
const automations = database.collection('automations');
const userAutomations = await automations.findOne({ 'user_id': userId });
if (userAutomations) {
const automationIndex = userAutomations.automation_data.findIndex(
auto => auto.id === automationId
);
const automationData = {
id: automationId,
state: 'on',
config: config
};
if (automationIndex !== -1) {
userAutomations.automation_data[automationIndex] = automationData;
} else {
userAutomations.automation_data.push(automationData);
}
await automations.updateOne(
{ 'user_id': userId },
{ $set: { 'automation_data': userAutomations.automation_data } }
);
}else{
await automations.insertOne({
'user_id': userId,
'automation_data': [{ id: automationId, name: config['alias'], config: config }]
});
}
return true;
} catch (err) {
console.log('Errore in saveHAAutomation:', err);
return false;
}
};
const deleteRule = async (userId, ruleId, haDeleteFunc) => {
try {
const database = client.db(dbName);
const automations = database.collection('automations');
const problems = database.collection('problems');
const goals = database.collection('goals');
const rulesState = database.collection('rules_state');
// elimina l'automazione dal database
const userAutomations = await automations.findOne({ 'user_id': userId });
if (!userAutomations) {
return false;
}
const newAutomations = userAutomations.automation_data.filter(
auto => {
const match = auto.id.toString() !== ruleId.toString();
return match;
}
);
await automations.updateOne(
{ 'user_id': userId },
{ $set: { 'automation_data': newAutomations } }
);
// Elimina l'automazione dalla collezione rules_state
const userRulesState = await rulesState.findOne({ 'user_id': userId });
if (userRulesState && userRulesState.automation_data) {
const filteredRulesState = userRulesState.automation_data.filter(
rule => rule.id.toString() !== ruleId.toString()
);
await rulesState.updateOne(
{ 'user_id': userId },
{
$set: {
'automation_data': filteredRulesState,
'last_update': new Date()
}
}
);
}
// Elimina i problemi che coinvolgono questa automazione
const userProblems = await problems.findOne({ 'user_id': userId });
if (userProblems && userProblems.problems) {
userProblems.problems.forEach((problem, index) => {
if (problem.rules) {
}
});
// Filtra i problemi che NON coinvolgono l'automazione eliminata
const filteredProblems = userProblems.problems.filter(problem => {
if (!problem.rules || !Array.isArray(problem.rules)) {
return true;
}
// Controlla se il problema coinvolge l'automazione eliminata
const involvesDeletedRule = problem.rules.some(rule => {
const ruleIdStr = rule.id ? rule.id.toString() : '';
const targetIdStr = ruleId.toString();
const matches = ruleIdStr === targetIdStr;
return matches;
});
if (involvesDeletedRule) {
return false; // Esclude questo problema
}
return true; // Mantiene questo problema
});
// Aggiorna la collezione problems
const updateResult = await problems.updateOne(
{ 'user_id': userId },
{
$set: {
'problems': filteredProblems,
'last_update': new Date()
}
}
);
}
// Elimina i goals che coinvolgono questa automazione
const userGoals = await goals.findOne({ 'user_id': userId });
if (userGoals) {
let goalsUpdated = false;
const updatedGoals = {};
// Itera attraverso ogni tipo di goal (energy, health, security, etc.)
for (const [goalType, goalArray] of Object.entries(userGoals)) {
if (goalType === '_id' || goalType === 'user_id' || goalType === 'created' || goalType === 'last_update') {
continue;
}
if (Array.isArray(goalArray)) {
// Filtra i goals che NON coinvolgono l'automazione eliminata
const filteredGoals = goalArray.filter(goal => {
if (!goal.rules || !Array.isArray(goal.rules)) {
return true;
}
// Controlla se il goal coinvolge l'automazione eliminata
const involvesDeletedRule = goal.rules.some(rule => {
const ruleIdStr = rule.id ? rule.id.toString() : '';
const targetIdStr = ruleId.toString();
return ruleIdStr === targetIdStr;
});
if (involvesDeletedRule) {
goalsUpdated = true;
return false; // Esclude questo goal
}
return true; // Mantiene questo goal
});
// Solo aggiungi il goalType se l'array non è vuoto
if (filteredGoals.length > 0) {
updatedGoals[goalType] = filteredGoals;
} else {
goalsUpdated = true; // Segna che è stato aggiornato perché abbiamo rimosso un array vuoto
}
} else {
updatedGoals[goalType] = goalArray;
}
}
// Aggiorna la collezione goals solo se ci sono stati cambiamenti
if (goalsUpdated) {
// Usa $unset per rimuovere completamente i campi che non sono in updatedGoals
const fieldsToUnset = {};
for (const [goalType, goalArray] of Object.entries(userGoals)) {
if (goalType !== '_id' && goalType !== 'user_id' && goalType !== 'created' && goalType !== 'last_update') {
if (Array.isArray(goalArray) && !updatedGoals.hasOwnProperty(goalType)) {
fieldsToUnset[goalType] = "";
}
}
}
const updateOperation = {
$set: {
...updatedGoals,
'last_update': new Date()
}
};
// Aggiungi $unset solo se ci sono campi da rimuovere
if (Object.keys(fieldsToUnset).length > 0) {
updateOperation.$unset = fieldsToUnset;
}
await goals.updateOne(
{ 'user_id': userId },
updateOperation
);
}
}
// elimina l'automazione da Home Assistant
const config = await getConfiguration(userId);
if (!config || !config.auth) {
return false;
}
const haResponse = await haDeleteFunc(config.auth.url, config.auth.token, ruleId);
if (!haResponse) {
return false;
}
return true;
} catch (err) {
console.log('Errore in deleteRule:', err);
return false;
}
}
async function updateAutomationState(userId, entity_id, is_running, entity_id_device, state_device) {
try {
const database = client.db(dbName);
const rulesState = database.collection('rules_state');
// Trova il documento dell'utente
const userRulesState = await rulesState.findOne({ 'user_id': userId });
if (!userRulesState || !userRulesState.automation_data) {
return false;
}
// Trova l'indice dell'automazione con l'entity_id specificato
const automationIndex = userRulesState.automation_data.findIndex(
automation => automation.entity_id === entity_id
);
if (automationIndex === -1) {
return false;
}
// Aggiorna l'automazione specifica usando l'approccio array completo
const updatedAutomationData = [...userRulesState.automation_data];
updatedAutomationData[automationIndex] = {
...updatedAutomationData[automationIndex],
is_running: is_running,
entity_id_device: entity_id_device,
state_device: state_device,
time: new Date().toISOString()
};
const updateResult = await rulesState.updateOne(
{ 'user_id': userId },
{ $set: { 'automation_data': updatedAutomationData } }
);
// Verifica l'aggiornamento
const verifyUpdate = await rulesState.findOne({ 'user_id': userId });
return true;
} catch (error) {
console.error('Errore in updateAutomationState:', error);
return false;
}
}
async function closeDatabaseConnection() {
if (client && client.topology && client.topology.isConnected()) {
await client.close();
console.log("Connessione a MongoDB chiusa.");
}
}
const toggleAutomation = async (userId, automationId, state) => {
try {
const database = client.db(dbName);
const automations = database.collection('automations');
const userAutomations = await automations.findOne({ 'user_id': userId });
if (!userAutomations) return false;
const automationIndex = userAutomations.automation_data.findIndex(
auto => auto.id.toString() === automationId.toString()
);
if (automationIndex === -1) return false; // Automazione non trovata
userAutomations.automation_data[automationIndex].state = state;
await automations.updateOne(
{ 'user_id': userId },
{ $set: { 'automation_data': userAutomations.automation_data } }
);
await updateAllProblemsState(userId);
return true;
} catch (err) {
console.log('Errore in toggleAutomation:', err);
return false;
}
}
const ignoreProblem = async (userId, problemId) => {
try {
const database = client.db(dbName);
const problems = database.collection('problems');
const userProblems = await problems.findOne({ 'user_id': userId });
if (!userProblems) return false;
// Trova il problema e imposta ignored a true
const updatedProblems = userProblems.problems.map(problem => {
if (problem.id.toString() === problemId.toString()) {
return { ...problem, ignore: true };
}
return problem;
});
// Aggiorna il documento con i problemi modificati
await problems.updateOne(
{ 'user_id': userId },
{ $set: { 'problems': updatedProblems } }
);
return true;
} catch (err) {
console.log('Errore in ignoreProblem:', err);
return false;
}
};
const ignoreGoalProblem = async (userId, goalProblemId) => {
try {
const database = client.db(dbName);
const goalsCollection = database.collection('goals');
// Recupera il documento dell'utente
const userGoals = await goalsCollection.findOne({ 'user_id': userId });
if (!userGoals) {
return false;
}
let updated = false;
// Itera attraverso le categorie di goal (energy, health, etc.)
const updatedGoals = {};
for (const [goalType, goalArray] of Object.entries(userGoals)) {
if (Array.isArray(goalArray)) {
// Cerca il problema con l'ID specificato
const updatedGoalArray = goalArray.map(goal => {
if (goal.id === goalProblemId) {
updated = true;
return { ...goal, ignore: true }; // Imposta ignore a true
}
return goal;
});
updatedGoals[goalType] = updatedGoalArray;
} else {
updatedGoals[goalType] = goalArray;
}
}
if (!updated) {
return false; // Nessun problema trovato
}
// Aggiorna il documento nel database
await goalsCollection.updateOne(
{ 'user_id': userId },
{ $set: { ...updatedGoals, last_update: new Date() } }
);
return true;
} catch (err) {
console.log('Errore in ignoreGoalProblem:', err);
return false;
}
};
const ignoreSuggestions = async (userId, suggestionId) => {
try {
const database = client.db(dbName);
const suggestions = database.collection('improvement_solutions');
const userSuggestions = await suggestions.findOne({ 'user_id': userId });
if (!userSuggestions || !userSuggestions.solutions || !userSuggestions.solutions.recommendations) return false;
let updated = false;
let goalOfIgnoredSuggestion = null;
let ignoredSuggestion = null;
// Trova e rimuovi il suggerimento dalla collezione
for (let goalKey of Object.keys(userSuggestions.solutions.recommendations)) {
const recs = userSuggestions.solutions.recommendations[goalKey];
if (Array.isArray(recs)) {
const suggestionIndex = recs.findIndex(rec => rec.unique_id === suggestionId);
if (suggestionIndex !== -1) {
ignoredSuggestion = recs[suggestionIndex];
goalOfIgnoredSuggestion = goalKey;
// Rimuovi il suggerimento dall'array
recs.splice(suggestionIndex, 1);
updated = true;
goalKey = goalKey.toLowerCase();
// Salva il suggerimento ignorato nella collezione ignored_suggestions
await saveIgnoredSuggestion(userId, goalKey, ignoredSuggestion);
break;
}
}
}
if (!updated) return false;
// Aggiorna il documento nel database
await suggestions.updateOne(
{ 'user_id': userId },
{ $set: { 'solutions': userSuggestions.solutions } }
);
// Genera un nuovo suggerimento per lo stesso goal
if (goalOfIgnoredSuggestion) {
try {
const pythonServerUrl = 'http://localhost:8080';
//console.log(`Tentativo di chiamata a: ${pythonServerUrl}/generate_replacement_suggestion`);
const response = await fetch(`${pythonServerUrl}/generate_replacement_suggestion`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: userId,
goal: goalOfIgnoredSuggestion
})
});
console.log(`Response status: ${response.status}`);
if (response.ok) {
const result = await response.json();
console.log('Nuovo suggerimento generato con successo');
} else {
const errorText = await response.text();
console.log(`Errore nella generazione del nuovo suggerimento. Status: ${response.status}, Message: ${errorText}`);
}
} catch (error) {
console.log('Errore nella chiamata per generare nuovo suggerimento:', error.message);
}
}
return true;
} catch (err) {
console.log('Errore in ignoreSuggestions:', err);
return false;
}
};
const deleteSuggestion = async (userId, suggestionId) => {
try {
const database = client.db(dbName);
const suggestions = database.collection('improvement_solutions');
// Trova il documento dell'utente
const userSuggestions = await suggestions.findOne({ 'user_id': userId });
if (!userSuggestions || !userSuggestions.solutions || !userSuggestions.solutions.recommendations) {
return false; // Nessun suggerimento trovato
}
let updated = false;
let goalOfIgnoredSuggestion = null;
// Itera attraverso le categorie di suggerimenti (energia, sicurezza, ecc.)
for (const [goalKey, recs] of Object.entries(userSuggestions.solutions.recommendations)) {
if (Array.isArray(recs)) {
goalOfIgnoredSuggestion = goalKey;
// Trova l'indice del suggerimento da eliminare
const suggestionIndex = recs.findIndex(rec => rec.unique_id === suggestionId);
if (suggestionIndex !== -1) {
// Rimuovi il suggerimento dall'array
recs.splice(suggestionIndex, 1);
updated = true;
break;
}
}
}
if (!updated) {
return false; // Suggerimento non trovato
}
// Aggiorna il documento nel database
await suggestions.updateOne(
{ 'user_id': userId },
{ $set: { 'solutions': userSuggestions.solutions } }
);
//Genera un nuovo suggerimento per lo stesso goal
if (goalOfIgnoredSuggestion) {
try {
const pythonServerUrl = 'http://localhost:8080';
//console.log(`Tentativo di chiamata a: ${pythonServerUrl}/generate_replacement_suggestion`);
const response = await fetch(`${pythonServerUrl}/generate_replacement_suggestion`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: userId,
goal: goalOfIgnoredSuggestion
})
});
console.log(`Response status: ${response.status}`);
if (response.ok) {
const result = await response.json();
console.log('Nuovo suggerimento generato con successo');
} else {
const errorText = await response.text();
console.log(`Errore nella generazione del nuovo suggerimento. Status: ${response.status}, Message: ${errorText}`);
}
} catch (error) {
console.log('Errore nella chiamata per generare nuovo suggerimento:', error.message);
}
}
return true; // Suggerimento eliminato con successo
} catch (err) {
console.error('Errore in deleteSuggestion:', err);
return false;
}
};
const saveIgnoredSuggestion = async (userId, goal, suggestion) => {
try {
const database = client.db(dbName);
const ignored = database.collection('ignored_suggestions');
// Cerca se già esiste
const userDoc = await ignored.findOne({ user_id: userId });
let ignoredArr = [];
if (userDoc && userDoc.ignored && userDoc.ignored[goal]) {
ignoredArr = userDoc.ignored[goal];
// Evita duplicati
if (ignoredArr.some(s => s.suggestion.unique_id === suggestion.unique_id)) {
return true;
}
}
// Se ci sono già 3 suggerimenti, rimuovi il più vecchio
if (ignoredArr.length >= 3) {
// Ordina per data crescente e rimuovi il primo (il più vecchio)
ignoredArr.sort((a, b) => new Date(a.ignored_at) - new Date(b.ignored_at));
ignoredArr.shift();
}
// Aggiungi il nuovo suggerimento
ignoredArr.push({
suggestion: suggestion,
ignored_at: new Date()
});
// Aggiorna il documento
await ignored.updateOne(
{ user_id: userId },
{ $set: { [`ignored.${goal}`]: ignoredArr } },
{ upsert: true }
);
return true;
} catch (err) {
console.log('Errore in saveIgnoredSuggestion:', err);
return false;
}
};
const changeStateProblem = async (userId, problemId, newState = null) => {
try {
const database = client.db(dbName);
const problems = database.collection('problems');
const automations = database.collection('automations');
const userProblems = await problems.findOne({ 'user_id': userId });
const userAutomations = await automations.findOne({ 'user_id': userId });
if (!userProblems || !userAutomations) {
return false;
}
// Trova il problema specifico
const targetProblem = userProblems.problems.find(problem =>
problem.id.toString() === problemId.toString()
);
if (!targetProblem || !targetProblem.rules) {
return false;
}