-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
1449 lines (1328 loc) · 40.3 KB
/
db.js
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 mysql = require("mysql2");
const axios = require("axios");
const argon2 = require("argon2");
const cron = require("node-cron");
require("dotenv").config();
const host = process.env.HOST;
const usr = process.env.USR;
const password = process.env.PASSWORD;
const database = process.env.DATABASE;
const pool = createPool();
const maxCoinBudget = 2000;
let pilotsNicks = {};
let pilotsGlobalInfo = {};
let allRoundResults = [];
let pilotsAllRoundsResults = {};
let lastRoundNum;
async function cachePilotsGlobalInfo() {
let pilots = await getPilots();
pilots.forEach((pilot) => {
if (pilot.permanentNumber == 33) pilot.permanentNumber = 1;
if (pilot.permanentNumber == 15) pilot.permanentNumber = 40;
pilotsGlobalInfo[pilot.permanentNumber] = pilot;
});
}
function createPool() {
let pool = mysql.createPool({
host: host,
user: usr,
password: password,
database: database,
waitForConnections: true,
connectionLimit: 20,
});
return pool;
}
const inizializeDatabase = async () => {
//await newSeasonCleanup();
await inizializePilotsTable();
let w = await insertPilots();
await createCoinsTable();
await setLastRoundNumber();
await getPilotsNicks();
await updateAllRoundsResultsCache();
await updatePilotsAllRoundsResultsCache();
await cachePilotsGlobalInfo();
await createUsersTable();
await createTeamTable();
await retrieveAllRoundResults();
await pilotsValueUpdate();
//await insertTestStandings();
//insertTestUsers();
//testing
//console.log(await getPilotsScoreStandings());
};
async function pilotsScoreCleanup() {
return new Promise((resolve, reject) => {
pool.execute(
`DROP TABLE IF EXISTS pilots`,
(err) => {
if (err) {
console.error("Errore durante la cancellazione della tabella:", err);
reject(err);
} else {
resolve(true);
}
}
);
});
}
async function inizializePilotsTable() {
let waitCleanup = await pilotsScoreCleanup();
return new Promise((resolve, reject) => {
pool.execute(
`CREATE TABLE IF NOT EXISTS pilots (
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
surname VARCHAR(255) NOT NULL,
score VARCHAR(1000)
)
`,
(err) => {
if (err) {
console.error("Errore durante la creazione della tabella:", err);
reject(err);
} else {
resolve(true);
}
}
);
});
}
function getPilots() {
const url = "http://ergast.com/api/f1/2023/drivers.json";
// Funzione per ottenere i dati dei piloti dalla Ergast API
async function getDriversData() {
try {
const response = await axios.get(url);
const driversData = response.data.MRData.DriverTable.Drivers;
return driversData;
} catch (error) {
console.error("Errore durante la richiesta:", error.message);
}
}
return getDriversData();
}
async function insertPilots() {
let pilots = await getPilots();
//insert pilots json to db
return new Promise((resolve, reject) => {
for (let i = 0; i < pilots.length; i++) {
if (pilots[i].permanentNumber == 33) pilots[i].permanentNumber = 1;
if (pilots[i].permanentNumber == 15) pilots[i].permanentNumber = 40;
pool.execute(
`
INSERT INTO pilots (id, name, surname)
VALUES (?,?,?)
ON DUPLICATE KEY UPDATE id = VALUES(id), name = VALUES(name), surname = VALUES(surname)
`,
[pilots[i].permanentNumber, pilots[i].givenName, pilots[i].familyName],
(err) => {
if (err) {
console.error("Errore durante l'inserimento dei dati:", err);
reject(err);
} else {
//console.log("Dati inseriti con successo!");
}
}
);
}
resolve(true);
});
}
//crea tabella autenticazione utenti
function createUsersTable() {
pool.execute(
`
CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
role VARCHAR(255) NOT NULL,
UNIQUE (username))
`,
(err) => {
if (err) {
console.error("Errore durante la creazione della tabella:", err);
} else {
//console.log("Tabella degli utenti creata con successo!");
insertAdmin();
insertTestAccount();
}
}
);
function insertTestAccount() {
//insert if not exist test user
insertUser("test", "test");
}
function insertAdmin() {
//insert if not exist admin user
argon2.hash("admin").then((hash) => {
const criptedPassword = hash;
pool.execute(
`
INSERT INTO users (username, password, role)
VALUES (?,?,?)
ON DUPLICATE KEY UPDATE username = VALUES(username), password = VALUES(password), role = VALUES(role) `,
["admin", criptedPassword, "admin"],
(err) => {
if (err) {
console.error("Errore durante l'inserimento dei dati:", err);
} else {
//console.log("Dati inseriti con successo!");
}
}
);
});
}
}
async function insertUser(username, password) { //ritorna false se già presente nel db, true se inserito con successo
return new Promise((resolve, reject) => {
argon2.hash(password).then((hash) => {
const criptedPassword = hash;
pool.execute(
`
INSERT INTO users (username, password, role)
VALUES (?,?,?)
`,
[username, criptedPassword, "user"],
(err) => {
if (err) {
console.error("Errore durante l'inserimento dei dati:", err);
resolve(false);
} else {
//console.log("Dati inseriti con successo!");
resolve(true);
}
}
);
});
});
}
async function queryUser(username) {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT * FROM users WHERE username = ?
`,
[username],
(err, result) => {
if (err) {
console.error("Errore durante la ricerca dell'utente:", err);
reject(err);
} else {
if (result.length > 0) {
resolve(result[0]);
} else {
console.log("Utente non trovato");
resolve(null);
}
}
}
);
});
}
function retrieveLastRoundResults() {
return allRoundResults[lastRoundNum - 1];
}
async function verifyCredentials(username, password) {
let res = await queryUser(username);
if (res == null) {
return false;
}
let isCorrect = await verifyHash(password, res.password);
if (isCorrect) {
return true;
}
return false;
}
async function verifyHash(password, hash) {
return await argon2.verify(hash, password).then((esito) => {
if (esito) {
console.log("Password corretta");
return true;
} else {
console.log("Password errata");
return false;
}
});
}
function verifyAdminAccess(username) {
pool.execute(
`
SELECT * FROM users WHERE username = ?
`,
[username],
(err, result) => {
if (err) {
console.error("Errore durante la ricerca dell'amministratore:", err);
} else {
if (result.length > 0) {
if (result[0].role == "admin") {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
);
}
//funzione che crea il database dei coins di costo per ogni pilota
async function createCoinsTable() {
return new Promise((resolve, reject) => {
pool.execute(
`
CREATE TABLE IF NOT EXISTS coins (
driverId INT PRIMARY KEY,
coins INT NOT NULL,
UNIQUE (driverId))
`,
(err) => {
if (err) {
console.error("Errore durante la creazione della tabella:", err);
reject(err);
} else {
console.log("Tabella dei coins creata con successo!");
resolve(true);
}
}
);
});
}
/*async function insertCoins() {
let pilot_values = {
"1": 1500,
"2": 50,
"3": 100,
"4": 500,
"10": 80,
"11": 1200,
"14": 800,
"16": 1000,
"18": 200,
"20": 60,
"21": 10,
"22": 150,
"23": 300,
"24": 100,
"27": 100,
"31": 150,
"44": 1000,
"55": 900,
"63": 800,
"77": 80,
"81": 450,
"40": 10,
};
let wait = await createCoinsTable();
if (wait) {
for (let i = 0; i < Object.keys(pilot_values).length; i++) {
pool.execute(
`
INSERT INTO coins (driverId, coins)
VALUES (?,?)
ON DUPLICATE KEY UPDATE driverId = VALUES(driverId), coins = VALUES(coins)
`,
[Object.keys(pilot_values)[i], Object.values(pilot_values)[i]],
(err) => {
if (err) {
console.error("Errore durante l'inserimento dei dati:", err);
} else {
//console.log("Punti inseriti con successo!");
}
}
);
}
}
}*/
async function updatePilotCoins(newScore) { //dove newScore è un oggetto con chiave l'id del pilota e valore il punteggio da aggiungere
return new Promise((resolve, reject) => {
for (let i = 0; i < Object.keys(newScore).length; i++) {
pool.execute(
`
UPDATE coins SET coins = ? WHERE driverId = ?
`,
[Object.values(newScore)[i], Object.keys(newScore)[i]],
(err) => {
if (err) {
console.error("Errore durante l'aggiornamento dei dati:", err);
reject(err);
} else {
//console.log("Punti aggiornati con successo!");
}
}
);
}
resolve(true);
});
}
async function createTeamTable() {
return new Promise((resolve, reject) => {
pool.execute(
`
CREATE TABLE IF NOT EXISTS teams (
teamId INT PRIMARY KEY,
teamName VARCHAR(50) NOT NULL,
idPilots VARCHAR(50) NOT NULL,
score FLOAT NOT NULL,
UNIQUE (teamId))
`,
(err) => {
if (err) {
console.error("Errore durante la creazione della tabella:", err);
reject(err);
} else {
//console.log("Tabella dei team creata con successo!");
resolve(true);
}
}
);
});
}
async function insertTeam(userId, teamName, pilots, score) {
return new Promise((resolve, reject) => {
pool.execute(
`
INSERT INTO teams (teamId, teamName, idPilots, score)
VALUES (?,?,?,?)
ON DUPLICATE KEY UPDATE teamId = VALUES(teamId), teamName = VALUES(teamName), idPilots = VALUES(idPilots), score = VALUES(score)
`,
[userId, teamName, pilots, score],
(err) => {
if (err) {
console.error("Errore durante l'inserimento del team:", err);
reject(err);
} else {
//console.log("Team inserito con successo!");
resolve(true);
}
}
);
});
}
async function getTeam(userId) {
console.log("Ricerca del team...", userId)
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT * FROM teams WHERE teamId = ?
`,
[userId],
(err, result) => {
if (err) {
console.error("Errore durante la ricerca del team:", err);
reject(err);
} else {
if (result.length > 0) {
//console.log("Team trovato con successo!");
resolve(result[0]);
} else {
console.log("Team non presente nel database!");
resolve(false);
}
}
}
);
});
}
async function getTeams() {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT * FROM teams ORDER BY score DESC
`,
(err, result) => {
if (err) {
console.error("Errore durante la ricerca dei team:", err);
reject(err);
} else {
if (result.length > 0) {
//console.log("Team trovati con successo!");
resolve(result);
} else {
console.log("Team non presenti nel database!");
resolve(false);
}
}
}
);
});
}
function calculateBonus(lastRoundResult) {
let positionGainedBonus = calculatePositionGainedBonus(lastRoundResult);
let fastestLapBonus = calculateFastestLapBonus(lastRoundResult);
let bonus = {};
for (let i = 0; i < Object.keys(positionGainedBonus).length; i++) {
let driverId = Object.keys(positionGainedBonus)[i];
bonus[driverId] = positionGainedBonus[driverId] + fastestLapBonus[driverId];
}
return bonus;
}
function calculatePositionGainedBonus(lastRoundResult) { //ritorna un oggetto con chiave l'id del pilota e valore il punteggio da aggiungere
let positionGainedBonus = {};
let length = lastRoundResult.MRData.RaceTable.Races[0].Results.length;
let results = lastRoundResult.MRData.RaceTable.Races[0].Results;
for (let i = 0; i < length; i++) {
let driverId = results[i].number;
let positionGained = parseInt(results[i].grid) - parseInt(results[i].position);
if (positionGained > 0) {
positionGainedBonus[driverId] = positionGained * 2;
}
else if (positionGained <= 0) {
positionGainedBonus[driverId] = positionGained;
}
}
return positionGainedBonus;
}
function calculateFastestLapBonus(lastRoundResult) { //ritorna un oggetto con chiave l'id del pilota e valore il punteggio da aggiungere
let fastestLapBonus = {};
let length = lastRoundResult.MRData.RaceTable.Races[0].Results.length;
let results = lastRoundResult.MRData.RaceTable.Races[0].Results;
for (let i = 0; i < length; i++) {
let driverId = results[i].number;
let fastestLapRank = 0;
try {
fastestLapRank = results[i].FastestLap.rank;
} catch (err) { }
if (fastestLapRank == 1) {
fastestLapBonus[driverId] = 5; //punteggio da rivedere
}
else {
fastestLapBonus[driverId] = 0;
}
}
return fastestLapBonus;
}
async function getRoundResult(roundNumber) {
let RoundResult = await axios.get('http://ergast.com/api/f1/current/' + roundNumber + '/results.json');
return RoundResult.data;
}
function calculateRacePointsScore(lastRoundResult) {
let finalPositionScore = {};
let results = lastRoundResult.MRData.RaceTable.Races[0].Results;
for (let i = 0; i < results.length; i++) {
let driverId = results[i].number;
let points = results[i].points;
finalPositionScore[driverId] = points;
}
return finalPositionScore;
}
async function updateScore(lastRoundResult) {
let lastRaceScore = calculateRacePointsScore(lastRoundResult);
let bonus = calculateBonus(lastRoundResult);
await updatePilotsScore(lastRaceScore, lastRoundResult);
let teamsId = await getTeamsId();
for (let i = 0; i < teamsId.length; i++) {
let teamId = teamsId[i].teamId;
let team = await getTeam(teamId);
let idPilots = team.idPilots.split(",");
let score = parseInt(team.score);
for (let j = 0; j < idPilots.length; j++) {
let pilotId = idPilots[j];
if (typeof (lastRaceScore[pilotId]) != "undefined") {
score += parseInt(lastRaceScore[pilotId]) + parseInt(bonus[pilotId]);
}
}
pool.execute(
`
UPDATE teams SET score = ?
WHERE teamId = ?
`,
[score, teamId],
(err) => {
if (err) {
console.error("Errore durante l'aggiornamento del punteggio:", err);
} else {
//console.log("Punteggio aggiornato con successo!");
}
}
);
}
}
async function updatePilotsScore(lastRaceScore, lastRoundResult) {
let positionGainedBonus = calculatePositionGainedBonus(lastRoundResult);
let fastestLapBonus = calculateFastestLapBonus(lastRoundResult);
return new Promise(async (resolve, reject) => {
let pilotsId = await getPilotsId();
for (let i = 0; i < pilotsId.length; i++) {
let pilotId = pilotsId[i].id;
let lastPilotScore = await getPilotScore(pilotId);
let pilotRoundScore;
if (typeof (lastRaceScore[pilotId]) != "undefined") {
pilotRoundScore = lastRaceScore[pilotId] + "," + positionGainedBonus[pilotId] + "," + fastestLapBonus[pilotId] + ";";
}
else {
pilotRoundScore = "0,0,0;";
}
if (lastPilotScore != null) {
//console.log(lastPilotScore);
pilotRoundScore = lastPilotScore + pilotRoundScore;
}
pool.execute(
`
UPDATE pilots SET score = ?
WHERE id = ?
`,
[pilotRoundScore, pilotId],
(err) => {
if (err) {
console.error("Errore durante l'aggiornamento del punteggio:", err);
reject(err);
}
else {
//console.log("Punteggio aggiornato con successo!");
}
});
}
resolve(true);
});
}
async function getPilotScore(pilotId) {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT score FROM pilots
WHERE id = ?
`,
[pilotId],
(err, result) => {
if (err) {
console.error("Errore durante la ricerca del punteggio:", err);
reject(err);
} else {
if (result.length > 0) {
resolve(result[0].score);
} else {
console.log("Punteggio non presente nel database!");
resolve(false);
}
}
}
);
});
}
function sumScore(score) {
let totalScore = 0;
console.log(score);
score = score.split(";");
for (let i = 0; i < score.length; i++) {
if (score[i] != "") {
let roundScore = score[i].split(",");
totalScore += parseInt(roundScore[0]) + parseInt(roundScore[1]) + parseInt(roundScore[2]);
}
}
return totalScore;
}
async function getPilotTotalScore(pilotId) { //ok
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT score FROM pilots
WHERE id = ?
`,
[pilotId],
(err, result) => {
if (err) {
console.error("Errore durante la ricerca del punteggio:", err);
reject(err);
} else {
if (result.length > 0) {
let score = result[0].score;
let totalScore = sumScore(score);
resolve(totalScore);
} else {
console.log("Punteggio non presente nel database!");
resolve(false);
}
}
}
);
});
}
async function updateRoundTotalScore(roundNumber) {
let roundResult = await getRoundResult(roundNumber);
await updateScore(roundResult);
}
function weeklyUpdate(lastRoundNumber) {
updateRoundTotalScore(lastRoundNumber);
updateAllRoundsResultsCache();
updatePilotsAllRoundsResultsCache();
pilotsValueUpdate();
}
async function teamsScoreCleanup() {
return new Promise((resolve, reject) => {
pool.execute(
`UPDATE teams SET score = '0'`,
(err) => {
if (err) {
console.error("Errore durante la cancellazione della tabella:", err);
reject(err);
} else {
resolve(true);
}
}
);
});
}
async function retrieveAllRoundResults() {
let waitCleanup = await teamsScoreCleanup();
for (let i = 1; i <= parseInt(lastRoundNum); i++) {
await updateRoundTotalScore(i);
}
}
async function setLastRoundNumber() {
let lastRound = await axios.get('http://ergast.com/api/f1/current/last/results.json');
let lastRoundNumber = lastRound.data.MRData.RaceTable.round;
lastRoundNum = lastRoundNumber;
}
async function getTeamsId() {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT DISTINCT teamId FROM teams
`,
(err, result) => {
if (err) {
console.error("Errore durante la ricerca dei team:", err);
reject(err);
} else {
if (result.length > 0) {
resolve(result);
} else {
console.log("Team non presenti nel database!");
resolve(false);
}
}
}
);
});
}
async function hasTeam(userId) {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT * FROM teams
WHERE teamId = ?
`,
[userId],
(err, result) => {
if (err) {
console.error("Errore durante la ricerca del team:", err);
reject(err);
} else {
if (result.length > 0) {
resolve(true);
} else {
console.log("Team non presente nel database!");
resolve(false);
}
}
}
);
});
}
async function getUserId(username) {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT userId FROM users
WHERE username = ?
`,
[username],
(err, result) => {
if (err) {
console.error("Errore durante la ricerca dell'utente:", err);
reject(err);
} else {
if (result.length > 0) {
resolve(result[0].userId);
} else {
console.log("Utente non presente nel database!");
resolve(false);
}
}
}
);
});
}
cron.schedule('0 4 * * 1', async () => { // ogni lunedì controlla se è disponibile un nuovo risultato
let newRoundNumber = await getLastRoundNumber();
if (lastRoundNum < newRoundNumber) {
await weeklyUpdate(newRoundNumber);
}
else if (newRoundNumber == 1) {
await newSeasonCleanup();
await inizializeDatabase();
}
});
async function newSeasonCleanup() { // cancella e ripulisce tutte le table del database
return new Promise((resolve, reject) => {
pool.execute(
`
DROP TABLE IF EXISTS pilots, points, users, coins, teams, bonus
`,
(err) => {
if (err) {
console.error("Errore durante la cancellazione delle tabelle:", err);
reject(err);
} else {
resolve(true);
}
}
);
});
}
async function getCoins() {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT * FROM coins ORDER BY driverId ASC
`,
(err, result) => {
if (err) {
console.error("Errore durante la ricerca delle coins:", err);
reject(err);
} else {
if (result.length > 0) {
resolve(result);
} else {
console.log("Coins non presenti nel database!");
resolve(false);
}
}
}
);
});
}
async function getPilotsTable() {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT * FROM pilots ORDER BY id ASC
`,
(err, result) => {
if (err) {
console.error("Errore durante la ricerca dei piloti:", err);
reject(err);
} else {
if (result.length > 0) {
resolve(result);
} else {
console.log("Piloti non presenti nel database!");
resolve(false);
}
}
}
);
});
}
async function getPilotsValues() {
let pilots = await getPilotsTable();
let coins = await getCoins();
let pilotsValues = [];
for (let i = 0; i < pilots.length; i++) {
pilotsValues[i] = {};
pilotsValues[i]["value"] = coins[i].coins;
pilotsValues[i]["name"] = pilots[i].name;
pilotsValues[i]["surname"] = pilots[i].surname;
pilotsValues[i]["id"] = pilots[i].id;
pilotsValues[i]["team"] = pilotsAllRoundsResults[pilots[i].id][0].Results[0].Constructor.name;
pilotsValues[i]["constructorId"] = pilotsAllRoundsResults[pilots[i].id][0].Results[0].Constructor.constructorId;
}
return pilotsValues;
}
async function calculateTeamScore(pilots) { //inutile
let score = 0;
for (let i = 0; i < pilots.length; i++) {
let points = await getPilotTotalScore(pilots[i]);
if (points) {
score += parseInt(points);
}
}
return score;
}
async function updatePilotsAllRoundsResultsCache() {
let pilots = await getPilotsId();
for (let i = 0; i < pilots.length; i++) {
let pilotId = pilots[i].id;
let pilotNick = pilotsNicks[pilotId];
console.log(pilotNick);
let data = await getPilotAllRoundsResults(pilotNick);
pilotsAllRoundsResults[pilotId] = data;
}
}
async function getAllRoundsResults() {
const url = "http://ergast.com/api/f1/current/results.json?limit=1000";
try {
const response = await axios.get(url);
const driversData = response.data.MRData.RaceTable.Races;
return driversData;
} catch (error) {
console.error("Errore durante la richiesta all round:", error.message);
}
}
async function updateAllRoundsResultsCache() {
allRoundResults = await getAllRoundsResults();
}
async function checkTeamLegality(pilots) {
let coins = 0;
let pilotsValues = await getCoins();
for (let i = 0; i < pilots.length; i++) {
for (let j = 0; j < pilotsValues.length; j++) {
if (pilotsValues[j].driverId == pilots[i]) {
coins += parseInt(pilotsValues[j].coins);
}
}
}
return coins <= maxCoinBudget;
}
async function insertTestStandings() {
insertTeam(1, "teamN." + 1, "1,4", await calculateTeamScore(["1", "4"]));
}
async function getPilotsId() {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT id FROM pilots
`,
(err, result) => {
if (err) {
console.error("Errore durante la ricerca dei piloti:", err);
reject(err);
} else {
if (result.length > 0) {
//console.log("Piloti trovati con successo!");
resolve(result);
} else {
console.log("Piloti non presenti nel database!");
resolve(false);
}
}
}
);
});
}
async function getTeamsSinglePilotsPoints(teamId) {
return new Promise((resolve, reject) => {
pool.execute(
`
SELECT idPilots FROM teams
WHERE teamId = ?
`,
[teamId],
async (err, result) => {
if (err) {
console.error("Errore durante la ricerca dei membri del team:", err);
reject(err);
} else {