-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1269 lines (1262 loc) · 48 KB
/
server.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 express=require('express');
const app=express();
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const Handlebars = require("handlebars");
//import from another files
const util=import_util();
const matkhauDBService=import_matkhauDBService();
const db=import_db();
const phongDBService=import_phongDBService();
const loai_phongDBService=import_loai_phongDBService();
const loai_khachDBService=import_loai_khachDBService();
const khach_hangDBService=import_khach_hangDBService();
const phieu_thue_phongDBService=import_phieu_thue_phongDBService();
const khach_hang_phieu_thue_phongDBService=import_khach_hang_phieu_thue_phongDBService();
const hoa_donDBService=import_hoa_donDBService();
const templates=require('./templates.js');
const htmlTemplate2=require('./mainTemplate2.js');
const htmlTemplate=require('./mainTemplate');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname + "/public"));
app.use(cookieParser());
let arr=[];
app.get('/', function(req, res) {
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level==1){
//return staff's screen
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let aboutComponent=templates.about;
let html2=aboutComponent;
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
} else {
res.redirect('/manager');
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/logout', function(req, res) {
//logout and redirect to login page
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
})
app.post('/login', async function(req, res) {
//post login
//validate user's password
if (await matkhauDBService.validatePassword(req.body.pwd)){
let num=(Math.random()*1000000000000000000000)+'-'+(Math.random()*1000000000000000000000);
let level=await matkhauDBService.getLevel(req.body.pwd);
res.cookie('id',num);
arr.push({cookie:num,level});
res.redirect('/');
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/login', function(req, res) {
//get login page
if (util.validateCookie(req.cookies.id))
res.redirect('/');
else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.sendFile('./public/login.html', {root: __dirname });
}
})
app.get('/rooms', async function(req, res) {
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let notification=req.query['noti'];
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let roomsComponent=templates.rooms;
//create content for component
let rooms=await phongDBService.getAllRooms();
for (let i=0; i<rooms.length; i++){
let type=await loai_phongDBService.getTypeById(rooms[i].loai_phong);
rooms[i].stt=i+1;
rooms[i].ten_loai_phong=type.ten;
rooms[i].tinh_trang=(rooms[i].tinh_trang==0 ? 'Available' : 'Occupied');
}
let template2=Handlebars.compile(roomsComponent);
let types=await loai_phongDBService.getAllTypes();
let tmp=''+types[0].ten;
for (let i=1; i<types.length; i++)
tmp+=', '+types[i].ten;
types=tmp;
let html2=template2({rooms,types,notification});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/rent',async function (req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let notification=req.query['noti'];
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.rent;
//create content for component
let rooms=await phongDBService.getAvailableRooms();
for (let i=0; i<rooms.length; i++){
rooms[i].stt=i+1;
let type=await loai_phongDBService.getTypeById(rooms[i].loai_phong);
rooms[i].ten_loai_phong=type.ten;
}
let template2=Handlebars.compile(component);
let html2=template2({rooms,notification});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/rent-a-room',async function(req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.rentARoom;
//create content for component
let room=await phongDBService.getRoomById(req.query['id']);
let type=await loai_phongDBService.getTypeById(room.loai_phong);
let nums=[];
for (let i=0; i<type.so_khach_toi_da; i++)
nums.push(i+1);
let arr=await loai_khachDBService.getAllTypes();
let types=''+arr[0].id+' for "'+arr[0].ten+'"';
for (i=1; i<arr.length; i++)
types+=', '+arr[i].id+' for "'+arr[i].ten+'"';
let currentTime=new Date();
let date=util.formatNumberForDateTime(currentTime.getDate())+'-'+util.formatNumberForDateTime(currentTime.getMonth()+1)+'-'+currentTime.getFullYear();
let template2=Handlebars.compile(component);
let html2=template2({room,type,nums,types,date});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.post('/rent-a-room',async function(req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let room=await phongDBService.getRoomById(req.query['id']);
let numberOfCustomers=req.body.numberOfCustomers;
let currentTime=new Date();
let startDate=currentTime.getFullYear()+'-'+util.formatNumberForDateTime(currentTime.getMonth()+1)+'-'+util.formatNumberForDateTime(currentTime.getDate());
let customers=[];
for (let i=1; i<=numberOfCustomers; i++)
if (req.body[`name_${i}`]!=''){
let customer={};
customer.cmnd=req.body[`id_${i}`];
customer.ho_ten=req.body[`name_${i}`];
customer.loai=req.body[`type_${i}`];
customer.dia_chi=req.body[`addr_${i}`];
customers.push(customer);
}
//validate customers information
let isOk=true;
for (let i=0; i<customers.length; i++){
let customer=await khach_hangDBService.getCustomerById(customers[i].cmnd);
if (customer===undefined)
await khach_hangDBService.addNew(customers[i]);
else if (customer.ho_ten!=customers[i].ho_ten)
isOk=false;
else if (customer.loai!=customers[i].loai)
isOk=false;
else if (customer.dia_chi!=customers[i].dia_chi)
isOk=false;
}
let notification='';
if (!isOk)
notification="Information of customers is not identical with the data in DB";
else
notification="Create rental slip successfully";
if (isOk){
//update DB
await phongDBService.updateStatus(room.id,1);
await phieu_thue_phongDBService.addNew(startDate,room.id);
let slipId=await phieu_thue_phongDBService.find(startDate,room.id);
slipId=slipId.id;
for (let i=0; i<customers.length; i++){
await khach_hang_phieu_thue_phongDBService.addNew(customers[i].cmnd,slipId);
}
}
res.redirect(`/rent?noti=${notification}`);
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/search',async function (req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.searchRoom;
//create content for component
let types=await loai_phongDBService.getAllTypes();
let typeId=req.query['id'];
let avaiRooms=[];
let occupiedRooms=[];
if (typeId!==undefined){
let rooms=await phongDBService.getRoomsByType(typeId);
let type=await loai_phongDBService.getTypeById(typeId);
for (let i=0; i<rooms.length; i++)
if (rooms[i].tinh_trang==0){
rooms[i].stt=avaiRooms.length+1;
rooms[i].ten_loai_phong=type.ten;
rooms[i].don_gia=type.don_gia;
avaiRooms.push(rooms[i]);
} else {
rooms[i].stt=occupiedRooms.length+1;
rooms[i].ten_loai_phong=type.ten;
rooms[i].don_gia=type.don_gia;
occupiedRooms.push(rooms[i]);
}
}
let template2=Handlebars.compile(component);
let html2=template2({types,avaiRooms,occupiedRooms});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/update-room', async function(req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let mode=req.query['mode'];
if (mode=='add'){
let notification='';
let isOk=true;
let ten=req.query['name'];
let ghi_chu=req.query['note'];
let loai_phong=await loai_phongDBService.getIdByName(req.query['type']);
if (loai_phong===undefined)
isOk=false;
else {
let room={ten,loai_phong,ghi_chu,tinh_trang:0};
//add new room
isOk=await phongDBService.addNewRoom(room);
}
if (isOk)
notification="New room was added successfully";
else
notification="Please check the Name and the Type of room again:\n1. Name must be distinct\n2. Type must be valid";
res.redirect('/rooms?noti='+notification);
}
if (mode=='del'){
let notification='';
let isOk=true;
let id=parseInt(req.query['id']);
isOk=await phongDBService.checkSafeDelete(id);
if (isOk)
isOk=await phongDBService.deleteRoom(id);
if (isOk)
notification='Deleted successfully';
else
notification='The room is occupied, can not delete it';
res.redirect('/rooms?noti='+notification);
}
if (mode=='upd'){
let notification='';
let isOk=true;
let id=parseInt(req.query['id']);
let ten=req.query['name'];
let tinh_trang=(req.query['status']=='Available' ? 0 : 1);
let ghi_chu=req.query['note'];
let loai_phong=await loai_phongDBService.getIdByName(req.query['type']);
if (loai_phong===undefined)
isOk=false;
else {
let room={id,ten,loai_phong,ghi_chu,tinh_trang};
//update room
isOk=await phongDBService.updateRoomById(room);
}
if (isOk)
notification='Updated successfully';
else
notification='Please check the Name, the Type and the Status of room again:\n1. Name must be distinct\n2. Type must be valid\n3. Status must be Available';
res.redirect('rooms?noti='+notification);
}
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/bill', async function(req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let roomName=req.query['name'];
if (roomName===undefined){
let notification=req.query['noti'];
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.chooseRoom;
let template2=Handlebars.compile(component);
let html2=template2({notification});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
} else {
//check roomName
let room=await phongDBService.getRoomByName(roomName);
if (room===undefined){
res.redirect(`/bill?noti=${'This room does not exist\nPlease check again'}`);
} else {
if (room.tinh_trang==0){
res.redirect(`/bill?noti=${'This room is not being rented\nPlease check again'}`);
} else {
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.createBill;
let template2=Handlebars.compile(component);
let phieu_thue_phong=await phieu_thue_phongDBService.getByRoomId(room.id);
let customersId=await khach_hang_phieu_thue_phongDBService.getByPhieuThueId(phieu_thue_phong.id);
let customers=await khach_hangDBService.getByIdList(customersId);
for (let i=0; i<customers.length; i++)
customers[i].stt=i+1;
let type=await loai_phongDBService.getTypeById(room.loai_phong);
let startDate=new Date(phieu_thue_phong.ngay_bat_dau);
let currentTime=new Date();
let days=currentTime.getDate()-startDate.getDate();
//calculate total
let total=type.don_gia;
for (let i=2; i<customers.length; i++){
total+=type.don_gia*type.ty_le_phu_thu;
}
let maxHeSo=1;
for (let i=0; i<customers.length; i++){
let tmp=await loai_khachDBService.getById(customers[i].loai);
maxHeSo=Math.max(maxHeSo,tmp.he_so);
}
total*=maxHeSo;
total*=days;
let ngay_lap=currentTime.getFullYear()+'-'+util.formatNumberForDateTime(currentTime.getMonth()+1)+'-'+util.formatNumberForDateTime(currentTime.getDate());
let html2=template2({customers,room,type,days,total,phieuThueId:phieu_thue_phong.id,ngay_lap});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
}
}
}
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.post('/create-bill',async function(req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
//get data from body
let tri_gia=parseInt(req.body.tri_gia);
let phieu_thue=parseInt(req.body.phieu_thue);
let ngay_lap=req.body.ngay_lap;
let tmp=await phieu_thue_phongDBService.getById(phieu_thue);
let notification='';
let isOk=(await hoa_donDBService.addNew(tri_gia,phieu_thue,ngay_lap) && phongDBService.updateStatus(tmp.phong, 0));
if (isOk)
notification="Created successfully";
else
notification="Something went wrong with the DB. Please check DB log for more details";
res.redirect('/bill?noti='+notification);
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/stat', async function (req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level!=1)
res.redirect('/');
else {
let month=req.query['month'];
let notification=req.query['noti'];
if (month===undefined){
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.chooseMonth;
let template2=Handlebars.compile(component);
let html2=template2({notification});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
} else {
let currentTime=new Date();
if (parseInt(month)<currentTime.getMonth()+1){
let html=htmlTemplate.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.stat;
let template2=Handlebars.compile(component);
let types=await loai_phongDBService.getAllTypes();
let total=0;
for (let i=0; i<types.length; i++){
types[i].stt=i+1;
let doanh_thu=await hoa_donDBService.getTotalByRoomType(types[i].id,month);
total+=doanh_thu;
types[i].doanh_thu=doanh_thu;
}
for (let i=0; i<types.length; i++){
types[i].phan_tram=(types[i].doanh_thu>0 ? types[i].doanh_thu*100/total : 0);
}
let rooms=await phongDBService.getAllRooms();
for (let i=0; i<rooms.length; i++){
rooms[i].stt=i+1;
rooms[i].days=await phieu_thue_phongDBService.countDays(rooms[i].id,month);
rooms[i].phan_tram=rooms[i].days/30*100;
}
let tmp=['','January','February','March','April','May','June','July','August','September','October','November','December'];
let html2=template2({month:tmp[parseInt(month)],types,rooms});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
} else {
notification='Month to create Statistics is smaller than the current month. Please input a valid month';
res.redirect(`/stat?noti=${notification}`);
}
}
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/manager',async function (req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level==1)
res.redirect('/');
else {
//return manager's screen
let html=htmlTemplate2.htmlTemplate;
let template=Handlebars.compile(html);
let aboutComponent=templates.about;
let html2=aboutComponent;
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/manager/room-type',async function(req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level==1)
res.redirect('/');
else {
let mode=req.query['mode'];
if (mode===undefined){
let notification=req.query['noti'];
let html=htmlTemplate2.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.roomTypeManage;
//create content for component
let types=await loai_phongDBService.getAllTypes();
for (let i=0; i<types.length; i++)
types[i].stt=i+1;
let template2=Handlebars.compile(component);
let html2=template2({notification,types});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
} else if (mode=='add'){
//get data
let ten=req.query['name'];
let don_gia=req.query['price'];
let so_khach_toi_da=req.query['max'];
let ty_le_phu_thu=req.query['extra'];
//check name is unique or not
let isOk=await loai_phongDBService.checkUniqueName(ten);
if (isOk)
isOk=await loai_phongDBService.addNew({ten,don_gia,so_khach_toi_da,ty_le_phu_thu});
if (!isOk){
let notification='This room type name is already exists';
res.redirect('/manager/room-type?noti='+notification);
} else {
let notification='Added new room type successfully';
res.redirect('/manager/room-type?noti='+notification);
}
} else if (mode=='upd'){
//get data
let id=req.query['id'];
let ten=req.query['name'];
let don_gia=req.query['price'];
let so_khach_toi_da=req.query['max'];
let ty_le_phu_thu=req.query['extra'];
//check name is unique or not
let isOk=await loai_phongDBService.checkUniqueNameForUpdate(id,ten);
if (isOk)
isOk=await loai_phongDBService.update({id,ten,don_gia,so_khach_toi_da,ty_le_phu_thu});
if (!isOk){
let notification='This room type name is already exists';
res.redirect('/manager/room-type?noti='+notification);
} else {
let notification='Updated room type successfully';
res.redirect('/manager/room-type?noti='+notification);
}
}
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.get('/manager/customer-type',async function(req, res){
if (util.validateCookie(req.cookies.id)){
let level=util.getUserLevel(arr,req.cookies.id);
if (level==1)
res.redirect('/');
else {
let mode=req.query['mode'];
if (mode===undefined){
let notification=req.query['noti'];
let html=htmlTemplate2.htmlTemplate;
let template=Handlebars.compile(html);
let component=templates.customTypeManage;
//create content for component
let types=await loai_khachDBService.getAllTypes();
for (let i=0; i<types.length; i++)
types[i].stt=i+1;
let template2=Handlebars.compile(component);
let html2=template2({notification,types});
html=template({contentPanel:html2});
let dummy='';
for (let i=0; i<100; i++)
dummy+=' ';
html+=dummy;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': html.length,
"Cache-Control": "no-cache, no-store, must-revalidate"
});
res.end(html);
} else if (mode=='add'){
//get data
let ten=req.query['name'];
let he_so=req.query['coef'];
//check name is unique or not
let isOk=await loai_khachDBService.checkUniqueName(ten);
if (isOk)
isOk=await loai_khachDBService.addNew({ten,he_so});
if (!isOk){
let notification='This customer type name is already exists';
res.redirect('/manager/customer-type?noti='+notification);
} else {
let notification='Added new customer type successfully';
res.redirect('/manager/customer-type?noti='+notification);
}
} else if (mode=='upd'){
//get data
let id=req.query['id'];
let ten=req.query['name'];
let he_so=req.query['coef'];
//check name is unique or not
let isOk=await loai_khachDBService.checkUniqueNameForUpdate(id,ten);
if (isOk)
isOk=await loai_khachDBService.update({id,ten,he_so});
if (!isOk){
let notification='This customer type name is already exists';
res.redirect('/manager/customer-type?noti='+notification);
} else {
let notification='Updated customer type successfully';
res.redirect('/manager/customer-type?noti='+notification);
}
}
}
} else {
util.removeElement(arr,req.cookies.id);
res.clearCookie('id');
res.redirect('/login');
}
})
app.use('/',function(req, res){
res.send(`
<div style="height: 100%; display:flex; justify-content: center; align-items: center">
<b style="font-size:40px">
404<br>Page Not Found
</b>
</div>
`);
})
//file utils.js ==============================================================================
function import_util(){
function validateCookie(userCookie){
//validate user's cookie
if (userCookie === undefined)
return false;
for (let i=0; i<arr.length; i++)
if (arr[i].cookie==userCookie)
return true;
return false;
}
function removeElement(arr, cookie){
if (cookie===undefined)
return;
for (let i=0; i<arr.length; i++)
if (arr[i].cookie==cookie){
let tmp=arr[i];
arr[i]=arr[arr.length-1];
arr[arr.length-1]=tmp;
}
arr.pop();
}
function getUserLevel(arr, cookie){
for (let i=0; i<arr.length; i++)
if (arr[i].cookie===cookie)
return arr[i].level;
}
function formatNumberForDateTime(digit){
return (digit<10 ? '0'+digit : digit);
}
return {validateCookie,removeElement,getUserLevel,formatNumberForDateTime};
}
//file matkhauDBService.js ===================================================================
function import_matkhauDBService(){
async function validatePassword(password) {
let sql='select * from mat_khau';
let arr=await db.read(sql);
let hashPassword=password;
for (let i=0; i<arr.length; i++)
if (arr[i].hash_mat_khau==hashPassword)
return true;
return false;
}
async function getLevel(password) {
let sql='select * from mat_khau';
let arr=await db.read(sql);
let hashPassword=password;
for (let i=0; i<arr.length; i++)
if (arr[i].hash_mat_khau==hashPassword)
return arr[i].cap_bac;
}
return {validatePassword,getLevel};
}
//file db.js =================================================================================
function import_db(){
const mysql = require("mysql");
function createConnection() {
return mysql.createConnection({
host: "localhost",
port: "3306",
user: "root",
password: "",
database: "hoteldb"
});
}
function read(sql){
return new Promise((resolve, reject) => {
const con = createConnection();
con.connect(err => {
if (err) {
reject(err);
}
});
con.query(sql, (error, results, fields) => {
if (error) {
reject(error);
} else
resolve(results);
});
con.end();
});
};
function create(tbName, entity){
return new Promise((resolve, reject) => {
const con = createConnection();
con.connect(err => {
if (err) {
reject(err);
}
});
const sql = `INSERT INTO ${tbName} SET ?`;
con.query(sql, entity, (error, results, fields) => {
if (error)
reject(error);
else
resolve(results);
});
con.end();
});
};
function del(tbName, idField, id){
return new Promise((resolve, reject) => {
const con = createConnection();
con.connect(err => {
if (err)
reject(err);
});
let sql = `DELETE FROM ?? WHERE ?? = ?`;
const params = [tbName, idField, id];
sql = mysql.format(sql, params);
con.query(sql, (error, results, fields) => {
if (error)
reject(error);
else
resolve(results);
});
con.end();
});
};
function update(tbName, idField, entity){
return new Promise((resolve, reject) => {
const con = createConnection();
con.connect(err => {
if (err)
reject(err);
});
const id = entity[idField];
delete entity[idField];
let sql = `UPDATE ${tbName} SET ? WHERE ${idField} = "${id}"`;
sql = mysql.format(sql, entity);
con.query(sql, (error, results, fields) => {
if (error)
reject(error);
else
resolve(results);
});
con.end();
});
};
return {create,read,update,del};
}
//file phongDBService.js =====================================================================
function import_phongDBService(){
async function getAllRooms() {
let sql='select * from phong';
let arr=await db.read(sql);
return arr;
}
async function addNewRoom(room){
let arr=await getAllRooms();
for (let i=0; i<arr.length; i++)
if (arr[i].ten==room.ten)
return false;
try {
await db.create('phong',room);
} catch (e) {
console.log(e);
return false;
}
return true;
}
async function updateRoomById(room){
room.id=parseInt(room.id);
room.tinh_trang=parseInt(room.tinh_trang);
room.loai_phong=parseInt(room.loai_phong);
//check ten, loai_phong and tinh_trang
let arr=await getAllRooms();
for (let i=0; i<arr.length; i++)
if (arr[i].ten==room.ten && arr[i].id!=room.id)
return false;
let type=await loai_phongDBService.getTypeById(room.loai_phong);
if (type===undefined)
return false;
if (room.tinh_trang!=0)
return false;
try {
await db.update('phong','id',room);
} catch (e) {
console.log(e);
return false;
}
return true;
}
async function getAvailableRooms(){
let arr=await getAllRooms();
let newArr=[];
for (let i=0; i<arr.length; i++)
if (arr[i].tinh_trang==0)
newArr.push(arr[i]);
return newArr;
}
async function getRoomById(id){
let arr=await getAllRooms();
for (let i=0; i<arr.length; i++)
if (arr[i].id==id)
return arr[i];
}
async function getRoomByName(name){
let arr=await getAllRooms();
for (let i=0; i<arr.length; i++)
if (arr[i].ten==name)
return arr[i];
}
async function updateStatus(roomId,status){
let room=await getRoomById(roomId);
room.tinh_trang=status;
try {
await db.update('phong','id',room);
} catch (e) {
console.log(e);
return false;
}
return true;
}
async function getRoomsByType(id){
let arr=await getAllRooms();
let newArr=[];
for (let i=0; i<arr.length; i++)
if (arr[i].loai_phong==id)
newArr.push(arr[i]);
return newArr;
}
async function checkSafeDelete(id){
let arr=await phieu_thue_phongDBService.getAll();
for (let i=0; i<arr.length; i++)
if (arr[i].phong==id)
return false;
return true;
}
async function deleteRoom(id){
try {
await db.del('phong','id',id);
} catch (e) {
console.log(e);
return false;
}
return true;
}
return {getAllRooms,addNewRoom,getAvailableRooms,getRoomById,updateStatus,getRoomsByType,updateRoomById,checkSafeDelete,deleteRoom,getRoomByName};
}
//file loai_phongDBService.js ================================================================
function import_loai_phongDBService(){
async function getAllTypes() {
let sql='select * from loai_phong';
let arr=await db.read(sql);
return arr;
}
async function getIdByName(name){
let arr=await getAllTypes();
for (let i=0; i<arr.length; i++)
if (arr[i].ten==name)
return parseInt(arr[i].id);
}
async function getTypeById(id){
let arr=await getAllTypes();
for (let i=0; i<arr.length; i++)
if (arr[i].id==id)
return arr[i];
}