-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
825 lines (712 loc) · 30.4 KB
/
main.py
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
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import google.oauth2.id_token
from google.auth.transport import requests
import starlette.status as status
from google.cloud import firestore
from google.cloud.firestore_v1.base_query import FieldFilter, Or
import datetime
# define the app that will contain all of our routing for Fast API
app = FastAPI()
# Initialize Firestore client for database operations
firestore_db = firestore.Client()
# Set up request adapter for Firebase authentication
firebase_request_adapter = requests.Request()
# Define the static and templates directories
app.mount('/static', StaticFiles(directory='static'), name='static')
templates = Jinja2Templates(directory="templates")
# Function to retrieve user data from Firestore or create a default user if not found
def getUser(user_token):
user = firestore_db.collection('users').document(user_token['user_id'])
if not user.get().exists:
user_data = {
"username": '',
"rooms_list": []
}
firestore_db.collection('users').document(user_token['user_id']).set(user_data)
return user
# Function to validate Firebase ID token and retrieve user information
def validateFirebaseToken(id_token):
if not id_token:
return None
user_token = None
try:
user_token = google.oauth2.id_token.verify_firebase_token(id_token, firebase_request_adapter)
except ValueError as err:
print(str(err))
return user_token
# Route for the main page, handling user and guest authentication
@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
# Query firebase for the request token. An error message is set in case we want to output an error to
# the user in the template.
id_token = request.cookies.get("token")
errors: str | None = None
user_token = None
user = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None
)
return templates.TemplateResponse('main.html', context=context)
user = getUser(user_token).get()
rooms = [room.get("name") for room in firestore_db.collection('rooms').stream()]
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms
)
return templates.TemplateResponse('main.html', context=context)
@app.get('/set-username', response_class=HTMLResponse)
async def setUsername(request: Request):
"""Route (GET) for setting the username when a user logs in for the first time."""
id_token = request.cookies.get("token")
errors: str | None = None
user_token = None
user = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None
)
return templates.TemplateResponse('main.html', context=context)
user = getUser(user_token).get()
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
)
return templates.TemplateResponse('set-username.html', context=context)
@app.post('/set-username', response_class=HTMLResponse)
async def setUsername(request: Request):
"""Route (POST) for setting the username.
If the username is taken, redisplay the form with the error message.
"""
id_token = request.cookies.get("token")
user_token = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
form = await request.form()
user_exists = firestore_db.collection("users").where(filter=FieldFilter('username', '==', form['username'])).get()
if user_exists:
errors = 'This username is already taken.'
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None
)
return templates.TemplateResponse('set-username.html', context=context)
firestore_db.collection('users').document(user_token['user_id']).update({"username": form["username"]})
return RedirectResponse("/", status_code=status.HTTP_302_FOUND)
@app.post("/add-room", response_class=RedirectResponse)
async def addRoom(request: Request):
"""Gets the data from the form and adds it to Firestore."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
form = await request.form()
user = getUser(user_token)
# rooms are linked to users via keys. Get list of rooms for that user, add the new room to list, then update the list under user
rooms = user.get().get('rooms_list')
rooms_list = [room.get("name") for room in firestore_db.collection('rooms').stream()]
if form["roomName"] not in rooms_list:
# create a transaction object and the document reference object, then set the data and commit to save
transaction = firestore_db.transaction()
rooms_ref = firestore_db.collection('rooms').document()
transaction.set(rooms_ref, {'name': form['roomName'], 'days':[], 'owner': user_token['email'], 'user_id': user.id, 'date_created': str(datetime.date.today())})
transaction.commit()
rooms.append(rooms_ref)
user.update({'rooms_list': rooms})
return RedirectResponse('/', status.HTTP_302_FOUND)
else:
errors = "A room with that name already exists"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=[room.get("name") for room in user.get().get('rooms_list')]
)
return templates.TemplateResponse('main.html', context=context)
@app.get("/book-room", response_class=HTMLResponse)
async def bookRoom(request: Request, room: str):
"""Returns a form for booking a room.
Args;
room: the room to be booked, an optional argument.
"""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
min_time = ''
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None
)
return templates.TemplateResponse('main.html', context=context)
# find the minimum time that should be accepted from the user.
# if time now is past 7:00 am then provide current time as the minimum value to be accepted
# else provide 7:00 am as the default
if datetime.datetime.now().time() > datetime.time(7, 0, 0):
min_time = datetime.datetime.now().time().strftime("%H:%M")
else:
min_time = '07:00'
user = getUser(user_token)
# get the related rooms and store their names in a list
rooms = []
if room:
rooms.append(room)
else:
rooms = [room.get("name") for room in firestore_db.collection("rooms").stream()]
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms,
min_date=datetime.datetime.today().strftime("%Y-%m-%d"),
min_time=min_time,
)
return templates.TemplateResponse('book-room.html', context=context)
@app.post("/book-room", response_class=RedirectResponse)
async def bookRoom(request: Request):
"""Creates a booking for a room on the specified date."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
form = await request.form()
rooms = firestore_db.collection("rooms").stream()
if form["bookingStartTime"] >= form["bookingEndTime"]:
rooms_list = [room.get("name") for room in rooms]
errors = "Invalid start and end time selected"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
if datetime.date.fromisoformat(form['bookingDate']) == datetime.date.today():
'''If booking date is today and booking time is past'''
if datetime.time.fromisoformat(form['bookingStartTime']) < datetime.time.fromisoformat(datetime.datetime.now().time().isoformat(timespec='minutes')):
rooms_list = [room.get("name") for room in rooms]
errors = "Select a valid time"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
user = getUser(user_token)
try:
*_, room_query = firestore_db.collection("rooms").where(filter=FieldFilter('name', '==', form['roomName'])).get()
except ValueError:
rooms_list = [room.get("name") for room in rooms]
errors = "The selected room is no longer available"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
# get the dates associated with the room
dates = [day.get().get('date') for day in room_query.get('days')]
transaction = firestore_db.transaction()
if form["bookingDate"] not in dates:
"""The day we want to add booking for is not in the room yet.
There is no validation to do for bookings since there will be no bookings.
Create a ref object for the new day document, build a dict for the booking info,
and save it in a transaction.
Then update the room's days list to include the new day ref.
"""
days_ref = firestore_db.collection('days').document()
room_booking = {
'name': form['eventName'],
'date': form['bookingDate'],
'room': form['roomName'],
'from': form['bookingStartTime'],
'to': form['bookingEndTime'],
'user': user.id
}
transaction.set(days_ref, {'date': form['bookingDate'], 'room': form['roomName'], 'bookings':[room_booking,]})
transaction.commit()
days_list = room_query.get("days")
days_list.append(days_ref)
room_ref = room_query.reference
room_ref.update({'days': days_list})
else:
"""The day we want to add booking for is in the room.
We do validation for bookings.
Iterate through the days in the room, checking if the day matches our target.
Once we find a match we iterate through the bookings associated with that day
and do two checks to validate the new booking.
1. We check if the booking end time given in the form is greater than the start
time of the current booking we are iterating over.
2. We check if the booking start time given in the form is less than the end
time of the current booking we are iterating over.
If both the conditions are true then the user is trying to book a meeting in a time
slot that is already booked so we raise an exception.
If we iterate through the days without raising an exception it means the booking is
valid so we follow same steps as above to add it.
"""
days = room_query.get("days")
day = days[dates.index(form['bookingDate'])]
for booking in day.get().get("bookings"):
if form["bookingEndTime"] > booking["from"] and form["bookingStartTime"] < booking["to"]:
rooms_list = [room.get("name") for room in rooms]
errors = f"The room is already booked in this time slot: {booking['name']}, {booking['date']}, {booking['room']}, from {booking['from']} to {booking['to']}"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
room_booking = {
'name': form['eventName'],
'date': form['bookingDate'],
'room': form['roomName'],
'from': form['bookingStartTime'],
'to': form['bookingEndTime'],
'user': user.id
}
bookings_list = day.get().get('bookings')
bookings_list.append(room_booking)
day.update({"bookings": bookings_list})
return RedirectResponse('/', status.HTTP_302_FOUND)
@app.get('/view-bookings')
async def viewBookings(request: Request):
"""Show all the bookings the user has made on all the rooms."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None,
)
return templates.TemplateResponse('main.html', context=context)
user = getUser(user_token).get()
rooms = [room.get("name") for room in firestore_db.collection("rooms").stream()]
bookings_list = []
for day in firestore_db.collection("days").stream():
for booking in day.get('bookings'):
if booking['user'] == user.id:
bookings_list.append(booking)
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
bookings=bookings_list,
rooms=rooms
)
return templates.TemplateResponse('view-bookings.html', context=context)
@app.post('/view-bookings')
async def filterByRoomAndDay(request: Request):
"""Show all the bookings the user has made on one the rooms."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
room = None
date = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None,
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
form = await request.form()
try:
date = form['date']
except KeyError:
pass
try:
room = form['room']
except KeyError:
pass
user = getUser(user_token).get()
rooms = [room.get("name") for room in firestore_db.collection("rooms").stream()]
bookings_list = []
if date:
for day in firestore_db.collection("days").where(filter=FieldFilter('date', '==', date)).stream():
for booking in day.get('bookings'):
if room:
if booking['user'] == user.id and booking['room'] == room:
bookings_list.append(booking)
else:
bookings_list.append(booking)
elif room:
for day in firestore_db.collection("days").stream():
for booking in day.get('bookings'):
if booking['user'] == user.id and booking['room'] == room:
bookings_list.append(booking)
else:
for day in firestore_db.collection("days").stream():
for booking in day.get('bookings'):
if booking['user'] == user.id:
bookings_list.append(booking)
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
bookings=bookings_list,
rooms=rooms
)
return templates.TemplateResponse('view-bookings.html', context=context)
@app.post('/delete-booking')
async def deleteBooking(request: Request):
"""Delete a booking."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None,
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
form = await request.form()
try:
*_, room = firestore_db.collection('rooms').where(filter=FieldFilter('name', '==', form['room'])).get()
except ValueError:
pass
for day in room.get('days'):
if day.get().get('date') == form['date']:
bookings = day.get().get('bookings')
for index, value in enumerate(bookings):
if value.get("from") == form['from'] and value.get("to") == form['to']:
del bookings[index]
day.update({'bookings': bookings})
return RedirectResponse('/', status.HTTP_302_FOUND)
@app.get('/edit-booking')
async def editBooking(request: Request, booking_room: str, date: str, start: str, end: str, ):
"""Edit a booking.
Why delete a booking first when updating? A lot of information can change when a booking is updated,
notably the Room and Day. In that case we would have to delete the existing booking in the current day
and room then update it in the new day and room. Considering this is a possibility then it does no harm
to delete the booking right away an update is initiated, then recreate a new booking with the new information.
"""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None,
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
#form = await request.form()
user = getUser(user_token).get()
rooms = [room.get("name") for room in firestore_db.collection("rooms").stream()]
# find the minimum time that should be accepted from the user.
# if time now is past 7:00 am then provide current time as the minimum value to be accepted
# else provide 7:00 am as the default
if datetime.datetime.now().time() > datetime.time(7, 0, 0):
min_time = datetime.datetime.now().time().strftime("%H:%M")
else:
min_time = '07:00'
*_, room = firestore_db.collection("rooms").where(filter=FieldFilter('name', '==', booking_room)).get()
for day in room.get('days'):
if day.get().get('date') == date:
bookings = day.get().get('bookings')
for index, value in enumerate(bookings):
if value.get("from") == start and value.get("to") == end:
booking = {
'event': bookings[index].get('name'),
'date': bookings[index].get('date'),
'room': bookings[index].get('room'),
'from': bookings[index].get('from'),
'to': bookings[index].get('to')
}
del bookings[index]
day.update({'bookings': bookings})
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
booking=booking,
rooms=rooms,
min_time=min_time
)
return templates.TemplateResponse('edit-booking.html', context=context)
@app.post('/edit-booking')
async def editBooking(request: Request):
"""Edit a booking."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None,
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
form = await request.form()
rooms = firestore_db.collection("rooms").stream()
if form["bookingStartTime"] >= form["bookingEndTime"]:
rooms_list = [room.get("name") for room in rooms]
errors = "Invalid start and end time selected"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
if datetime.date.fromisoformat(form['bookingDate']) == datetime.date.today():
'''If booking date is today and booking time is past'''
if datetime.time.fromisoformat(form['bookingStartTime']) < datetime.time.fromisoformat(datetime.datetime.now().time().isoformat(timespec='minutes')):
rooms_list = [room.get("name") for room in rooms]
errors = "Select a valid time"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
user = getUser(user_token).get()
try:
*_, room_query = firestore_db.collection("rooms").where(filter=FieldFilter('name', '==', form['roomName'])).get()
except ValueError:
rooms_list = [room.get("name") for room in rooms]
errors = "The selected room is no longer available"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
# validation for day and bookings
dates = [day.get().get('date') for day in room_query.get('days')]
transaction = firestore_db.transaction()
if form["bookingDate"] not in dates:
days_ref = firestore_db.collection('days').document()
room_booking = {
'name': form['eventName'],
'date': form['bookingDate'],
'room': form['roomName'],
'from': form['bookingStartTime'],
'to': form['bookingEndTime'],
'user': user.id
}
transaction.set(days_ref, {'date': form['bookingDate'], 'bookings':[room_booking,]})
transaction.commit()
days_list = room_query.get("days")
days_list.append(days_ref)
room_ref = room_query.reference
room_ref.update({'days': days_list})
else:
days = room_query.get("days")
day = days[dates.index(form['bookingDate'])]
for booking in day.get().get("bookings"):
if form["bookingEndTime"] > booking["from"] and form["bookingStartTime"] < booking["to"]:
rooms_list = [room.get("name") for room in rooms]
errors = f"The room is already booked in this time slot: {booking['name']}, {booking['date']}, {booking['room']}, from {booking['from']} to {booking['to']}"
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=rooms_list
)
return templates.TemplateResponse('book-room.html', context=context)
room_booking = {
'name': form['eventName'],
'date': form['bookingDate'],
'room': form['roomName'],
'from': form['bookingStartTime'],
'to': form['bookingEndTime'],
'user': user.id
}
bookings_list = day.get().get('bookings')
bookings_list.append(room_booking)
day.update({"bookings": bookings_list})
return RedirectResponse('/', status.HTTP_302_FOUND)
@app.post('/delete-room')
async def deleteRoom(request: Request):
"""Delete a room."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None,
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
form = await request.form()
user = getUser(user_token)
if form['user'] != user.id:
errors = 'Rooms can only be deleted by the person who created it.'
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=[room.get("name") for room in user.get().get('rooms_list')]
)
return templates.TemplateResponse('main.html', context=context)
*_, room_query = firestore_db.collection('rooms').where(filter=FieldFilter('name', '==', form['room'])).where(filter=FieldFilter('user_id', '==', form['user'])).get()
days = room_query.get('days')
for day_index, day in enumerate(days):
"""Check if the room has bookings associated."""
if day.get().get('bookings'):
errors = 'Cannot delete room with bookings'
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=[room.get("name") for room in user.get().get('rooms_list')]
)
return templates.TemplateResponse('main.html', context=context)
else:
days[day_index].delete()
del days[day_index]
user_rooms = user.get().get('rooms_list')
room_names = [room.get().get("name") for room in user_rooms]
room_index = room_names.index(form['room'])
room_query.reference.update({'days':[]})
user_rooms[room_index].delete()
del user_rooms[room_index]
user.update({'rooms_list': user_rooms})
return RedirectResponse('/', status.HTTP_302_FOUND)
@app.get("/view-room/{room}", response_class=RedirectResponse)
async def viewRoom(request: Request, room: str):
"""Gets the details of a specified room."""
id_token = request.cookies.get("token")
user_token = None
user = None
errors: str | None = None
user_token = validateFirebaseToken(id_token)
# Validate user token - check if we have a valid firebase login if not return the template with empty data as we will show the login box
if not user_token:
context = dict(
request=request,
user_token=None,
errors=errors,
user_info=None,
)
return templates.TemplateResponse('main.html', context=context)
# get form data from the html page
# form = await request.form()
user = getUser(user_token)
bookings = []
try:
*_, room_query = firestore_db.collection('rooms').where(filter=FieldFilter('name', '==', room)).get()
except ValueError:
errors = 'The selected room is no longer available.'
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
rooms=[room.get("name") for room in user.get().get('rooms_list')]
)
return templates.TemplateResponse('main.html', context=context)
for day in room_query.get("days"):
if day.get().get("bookings"):
'''Only add to bookings if the list of bookings associated with this day is not empty.'''
bookings.append({day.get().get('date'): [item for item in day.get().get("bookings")]})
context = dict(
request=request,
user_token=user_token,
errors=errors,
user_info=user,
room=room_query,
bookings=bookings
)
return templates.TemplateResponse('view-room.html', context=context)