-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
1411 lines (1175 loc) · 38.7 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 sql = require('mssql');
const dbc = require('./db-config.js');
const crypto = require('crypto');
const isProduction = require('./nodeenv.js');
const pool = new sql.ConnectionPool(dbc.dbConfig);
async function loginUser(email, password) {
const user = {};
try {
//SELECT * FROM users WHERE username = 'user1' AND password = 'hashed_password';
const query = 'SELECT top 1 user_no, privilege_type, first_name, last_name FROM novapark.[user] WHERE email = @email AND passkey = @passkey';
await pool.connect();
const result = await pool.request()
.input('email', sql.NVarChar, email)
.input('passkey', sql.NVarChar, password)
.query(query);
if (result.recordset.length > 0) {
user.userNo = result.recordset[0].user_no;
user.privilege = result.recordset[0].privilege_type;
user.fname = result.recordset[0].first_name;
user.lname = result.recordset[0].last_name;
user.loggedIn = true;
console.log('User successfully logged in\n');
} else {
throw new Error('User could not login');
}
} catch (err) {
console.error('Error:', err);
user.loggedIn = false;
} finally {
pool.close();
}
return user;
}
async function addUser(fname, lname, email, password) {
let userNo = -1;
try {
await pool.connect();
let result = await pool.request()
.input('email', sql.NVarChar, email)
.input('passkey', sql.NVarChar, password)
.input('first_name', sql.NVarChar, fname)
.input('last_name', sql.NVarChar, lname)
.query('insert into novapark.[user] (email, passkey, first_name, last_name) values (@email, @passkey, @first_name, @last_name); SELECT top 1 user_no from novapark.[user] order by user_no desc;');
userNo = result.recordset[0].user_no;
// result = await pool.request()
// .input('user_no', sql.Int, userNo)
// .query('insert into novapark.owns_ticket (user_no, ticket_no) values (@user_no, NULL)');
console.log("User successfully added!\n");
} catch (err) {
console.error('Error:', err);
} finally {
pool.close();
}
return userNo;
}
//{fname, lname, phone: req.body.phone, age: req.body.age, ticketOption: req.body.ticket_choice}
async function addTicketAndVisitor(input) {
let wasSuccessful = true;
try {
//{visitorNo, wasSuccess}
// findExistingVisitor(userNo)
const vlookup = await findExistingVisitor(input.userNo);
// if (!(vlookup.wasSuccess))
// throw new Error('Visitor lookup was not successful');
// delete from novapark.ticket where ticket_no = @ticket_no;
// update novapark.owns_ticket set ticket_no = NULL where user_no = @user_no;
// update novapark.visitor set ticket_no = NULL where ticket_no = @ticket_no;
let query;
if (vlookup.wasSuccess) {
query = `
insert into novapark.ticket (ticket_no, t_type) values (@ticket_no, @t_type);
update novapark.visitor set ticket_no = @ticket_no where visitor_no = @visitor_no;
update novapark.owns_ticket set ticket_no = @ticket_no where user_no = @user_no;
`;
} else {
query = `
insert into novapark.ticket (ticket_no,t_type) values (@ticket_no, @t_type);
insert into novapark.visitor (first_name, last_name, ticket_no, phone, is_present, age, num_of_visitations) values (@first_name, @last_name, @ticket_no, @phone, @is_present, @age, @num_of_visitations);
insert into novapark.owns_ticket (user_no, ticket_no) values (@user_no, @ticket_no);
insert into novapark.is_visitor (user_no, visitor_no) select @user_no, visitor_no from novapark.visitor where ticket_no = @ticket_no;
`;
}
const ticketNum = generateRandomString(7);
let result;
await pool.connect();
if (vlookup.wasSuccess) {
result = await pool.request()
.input('ticket_no', sql.NChar(7), ticketNum)
.input('t_type', sql.NVarChar(8), input.ticketOption)
.input('visitor_no', sql.Int, vlookup.visitorNo)
.input('user_no', sql.Int, input.userNo)
.query(query);
} else {
result = await pool.request()
.input('first_name', sql.NVarChar(15), input.fname)
.input('last_name', sql.NVarChar(15), input.lname)
.input('ticket_no', sql.NChar(7), ticketNum)
.input('phone', sql.NChar(10), input.phone)
.input('is_present', sql.Bit, 0)
.input('age', sql.TinyInt, input.age)
.input('num_of_visitations', sql.SmallInt, 0)
.input('t_type', sql.NVarChar(8), input.ticketOption)
.input('user_no', sql.Int, input.userNo)
.query(query);
}
} catch (err) {
console.error('Error:', err);
wasSuccessful = false;
} finally {
pool.close();
}
return wasSuccessful;
}
async function addResortReservation(reservationInput, ticketNo) {
const {bookDate, suiteChoice, hoursChoice} = reservationInput;
const formattedBookDate = bookDate.replace('T', ' ');
let wasSuccessful = true;
let errMsg;
try {
//check if there is an existing resort reservation that is more than 24 hours
// let query = "select 1 from novapark.restaurant_reservation where (DATEDIFF(HOUR, _date, '" + formattedBookDate + "') > 24) and (ticket_no = @ticket_no)";
// let result = await pool.request()
// .input('ticket_no', sql.NChar(7), ticketNo)
// .query(query);
// if (result.recordset.length > 0) {
// errMsg = 'You cannot book a reservation that is more than 24 hours apart from another one';
// throw new Error('addRestaurantReservation: Tried to book reservations more than 24 hours apart!\n');
// }
const query = "insert into novapark.resort_reservation (ticket_no, _date, suite_type, stay_in_hours) values (@ticket_no, '" + formattedBookDate + "', @suite_type, @stay_in_hours)";
await pool.connect();
await pool.request()
.input('ticket_no', sql.NChar(7), ticketNo)
// .input('_date', sql.DateTime2(0), bookDate)
.input('suite_type', sql.Char(12), suiteChoice)
.input('stay_in_hours', sql.TinyInt, hoursChoice)
.query(query);
} catch (err) {
errMsg = 'Unable to book a resort reservation. Check to make sure the date you entered follows our booking policy and try again';
console.error('Error:', err);
wasSuccessful = false;
} finally {
pool.close();
}
return {wasSuccessful, errMsg};
}
//{ bookDate, restaurantChoice, numOfSeats }
async function addRestaurantReservation(reservationInput, ticketNo) {
const {bookDate, restaurantChoice, numOfSeats} = reservationInput;
const formattedBookDate = bookDate.replace('T', ' ');
let wasSuccessful = true;
let errMsg = '';
console.log(formattedBookDate);
try {
//check if there is an existing resort reservation that is more than 24 hours
// let query = "select 1 from novapark.resort_reservation where (DATEDIFF(HOUR, _date, '" + formattedBookDate + "') > 24) and (ticket_no = @ticket_no)";
// let result = await pool.request()
// .input('ticket_no', sql.NChar(7), ticketNo)
// .query(query);
// if (result.recordset.length > 0) {
// errMsg = 'You cannot book a reservation that is more than 24 hours apart from another one';
// throw new Error('addRestaurantReservation: Tried to book reservations more than 24 hours apart!\n');
// }
//lookup the restaurant no of the add restaurant choice
let query = 'select _no from novapark.restaurant where _name = @_name';
await pool.connect()
let result = await pool.request()
.input('_name', sql.NVarChar(40), restaurantChoice)
.query(query);
const res_no = (result.recordset.length > 0) ? result.recordset[0]._no : -1;
if (res_no === -1) {
errMsg = 'The restaurant you selected was invalid!';
throw new Error('addRestaurantReservation: Restaurant no is invalid!\n');
}
// console.log(res_no);
//check to make sure the input time is not out of bounds
// query = `SELECT 1 FROM novapark.restaurant WHERE (_no = @_no) AND CONVERT(TIME, ${formattedBookDate}) BETWEEN open_time AND close_time AND ${formattedBookDate} > GETDATE()`;
// equery = "SELECT 1 FROM novapark.restaurant WHERE _no = 8 AND CONVERT(TIME, '2023-11-22 17:42') BETWEEN open_time AND close_time AND '2023-11-21 13:18' > GETDATE()";
// await pool.connect()
// query = "SELECT 1 FROM novapark.restaurant WHERE _no = @_no AND CONVERT(TIME, '" + formattedBookDate + "') BETWEEN open_time AND close_time AND '" + formattedBookDate + "' > GETDATE();";
// result = await pool.request()
// .input('_no', sql.SmallInt, res_no)
// // .input('_date', sql.DateTime, formattedBookDate)
// .query(query);
// if (result.recordset.length === 0) {
// errMsg = 'The time you put is outside the business hours of the restaurant you selected!'
// throw new Error('addRestaurantReservation: The time you put in is outside the business hours of the restaurant you chose\n');
// }
query = "insert into novapark.restaurant_reservation (ticket_no, _no, _date, num_of_people) values (@ticket_no, @_no, '" + formattedBookDate + "', @num_of_people)";
result = await pool.request()
.input('ticket_no', sql.NChar(7), ticketNo)
.input('_no', sql.SmallInt, res_no)
// .input('_date', sql.DateTime, formattedBookDate)
.input('num_of_people', sql.TinyInt, numOfSeats)
.query(query);
} catch (err) {
console.error('Error:', err);
errMsg = 'Unable to book a restaurant reservation. Check to make sure the date you entered follows our booking policy and try again';
wasSuccessful = false;
} finally {
pool.close();
}
return {wasSuccessful, errMsg};
}
async function test() {
}
// async function getTicketHolder(ticket)
// SELECT *
// FROM Table1
// INNER JOIN Table2 ON Table1.ColumnA = Table2.ColumnB
// INNER JOIN Table3 ON Table2.ColumnC = Table3.ColumnD;
async function getTicketInfo(userNo) {
const payload = {ticketNum: '', ticketType: '', wasSuccess: true};
try {
await pool.connect();
let result = await pool.request()
.input('user_no', sql.Int, userNo)
.query(`
select t.ticket_no, t.t_type, v.first_name, v.last_name from novapark.owns_ticket as o
inner join novapark.ticket as t on o.ticket_no = t.ticket_no
inner join novapark.visitor as v on t.ticket_no = v.ticket_no
where o.user_no = @user_no
`);
if (result.recordset.length > 0) {
payload.ticketNum = result.recordset[0].ticket_no;
payload.ticketType = result.recordset[0].t_type;
payload.fname = result.recordset[0].first_name;
payload.lname = result.recordset[0].last_name;
}
else
throw new Error('Could not find a ticket for current user');
}
catch (err) {
console.error('Error:', err);
payload.wasSuccess = false;
} finally {
pool.close();
}
return payload;
}
async function getResortReservation(ticketNo) {
const payload = {wasSuccess: true};
try {
await pool.connect();
result = await pool.request()
.input('ticket_no', sql.NChar, ticketNo)
.query('select _date, suite_type, stay_in_hours from novapark.resort_reservation where ticket_no = @ticket_no');
if (result.recordset.length > 0) {
payload.bookDate = result.recordset[0]._date;
payload.suiteType = result.recordset[0].suite_type;
payload.stayInHours = result.recordset[0].stay_in_hours;
}
else
throw new Error('getResortReservation: Could not find a ticket for current user');
} catch (err) {
console.error('Error:', err);
payload.wasSuccess = false;
} finally {
pool.close();
}
return payload;
}
// select rr._date, rr.num_of_people, r._name
// from novapark.restaurant as r inner join novapark.restaurant_reservation as rr on r._no = rr._no
async function getRestaurantReservation(ticketNo) {
let wasSuccess = true;
const payload = {};
try {
await pool.connect();
const result = await pool.request()
.input('ticket_no', sql.NChar, ticketNo)
.query('select rr._date, rr.num_of_people, r._name from novapark.restaurant as r inner join novapark.restaurant_reservation as rr on r._no = rr._no where rr.ticket_no = @ticket_no');
if (result.recordset.length > 0) {
payload.bookDate = result.recordset[0]._date;
payload.numOfPeople = result.recordset[0].num_of_people;
payload.restaurantName = result.recordset[0]._name;
}
else
throw new Error('getRestaurantReservation: Could not find a restaurant reservation for current user');
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, payload};
}
//{wasSuccess, bookDate, numOfPeople}
async function getRestaurantReservationFor(ticketNo, restaurantName) {
const payload = {wasSuccess: true};
try {
await pool.connect();
const result = await pool.request()
.input('ticket_no', sql.NChar, ticketNo)
.input('_name', sql.NVarChar(40), restaurantName)
.query('select rr._date, rr.num_of_people from novapark.restaurant as r inner join novapark.restaurant_reservation as rr on r._no = rr._no where rr.ticket_no = @ticket_no and r._name = @_name');
if (result.recordset.length > 0) {
payload.bookDate = result.recordset[0]._date;
payload.numOfPeople = result.recordset[0].num_of_people;
}
else
throw new Error('getRestaurantReservationFor: Could not find reservation at ' + reservationName + ' for current user\n');
} catch (err) {
console.error('Error:', err);
payload.wasSuccess = false;
} finally {
pool.close();
}
return payload;
}
// { book_date, restaurant_choice, num_seats }
async function updateRestaurantReservation(ticketNo, newInfo) {
const { book_date, restaurant_choice, num_seats } = newInfo;
const formattedDate = book_date.replace('T', ' ');
let payload = {wasSuccess: true, errMsg: ''};
try {
const query = `
declare @res_no SMALLINT;
select @res_no = _no
from novapark.restaurant where _name = @_name;
update novapark.restaurant_reservation
set _date = @_date, _no = @res_no, num_of_people = @num_of_people
where ticket_no = @ticket_no;
`;
await pool.connect();
await pool.request()
.input('_name', sql.NVarChar(40), restaurant_choice)
.input('_date', sql.DateTime, formattedDate)
.input('num_of_people', sql.TinyInt, num_seats)
.input('ticket_no', sql.NChar(7), ticketNo)
.query(query);
} catch (err) {
console.error('Error:', err);
payload.wasSuccess = false;
payload.errMsg = err;
} finally {
pool.close();
}
return payload;
}
async function updateResortReservation(ticketNo, newInfo) {
const { book_date, suite_choice, hours_choice } = newInfo;
const formattedDate = book_date.replace('T', ' ');
let payload = {wasSuccess: true, errMsg: ''};
try {
const query = `
update novapark.resort_reservation
set _date = @_date, suite_type = @suite_type, stay_in_hours = @stay_in_hours
where ticket_no = @ticket_no
`;
await pool.connect();
await pool.request()
.input('_date', sql.DateTime, formattedDate)
.input('suite_type', sql.Char(12), suite_choice)
.input('stay_in_hours', sql.TinyInt, hours_choice)
.input('ticket_no', sql.NChar(7), ticketNo)
.query(query);
} catch (err) {
console.error('Error:', err);
payload.wasSuccess = false;
payload.errMsg = err;
} finally {
pool.close();
}
return payload;
}
async function removeReservation(ticketNo, isResort=true) {
let errMsg = '';
try {
await pool.connect();
let result, query;
if (isResort)
query = 'delete from novapark.resort_reservation where ticket_no = @ticket_no';
else
query = 'delete from novapark.restaurant_reservation where ticket_no = @ticket_no';
result = await pool.request()
.input('ticket_no', sql.NChar(7), ticketNo)
.query(query);
} catch (err) {
console.error('Error:', err);
errMsg = 'Could not remove reservation, try again later.';
} finally {
pool.close();
}
return errMsg;
}
// --nkXKD4Q
// -- user_no = 3
// -- delete from novapark.resort_reservation where ticket_no = 'nkXKD4Q';
// -- delete from novapark.restaurant_reservation where ticket_no = 'nkXKD4Q';
// -- delete from novapark.owns_ticket;
// -- delete from novapark.ticket where ticket_no = 'nkXKD4Q';
// -- delete from novapark.[user] where user_no = 3;
// -- delete from novapark.visitor where ticket_no = 'nkXKD4Q';
async function removeTicket(ticketNo, userNo) {
let errMsg = '';
try {
//if operation returns an error message, something went wrong
if ((await removeReservation(ticketNo, true))) {
errMsg = 'Unable to remove resort reservation';
throw new Error(errMsg);
}
if ((await removeReservation(ticketNo, false))) {
errMsg = 'Unable to remove restaurant reservation';
throw new Error(errMsg);
}
const query = `
delete from novapark.ticket where ticket_no = @ticket_no;
update novapark.owns_ticket set ticket_no = NULL where user_no = @user_no;
update novapark.visitor set ticket_no = NULL where ticket_no = @ticket_no;
`;
await pool.connect();
await pool.request()
.input('ticket_no', sql.NChar(7), ticketNo)
.input('user_no', sql.Int, userNo)
.query(query);
}
catch (err) {
console.error('Error:', err);
errMsg = 'Unable to refund your ticket! Try again later';
} finally {
pool.close();
}
return errMsg;
}
async function getAllRestaurantReservations(name) {
let reservations = null;
let wasSuccess = true;
try {
const query = `
select ticket_no, _date, num_of_people
from novapark.restaurant as r inner join novapark.restaurant_reservation as rr
on r._no = rr._no
where r._name = @_name;
`;
await pool.connect();
const result = await pool.request()
.input('_name', sql.NVarChar(40), name)
.query(query);
if (result.recordset.length > 0)
reservations = result.recordset;
else
throw new Error('Not one reservation was found');
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, reservations};
}
async function getAllResortReservations() {
let reservations = null;
let wasSuccess = true;
try {
const query = `
select * from novapark.resort_reservation;
`;
await pool.connect();
const result = await pool.request()
.query(query);
if (result.recordset.length > 0)
reservations = result.recordset;
else
throw new Error('Not one reservation was found');
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, reservations};
}
async function getRestaurantNo(name) {
let wasSuccess = true;
let no;
try {
//.input('ticket_no', sql.NChar(7), ticketNo)
await pool.connect();
const result = await pool.request()
.input('_name', sql.NVarChar(40), name)
.query('select _no from novapark.restaurant where _name = @_name');
if (result.recordset.length > 0)
no = result.recordset[0]._no;
else
throw new Error('Unable to find restaurant with identifier ' + no);
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, no};
}
async function loadRestaurantNames() {
let wasSuccess = true;
let restaurantList;
try {
await pool.connect();
result = await pool.request()
.query('select _name from novapark.restaurant');
if (result.recordset.length > 0)
restaurantList = result.recordset;
else
throw new Error('loadRestaurantNames: No restaurant was found in the DB');
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, restaurantList};
}
//returns {email, fname, lname}
async function getProfile(userNo) {
const payload = {wasSuccess: true};
try {
const query = `
select first_name, last_name, email
from novapark.[user]
where user_no = @user_no
`;
await pool.connect();
const result = await pool.request()
.input('user_no', sql.Int, userNo)
.query(query);
if (result.recordset.length > 0) {
payload.fname = result.recordset[0].first_name;
payload.lname = result.recordset[0].last_name;
payload.email = result.recordset[0].email;
} else {
payload.errMsg = 'Unable to retrieve user info';
throw new Error(payload.errMsg);
}
} catch (err) {
console.error('Error:', err);
payload.wasSuccess = false;
} finally {
pool.close();
}
return payload;
}
async function updateProfile(userNo, newInfo) {
const {email, fname, lname} = newInfo;
let wasSuccess = true;
let errMsg;
try {
const query = `
update novapark.[user]
set email = @email, first_name = @first_name, last_name = @last_name
where user_no = @user_no
`;
await pool.connect();
await pool.request()
.input('email', sql.VarChar(50), email)
.input('first_name', sql.VarChar(15), fname)
.input('last_name', sql.VarChar(15), lname)
.input('user_no', sql.Int, userNo)
.query(query);
} catch (err) {
console.error('Error:', err);
errMsg = err;
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, errMsg};
}
async function updatePassword(userNo, newPassword, currPassword) {
let wasSuccess = true;
let errMsg;
try {
const query = `
update novapark.[user]
set passkey = @passkey
where user_no = @user_no and passkey = @curr_passkey;
select 1
from novapark.[user]
where user_no = @user_no and passkey = @passkey;
`;
await pool.connect();
const result = await pool.request()
.input('passkey', sql.VarChar(50), newPassword)
.input('curr_passkey', sql.VarChar(50), currPassword)
.input('user_no', sql.Int, userNo)
.query(query);
if (result.recordset.length == 0) {
errMsg = 'The email or password you entered is invalid';
throw new Error('invalid user name or password');
}
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, errMsg};
}
//utility functions
function generateRandomString(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; // Character set
const charactersLength = characters.length;
let result = '';
for (let i = 0; i < length; i++) {
const randomIndex = crypto.randomInt(0, charactersLength); // Generate random index
result += characters.charAt(randomIndex); // Get character at random index
}
return result;
}
//{visitorNo, fname, lname, ticketNo, phone, age, wasSuccess}
async function findExistingVisitor(userNo) {
const payload = {visitorNo: null, wasSuccess: true};
try {
const query = `
select v.visitor_no, v.first_name, v.last_name, v.ticket_no, v.phone, v.age
from novapark.visitor as v inner join novapark.is_visitor as iv on v.visitor_no = iv.visitor_no
where iv.user_no = @user_no;
`;
await pool.connect();
const result = await pool.request()
.input('user_no', sql.Int, userNo)
.query(query);
if (result.recordset.length > 0) {
payload.visitorNo = result.recordset[0].visitor_no;
payload.fname = result.recordset[0].first_name;
payload.lname = result.recordset[0].last_name;
payload.ticketNo = result.recordset[0].ticket_no;
payload.phone = result.recordset[0].phone;
payload.age = result.recordset[0].age;
}
else
throw new Error('Unable to find existing visitor');
} catch (err) {
console.error('Error:', err);
payload.wasSuccess = false;
} finally {
pool.close();
}
return payload;
}
async function updateVisitor(userNo, info) {
const {fname, lname, phone, age} = info;
let wasSuccess = true;
try {
const query = `
update novapark.visitor
set first_name = @first_name, last_name = @last_name, phone = @phone, age = @age
from novapark.is_visitor as iv
inner join novapark.visitor as v on iv.visitor_no = v.visitor_no
where iv.user_no = @user_no;
`;
await pool.connect();
const result = await pool.request()
.input('first_name', sql.NVarChar(15), fname)
.input('last_name', sql.NVarChar(15), lname)
.input('phone', sql.NChar(10), phone)
.input('age', sql.TinyInt, age)
.input('user_no', sql.Int, userNo)
.query(query);
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return wasSuccess;
}
async function getSuiteInfo() {
let wasSuccess = true;
let payload;
try {
const query = `
select * from novapark.suite_and_prices;
`;
await pool.connect();
const result = await pool.request()
.query(query);
if (result.recordset.length > 0)
payload = result.recordset;
else
throw new Error('Unable to get a single suite info');
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, payload};
}
async function getRides(detailed=false) {
let wasSuccess = true;
let payload;
try {
const query = `
select ride_name, ride_no
from novapark.amusement_ride
`;
await pool.connect();
const result = await pool.request()
.query(query);
if (result.recordset.length > 0)
payload = result.recordset;
else
throw new Error('Not a single ride was returned');
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, payload};
}
//reports
async function ridePopularityReport(startDate, endDate, rideName) {
let wasSuccess = true;
let payload;
try {
startDate = startDate.replace('T', ' ');
endDate = endDate.replace('T', ' ');
const query = `
SELECT a.ride_name,
COUNT(DISTINCT re.ticket_no) AS total_visitors
FROM novapark.ride_checkin as re
JOIN novapark.amusement_ride as a ON re.ride_no = a.ride_no
JOIN novapark.visitor as v ON re.ticket_no = v.ticket_no
WHERE a.ride_name = @ride_name
AND re._date BETWEEN CONVERT(DATE, '${startDate}') AND CONVERT(DATE,'${endDate}')
GROUP BY a.ride_name;
`;
await pool.connect();
const result = await pool.request()
.input('ride_name', sql.NVarChar(30), rideName)
.query(query);
payload = result.recordset;
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, payload};
}
async function revenueReport(startDate, endDate) {
let wasSuccess = true;
let payload;
try {
startDate = startDate.replace('T', ' ');
endDate = endDate.replace('T', ' ');
const query = `
SELECT
product.pname as pname,
SUM(purchase.amount) AS total_revenue,
AVG(purchase.amount) AS average
FROM
novapark.purchase as purchase inner join novapark.product as product on purchase.product_id = product.pid
WHERE
convert(date, _date) BETWEEN '${startDate}' AND '${endDate}'
GROUP BY
product.pname;
`;
await pool.connect();
const result = await pool.request()
.query(query);
payload = result.recordset;
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, payload};
}
// SELECT T.staff_no, T._name, COUNT(ML._no) AS Tasks_Count
// FROM novapark.technician T
// LEFT JOIN maintain_log ML ON T.staff_no = ML.technician_no
// WHERE T._name = @name AND convert(date, ML._date) BETWEEN convert(date, @startDate) AND convert(date, @endDate)
// GROUP BY T.staff_no, T._name;
async function technicianWorkloadReport(input) {
let wasSuccess = true;
let { name, startDate, endDate } = input;
let payload;
try {
startDate = startDate.replace('T', ' ');
endDate = endDate.replace('T', ' ');
const query = `
SELECT T.staff_no, T._name, COUNT(ML._no) AS Tasks_Count
FROM novapark.technician T
LEFT JOIN novapark.maintain_log ML ON T.staff_no = ML.technician_no
WHERE T._name = @name AND convert(date, ML._date) BETWEEN convert(date, '${startDate}') AND convert(date, '${endDate}')
GROUP BY T.staff_no, T._name;
`;
await pool.connect();
const result = await pool.request()
.input('name', sql.VarChar(15), name)
.query(query);
payload = result.recordset;
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, payload};
}
// {wasSuccess, payload}
async function getTechnicians() {
let wasSuccess = true;
let payload;
try {
const query = `
select _name from novapark.technician
`;
await pool.connect();
const result = await pool.request()
.query(query);
if (result.recordset.length < 0)
throw new Error('Unable to get list of technicians');
payload = result.recordset;
} catch (err) {
console.error('Error:', err);
wasSuccess = false;
} finally {
pool.close();
}
return {wasSuccess, payload};
}
async function rideUsageReport(startDate, endDate, rideName='', getAll=false) {
let wasSuccess = true;
let payload;
try {
startDate = startDate.replace('T', ' ');
endDate = endDate.replace('T', ' ');
let query;
if (getAll) {
query = `