-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase_models.py
More file actions
2234 lines (1952 loc) · 83.8 KB
/
Copy pathfirebase_models.py
File metadata and controls
2234 lines (1952 loc) · 83.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Firebase Firestore Models
Provides data access layer for Firestore collections
"""
import math
from datetime import datetime, timedelta, timezone
from werkzeug.security import generate_password_hash, check_password_hash
from firebase_config import db, USERS_COLLECTION, PROJECTS_COLLECTION, TASKS_COLLECTION, PROJECT_MEMBERS_COLLECTION, LABELS_COLLECTION, COMMENTS_COLLECTION, ACTIVITIES_COLLECTION, EVENTS_COLLECTION, CLIENTS_COLLECTION, CLIENT_PROJECT_ACCESS_COLLECTION, NOTIFICATIONS_COLLECTION, TIME_ENTRIES_COLLECTION, REQUIREMENTS_COLLECTION, ATTENDANCE_COLLECTION, SETTINGS_COLLECTION, LEAVE_BALANCES_COLLECTION, LEAVE_BALANCE_ARCHIVE_COLLECTION, PETTY_CASH_FUND_COLLECTION, PETTY_CASH_EXPENSES_COLLECTION, PETTY_CASH_REQUESTS_COLLECTION, PETTY_CASH_CATEGORIES_COLLECTION, COMPANY_PURCHASES_COLLECTION, COMPANY_INVOICES_COLLECTION, HOLIDAYS_COLLECTION, CREDITS_COLLECTION, TRANSACTIONS_COLLECTION, ROLES_COLLECTION, REGULARIZATION_COLLECTION, FACE_EMBEDDINGS_COLLECTION
from google.cloud.firestore_v1 import FieldFilter
class FirebaseUser:
"""User model for Firebase"""
@staticmethod
def create(username, email, password, full_name=None, created_by_admin=False, department=None):
"""Create a new user"""
user_ref = db.collection(USERS_COLLECTION).document()
now = datetime.now(timezone.utc)
user_data = {
'id': user_ref.id,
'username': username,
'email': email,
'password_hash': generate_password_hash(password),
'full_name': full_name,
'is_superadmin': False,
'is_accountant': False,
'role': 'employee',
'department': department,
'created_at': now,
# Subscription fields (set only for admin-created accounts)
'subscription_status': 'active' if created_by_admin else None,
'subscription_start': now if created_by_admin else None,
'subscription_expires': now + timedelta(days=30) if created_by_admin else None,
'grace_period_ends': now + timedelta(days=37) if created_by_admin else None,
# First-login flag
'must_change_password': created_by_admin,
}
user_ref.set(user_data)
return user_ref.id
@staticmethod
def get_by_id(user_id):
"""Get user by ID"""
doc = db.collection(USERS_COLLECTION).document(user_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_email(email):
"""Get user by email"""
users = db.collection(USERS_COLLECTION).where(filter=FieldFilter('email', '==', email)).limit(1).stream()
for user in users:
data = user.to_dict()
data['id'] = user.id
return data
return None
@staticmethod
def get_by_username(username):
"""Get user by username"""
users = db.collection(USERS_COLLECTION).where(filter=FieldFilter('username', '==', username)).limit(1).stream()
for user in users:
data = user.to_dict()
data['id'] = user.id
return data
return None
@staticmethod
def check_password(user_data, password):
"""Check if password matches"""
return check_password_hash(user_data['password_hash'], password)
@staticmethod
def update(user_id, data):
"""Update user data"""
db.collection(USERS_COLLECTION).document(user_id).update(data)
@staticmethod
def set_password(user_id, password):
"""Update user password"""
db.collection(USERS_COLLECTION).document(user_id).update({
'password_hash': generate_password_hash(password)
})
@staticmethod
def get_all():
"""Get all users"""
users = db.collection(USERS_COLLECTION).stream()
return [{'id': u.id, **u.to_dict()} for u in users]
@staticmethod
def set_superadmin(user_id, is_superadmin):
"""Toggle superadmin status for a user"""
db.collection(USERS_COLLECTION).document(user_id).update({
'is_superadmin': is_superadmin
})
@staticmethod
def set_accountant(user_id, is_accountant):
"""Toggle accountant role for a user"""
db.collection(USERS_COLLECTION).document(user_id).update({
'is_accountant': is_accountant
})
class FirebaseProject:
"""Project model for Firebase"""
@staticmethod
def create(name, description, owner_id):
"""Create a new project"""
project_ref = db.collection(PROJECTS_COLLECTION).document()
project_data = {
'id': project_ref.id,
'name': name,
'description': description,
'owner_id': owner_id,
'created_at': datetime.utcnow(),
'updated_at': datetime.utcnow()
}
project_ref.set(project_data)
return project_ref.id
@staticmethod
def get_by_id(project_id):
"""Get project by ID"""
doc = db.collection(PROJECTS_COLLECTION).document(project_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_owner(owner_id):
"""Get all projects owned by user"""
projects = db.collection(PROJECTS_COLLECTION).where(filter=FieldFilter('owner_id', '==', owner_id)).stream()
return [{'id': p.id, **p.to_dict()} for p in projects]
@staticmethod
def update(project_id, data):
"""Update project"""
data['updated_at'] = datetime.utcnow()
db.collection(PROJECTS_COLLECTION).document(project_id).update(data)
@staticmethod
def get_all():
"""Get all projects"""
projects = db.collection(PROJECTS_COLLECTION).stream()
return [{'id': p.id, **p.to_dict()} for p in projects]
@staticmethod
def delete(project_id):
"""Delete project"""
db.collection(PROJECTS_COLLECTION).document(project_id).delete()
class FirebaseTask:
"""Task model for Firebase"""
@staticmethod
def create(title, description, status, priority, project_id, created_by, assigned_to=None, due_date=None):
"""Create a new task"""
task_ref = db.collection(TASKS_COLLECTION).document()
task_data = {
'id': task_ref.id,
'title': title,
'description': description,
'status': status,
'priority': priority,
'project_id': project_id,
'created_by': created_by,
'assigned_to': assigned_to,
'due_date': due_date,
'created_at': datetime.utcnow(),
'updated_at': datetime.utcnow()
}
task_ref.set(task_data)
return task_ref.id
@staticmethod
def get_by_id(task_id):
"""Get task by ID"""
doc = db.collection(TASKS_COLLECTION).document(task_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_project(project_id):
"""Get all tasks for a project"""
tasks = db.collection(TASKS_COLLECTION).where(filter=FieldFilter('project_id', '==', project_id)).stream()
return [{'id': t.id, **t.to_dict()} for t in tasks]
@staticmethod
def get_by_assigned_user(user_id):
"""Get all tasks assigned to a user"""
tasks = db.collection(TASKS_COLLECTION).where(filter=FieldFilter('assigned_to', '==', user_id)).stream()
return [{'id': t.id, **t.to_dict()} for t in tasks]
@staticmethod
def get_with_due_dates():
"""Get all tasks that have due dates"""
tasks = db.collection(TASKS_COLLECTION).where(filter=FieldFilter('due_date', '!=', None)).stream()
return [{'id': t.id, **t.to_dict()} for t in tasks]
@staticmethod
def update(task_id, data):
"""Update task"""
data['updated_at'] = datetime.utcnow()
db.collection(TASKS_COLLECTION).document(task_id).update(data)
@staticmethod
def get_all():
"""Get all tasks"""
tasks = db.collection(TASKS_COLLECTION).stream()
return [{'id': t.id, **t.to_dict()} for t in tasks]
@staticmethod
def delete(task_id):
"""Delete task"""
db.collection(TASKS_COLLECTION).document(task_id).delete()
class FirebaseProjectMember:
"""Project member model for Firebase"""
@staticmethod
def create(project_id, user_id, role='member'):
"""Add a member to a project"""
member_ref = db.collection(PROJECT_MEMBERS_COLLECTION).document()
member_data = {
'id': member_ref.id,
'project_id': project_id,
'user_id': user_id,
'role': role,
'joined_at': datetime.utcnow()
}
member_ref.set(member_data)
return member_ref.id
@staticmethod
def get_by_project(project_id):
"""Get all members of a project"""
members = db.collection(PROJECT_MEMBERS_COLLECTION).where(filter=FieldFilter('project_id', '==', project_id)).stream()
return [{'id': m.id, **m.to_dict()} for m in members]
@staticmethod
def get_by_user(user_id):
"""Get all projects where user is a member"""
members = db.collection(PROJECT_MEMBERS_COLLECTION).where(filter=FieldFilter('user_id', '==', user_id)).stream()
return [{'id': m.id, **m.to_dict()} for m in members]
@staticmethod
def get_by_project_and_user(project_id, user_id):
"""Check if user is a member of project"""
members = db.collection(PROJECT_MEMBERS_COLLECTION).where(filter=FieldFilter('project_id', '==', project_id)).where(filter=FieldFilter('user_id', '==', user_id)).limit(1).stream()
for member in members:
data = member.to_dict()
data['id'] = member.id
return data
return None
@staticmethod
def delete(member_id):
"""Remove a member from a project"""
db.collection(PROJECT_MEMBERS_COLLECTION).document(member_id).delete()
class FirebaseLabel:
"""Label model for Firebase"""
@staticmethod
def create(name, color, project_id):
"""Create a new label"""
label_ref = db.collection(LABELS_COLLECTION).document()
label_data = {
'id': label_ref.id,
'name': name,
'color': color,
'project_id': project_id,
'created_at': datetime.utcnow()
}
label_ref.set(label_data)
return label_ref.id
@staticmethod
def get_by_project(project_id):
"""Get all labels for a project"""
labels = db.collection(LABELS_COLLECTION).where(filter=FieldFilter('project_id', '==', project_id)).stream()
return [{'id': l.id, **l.to_dict()} for l in labels]
@staticmethod
def delete(label_id):
"""Delete a label"""
db.collection(LABELS_COLLECTION).document(label_id).delete()
class FirebaseComment:
"""Comment model for Firebase"""
@staticmethod
def create(content, task_id, user_id):
"""Create a new comment"""
comment_ref = db.collection(COMMENTS_COLLECTION).document()
comment_data = {
'id': comment_ref.id,
'content': content,
'task_id': task_id,
'user_id': user_id,
'created_at': datetime.utcnow(),
'updated_at': datetime.utcnow()
}
comment_ref.set(comment_data)
return comment_ref.id
@staticmethod
def get_by_id(comment_id):
"""Get comment by ID"""
doc = db.collection(COMMENTS_COLLECTION).document(comment_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_task(task_id):
"""Get all comments for a task"""
comments = db.collection(COMMENTS_COLLECTION).where(filter=FieldFilter('task_id', '==', task_id)).order_by('created_at', direction='DESCENDING').stream()
return [{'id': c.id, **c.to_dict()} for c in comments]
@staticmethod
def delete(comment_id):
"""Delete a comment"""
db.collection(COMMENTS_COLLECTION).document(comment_id).delete()
class FirebaseActivity:
"""Activity model for Firebase"""
@staticmethod
def create(action, details, task_id, user_id):
"""Create a new activity log"""
activity_ref = db.collection(ACTIVITIES_COLLECTION).document()
activity_data = {
'id': activity_ref.id,
'action': action,
'details': details,
'task_id': task_id,
'user_id': user_id,
'created_at': datetime.utcnow()
}
activity_ref.set(activity_data)
return activity_ref.id
@staticmethod
def get_by_task(task_id):
"""Get all activities for a task"""
activities = db.collection(ACTIVITIES_COLLECTION).where(filter=FieldFilter('task_id', '==', task_id)).order_by('created_at', direction='DESCENDING').stream()
return [{'id': a.id, **a.to_dict()} for a in activities]
class FirebaseEvent:
"""Event model for Firebase"""
@staticmethod
def create(title, description, event_type, start_time, user_id, end_time=None, location=None):
"""Create a new event"""
event_ref = db.collection(EVENTS_COLLECTION).document()
event_data = {
'id': event_ref.id,
'title': title,
'description': description,
'event_type': event_type,
'start_time': start_time,
'end_time': end_time,
'location': location,
'user_id': user_id,
'created_at': datetime.utcnow(),
'updated_at': datetime.utcnow()
}
event_ref.set(event_data)
return event_ref.id
@staticmethod
def get_by_id(event_id):
"""Get event by ID"""
doc = db.collection(EVENTS_COLLECTION).document(event_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_user(user_id):
"""Get all events for a user"""
events = db.collection(EVENTS_COLLECTION).where(filter=FieldFilter('user_id', '==', user_id)).order_by('start_time').stream()
return [{'id': e.id, **e.to_dict()} for e in events]
@staticmethod
def get_upcoming_by_user(user_id, current_time):
"""Get upcoming events for a user"""
events = db.collection(EVENTS_COLLECTION).where(filter=FieldFilter('user_id', '==', user_id)).where(filter=FieldFilter('start_time', '>=', current_time)).order_by('start_time').limit(5).stream()
return [{'id': e.id, **e.to_dict()} for e in events]
@staticmethod
def update(event_id, data):
"""Update event"""
data['updated_at'] = datetime.utcnow()
db.collection(EVENTS_COLLECTION).document(event_id).update(data)
@staticmethod
def delete(event_id):
"""Delete event"""
db.collection(EVENTS_COLLECTION).document(event_id).delete()
class FirebaseClient:
"""Client model for Firebase - External clients who can view projects"""
@staticmethod
def create(name, email, password, created_by):
"""Create a new client"""
client_ref = db.collection(CLIENTS_COLLECTION).document()
client_data = {
'id': client_ref.id,
'name': name,
'email': email,
'password_hash': generate_password_hash(password),
'created_by': created_by,
'is_active': True,
'created_at': datetime.utcnow(),
'last_login': None
}
client_ref.set(client_data)
return client_ref.id
@staticmethod
def get_by_id(client_id):
"""Get client by ID"""
doc = db.collection(CLIENTS_COLLECTION).document(client_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_email(email):
"""Get client by email"""
clients = db.collection(CLIENTS_COLLECTION).where(filter=FieldFilter('email', '==', email)).limit(1).stream()
for client in clients:
data = client.to_dict()
data['id'] = client.id
return data
return None
@staticmethod
def get_by_creator(user_id):
"""Get all clients created by a user"""
clients = db.collection(CLIENTS_COLLECTION).where(filter=FieldFilter('created_by', '==', user_id)).stream()
return [{'id': c.id, **c.to_dict()} for c in clients]
@staticmethod
def check_password(client_data, password):
"""Check if password matches"""
return check_password_hash(client_data['password_hash'], password)
@staticmethod
def update(client_id, data):
"""Update client data"""
db.collection(CLIENTS_COLLECTION).document(client_id).update(data)
@staticmethod
def update_last_login(client_id):
"""Update last login time"""
db.collection(CLIENTS_COLLECTION).document(client_id).update({
'last_login': datetime.utcnow()
})
@staticmethod
def set_password(client_id, password):
"""Update client password"""
db.collection(CLIENTS_COLLECTION).document(client_id).update({
'password_hash': generate_password_hash(password)
})
@staticmethod
def delete(client_id):
"""Delete client"""
db.collection(CLIENTS_COLLECTION).document(client_id).delete()
class FirebaseClientProjectAccess:
"""Client project access model - Links clients to projects they can view"""
@staticmethod
def create(client_id, project_id, granted_by):
"""Grant a client access to a project"""
access_ref = db.collection(CLIENT_PROJECT_ACCESS_COLLECTION).document()
access_data = {
'id': access_ref.id,
'client_id': client_id,
'project_id': project_id,
'granted_by': granted_by,
'granted_at': datetime.utcnow()
}
access_ref.set(access_data)
return access_ref.id
@staticmethod
def get_by_client(client_id):
"""Get all projects a client has access to"""
access_records = db.collection(CLIENT_PROJECT_ACCESS_COLLECTION).where(filter=FieldFilter('client_id', '==', client_id)).stream()
return [{'id': a.id, **a.to_dict()} for a in access_records]
@staticmethod
def get_by_project(project_id):
"""Get all clients with access to a project"""
access_records = db.collection(CLIENT_PROJECT_ACCESS_COLLECTION).where(filter=FieldFilter('project_id', '==', project_id)).stream()
return [{'id': a.id, **a.to_dict()} for a in access_records]
@staticmethod
def get_by_client_and_project(client_id, project_id):
"""Check if client has access to a specific project"""
access_records = db.collection(CLIENT_PROJECT_ACCESS_COLLECTION).where(filter=FieldFilter('client_id', '==', client_id)).where(filter=FieldFilter('project_id', '==', project_id)).limit(1).stream()
for access in access_records:
data = access.to_dict()
data['id'] = access.id
return data
return None
@staticmethod
def delete(access_id):
"""Remove client access to a project"""
db.collection(CLIENT_PROJECT_ACCESS_COLLECTION).document(access_id).delete()
@staticmethod
def delete_by_client(client_id):
"""Remove all project access for a client"""
access_records = db.collection(CLIENT_PROJECT_ACCESS_COLLECTION).where(filter=FieldFilter('client_id', '==', client_id)).stream()
for access in access_records:
access.reference.delete()
class FirebaseNotification:
"""Notification model for Firebase"""
@staticmethod
def create(user_id, notification_type, title, message, link=None, related_id=None):
"""Create a new notification"""
notif_ref = db.collection(NOTIFICATIONS_COLLECTION).document()
notif_data = {
'id': notif_ref.id,
'user_id': user_id,
'type': notification_type,
'title': title,
'message': message,
'link': link,
'related_id': related_id,
'is_read': False,
'created_at': datetime.utcnow()
}
notif_ref.set(notif_data)
return notif_ref.id
@staticmethod
def get_by_user(user_id, limit=50):
"""Get notifications for a user"""
notifications = db.collection(NOTIFICATIONS_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).order_by('created_at', direction='DESCENDING').limit(limit).stream()
return [{'id': n.id, **n.to_dict()} for n in notifications]
@staticmethod
def get_unread_count(user_id):
"""Get count of unread notifications for a user"""
notifications = db.collection(NOTIFICATIONS_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(filter=FieldFilter('is_read', '==', False)).stream()
return len(list(notifications))
@staticmethod
def mark_as_read(notification_id):
"""Mark a notification as read"""
db.collection(NOTIFICATIONS_COLLECTION).document(notification_id).update({
'is_read': True
})
@staticmethod
def mark_all_as_read(user_id):
"""Mark all notifications as read for a user"""
notifications = db.collection(NOTIFICATIONS_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(filter=FieldFilter('is_read', '==', False)).stream()
for notif in notifications:
notif.reference.update({'is_read': True})
@staticmethod
def delete(notification_id):
"""Delete a notification"""
db.collection(NOTIFICATIONS_COLLECTION).document(notification_id).delete()
@staticmethod
def delete_old_notifications(user_id, days=30):
"""Delete notifications older than specified days"""
cutoff = datetime.utcnow() - timedelta(days=days)
notifications = db.collection(NOTIFICATIONS_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(filter=FieldFilter('created_at', '<', cutoff)).stream()
for notif in notifications:
notif.reference.delete()
class FirebaseTimeEntry:
"""Time entry model for Firebase - tracks time spent on tasks"""
@staticmethod
def create(task_id, user_id, duration_minutes, description=None, start_time=None, end_time=None):
"""Create a new time entry"""
entry_ref = db.collection(TIME_ENTRIES_COLLECTION).document()
entry_data = {
'id': entry_ref.id,
'task_id': task_id,
'user_id': user_id,
'duration_minutes': duration_minutes,
'description': description,
'start_time': start_time,
'end_time': end_time,
'created_at': datetime.utcnow()
}
entry_ref.set(entry_data)
return entry_ref.id
@staticmethod
def get_by_id(entry_id):
"""Get time entry by ID"""
doc = db.collection(TIME_ENTRIES_COLLECTION).document(entry_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_task(task_id):
"""Get all time entries for a task"""
entries = db.collection(TIME_ENTRIES_COLLECTION).where(
filter=FieldFilter('task_id', '==', task_id)
).order_by('created_at', direction='DESCENDING').stream()
return [{'id': e.id, **e.to_dict()} for e in entries]
@staticmethod
def get_by_user(user_id):
"""Get all time entries by a user"""
entries = db.collection(TIME_ENTRIES_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).order_by('created_at', direction='DESCENDING').stream()
return [{'id': e.id, **e.to_dict()} for e in entries]
@staticmethod
def get_total_time_for_task(task_id):
"""Get total time spent on a task in minutes"""
entries = db.collection(TIME_ENTRIES_COLLECTION).where(
filter=FieldFilter('task_id', '==', task_id)
).stream()
total = sum(e.to_dict().get('duration_minutes', 0) for e in entries)
return total
@staticmethod
def update(entry_id, data):
"""Update time entry"""
db.collection(TIME_ENTRIES_COLLECTION).document(entry_id).update(data)
@staticmethod
def delete(entry_id):
"""Delete time entry"""
db.collection(TIME_ENTRIES_COLLECTION).document(entry_id).delete()
@staticmethod
def delete_by_task(task_id):
"""Delete all time entries for a task"""
entries = db.collection(TIME_ENTRIES_COLLECTION).where(
filter=FieldFilter('task_id', '==', task_id)
).stream()
for entry in entries:
entry.reference.delete()
class FirebaseRequirement:
"""Requirement model for Firebase - things the team needs from the client"""
@staticmethod
def create(project_id, title, description, priority, created_by):
"""Create a new requirement"""
req_ref = db.collection(REQUIREMENTS_COLLECTION).document()
req_data = {
'id': req_ref.id,
'project_id': project_id,
'title': title,
'description': description,
'priority': priority,
'status': 'pending',
'created_by': created_by,
'created_at': datetime.utcnow(),
'updated_at': datetime.utcnow(),
'fulfilled_at': None,
'fulfilled_by': None
}
req_ref.set(req_data)
return req_ref.id
@staticmethod
def get_by_id(req_id):
"""Get requirement by ID"""
doc = db.collection(REQUIREMENTS_COLLECTION).document(req_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_project(project_id):
"""Get all requirements for a project"""
reqs = db.collection(REQUIREMENTS_COLLECTION).where(
filter=FieldFilter('project_id', '==', project_id)
).order_by('created_at', direction='DESCENDING').stream()
return [{'id': r.id, **r.to_dict()} for r in reqs]
@staticmethod
def get_pending_count_by_project(project_id):
"""Get count of pending requirements for a project"""
reqs = db.collection(REQUIREMENTS_COLLECTION).where(
filter=FieldFilter('project_id', '==', project_id)
).where(filter=FieldFilter('status', '==', 'pending')).stream()
return len(list(reqs))
@staticmethod
def update(req_id, data):
"""Update requirement"""
data['updated_at'] = datetime.utcnow()
db.collection(REQUIREMENTS_COLLECTION).document(req_id).update(data)
@staticmethod
def fulfill(req_id, fulfilled_by):
"""Mark requirement as fulfilled"""
db.collection(REQUIREMENTS_COLLECTION).document(req_id).update({
'status': 'fulfilled',
'fulfilled_at': datetime.utcnow(),
'fulfilled_by': fulfilled_by,
'updated_at': datetime.utcnow()
})
@staticmethod
def delete(req_id):
"""Delete requirement"""
db.collection(REQUIREMENTS_COLLECTION).document(req_id).delete()
@staticmethod
def delete_by_project(project_id):
"""Delete all requirements for a project"""
reqs = db.collection(REQUIREMENTS_COLLECTION).where(
filter=FieldFilter('project_id', '==', project_id)
).stream()
for req in reqs:
req.reference.delete()
def haversine_distance(lat1, lon1, lat2, lon2):
"""Calculate distance in meters between two GPS coordinates using Haversine formula"""
R = 6371000 # Earth radius in meters
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
class FirebaseAttendance:
"""Attendance model for Firebase - tracks daily check-in/check-out with geolocation"""
@staticmethod
def create(user_id, ip_address, latitude=None, longitude=None, location_address=None, notes=None, device_id=None, device_info=None, leave_type=None, status=None, leave_date=None, leave_reason=None, leave_duration=None, approval_status=None, outside_geofence=False, manual_entry=False, created_by=None, late_arrival=False, late_by_minutes=None):
"""Create a new attendance check-in record"""
att_ref = db.collection(ATTENDANCE_COLLECTION).document()
att_data = {
'id': att_ref.id,
'user_id': user_id,
'check_in_time': datetime.now(timezone.utc) if not leave_type else None,
'check_out_time': None,
'ip_address': ip_address,
'latitude': latitude,
'longitude': longitude,
'location_address': location_address,
'work_hours': None,
'status': status or ('absent' if leave_type else 'present'),
'leave_type': leave_type,
'leave_date': leave_date,
'leave_reason': leave_reason,
'leave_duration': leave_duration or ('full' if leave_type else None),
'approval_status': approval_status,
'approved_by': None,
'approved_at': None,
'rejection_reason': None,
'outside_geofence': outside_geofence,
'manual_entry': manual_entry,
'created_by': created_by,
'last_edited_by': None,
'edited_at': None,
'notes': notes,
'device_id': device_id,
'device_info': device_info,
'late_arrival': late_arrival,
'late_by_minutes': late_by_minutes,
'early_departure': False,
'early_by_minutes': None,
'created_at': datetime.now(timezone.utc)
}
att_ref.set(att_data)
return att_ref.id
@staticmethod
def get_by_id(record_id):
"""Get attendance record by ID"""
doc = db.collection(ATTENDANCE_COLLECTION).document(record_id).get()
if doc.exists:
data = doc.to_dict()
data['id'] = doc.id
return data
return None
@staticmethod
def get_by_user_today(user_id):
"""Get today's attendance record for a user (check-in or leave record)"""
IST_OFFSET = timedelta(hours=5, minutes=30)
now_utc = datetime.now(timezone.utc)
# Get today's date in IST, then find its UTC-equivalent midnight
ist_date_str = (now_utc + IST_OFFSET).strftime('%Y-%m-%d')
ist_midnight_utc = datetime.strptime(ist_date_str, '%Y-%m-%d').replace(tzinfo=timezone.utc) - IST_OFFSET
today_start = ist_midnight_utc
today_end = today_start + timedelta(days=1)
# Check for check-in based records
records = db.collection(ATTENDANCE_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(
filter=FieldFilter('check_in_time', '>=', today_start)
).where(
filter=FieldFilter('check_in_time', '<', today_end)
).order_by('check_in_time', direction='DESCENDING').limit(1).stream()
for record in records:
data = record.to_dict()
data['id'] = record.id
return data
# Also check leave_date for leave/absent records (no check_in_time)
leave_records = db.collection(ATTENDANCE_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(
filter=FieldFilter('leave_date', '>=', today_start)
).where(
filter=FieldFilter('leave_date', '<', today_end)
).limit(1).stream()
for record in leave_records:
data = record.to_dict()
data['id'] = record.id
return data
return None
@staticmethod
def get_by_user_date(user_id, target_date):
"""Get attendance record for a user on a specific date (including leave records)"""
IST_OFFSET = timedelta(hours=5, minutes=30)
ist_midnight = target_date.replace(hour=0, minute=0, second=0, microsecond=0)
day_start = ist_midnight - IST_OFFSET # IST midnight in UTC
day_end = day_start + timedelta(days=1)
# First try check_in_time based records
records = db.collection(ATTENDANCE_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(
filter=FieldFilter('check_in_time', '>=', day_start)
).where(
filter=FieldFilter('check_in_time', '<', day_end)
).limit(1).stream()
for record in records:
data = record.to_dict()
data['id'] = record.id
return data
# Also check leave_date for leave records (no check_in_time)
records = db.collection(ATTENDANCE_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(
filter=FieldFilter('leave_date', '>=', day_start)
).where(
filter=FieldFilter('leave_date', '<', day_end)
).limit(1).stream()
for record in records:
data = record.to_dict()
data['id'] = record.id
return data
return None
@staticmethod
def get_by_user_date_range(user_id, start_date, end_date):
"""Get attendance records for a user within a date range (check-ins + leave records)"""
seen_ids = set()
results = []
# Check-in based records
records = db.collection(ATTENDANCE_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(
filter=FieldFilter('check_in_time', '>=', start_date)
).where(
filter=FieldFilter('check_in_time', '<=', end_date)
).order_by('check_in_time', direction='DESCENDING').stream()
for r in records:
if r.id not in seen_ids:
seen_ids.add(r.id)
results.append({'id': r.id, **r.to_dict()})
# Leave records (leave_date in range)
leave_records = db.collection(ATTENDANCE_COLLECTION).where(
filter=FieldFilter('user_id', '==', user_id)
).where(
filter=FieldFilter('leave_date', '>=', start_date)
).where(
filter=FieldFilter('leave_date', '<=', end_date)
).stream()
for r in leave_records:
if r.id not in seen_ids:
seen_ids.add(r.id)
results.append({'id': r.id, **r.to_dict()})
# Sort by date descending
def sort_key(rec):
return rec.get('check_in_time') or rec.get('leave_date') or rec.get('created_at')
results.sort(key=sort_key, reverse=True)
return results
@staticmethod
def check_out(record_id):
"""Check out: set check_out_time and calculate work_hours"""
doc_ref = db.collection(ATTENDANCE_COLLECTION).document(record_id)
doc = doc_ref.get()
if not doc.exists:
return None
data = doc.to_dict()
check_in_time = data.get('check_in_time')
check_out_time = datetime.now(timezone.utc)
work_hours = None
if check_in_time:
delta = check_out_time - check_in_time
work_hours = round(delta.total_seconds() / 3600, 2)
status = 'present'
settings = FirebaseSettings.get_office_settings()
half_day_threshold = settings.get('half_day_threshold', 4)
if work_hours is not None and work_hours < half_day_threshold:
status = 'half-day'
# Early departure flag
early_departure = False
early_by_minutes = None
office_end_str = settings.get('office_end', '18:00')
try:
office_end_time = datetime.strptime(office_end_str, '%H:%M').time()
scheduled_end = datetime.combine(check_out_time.date(), office_end_time).replace(tzinfo=timezone.utc)
diff = (scheduled_end - check_out_time).total_seconds() / 60
if diff > 0:
early_departure = True
early_by_minutes = round(diff)
except (ValueError, AttributeError):
pass
doc_ref.update({
'check_out_time': check_out_time,
'work_hours': work_hours,
'status': status,
'early_departure': early_departure,
'early_by_minutes': early_by_minutes,
})
updated = doc_ref.get().to_dict()
updated['id'] = doc.id
return updated
@staticmethod
def get_unchecked_out_for_date(target_date):
"""Get all records checked in on target_date that have no check_out_time"""
IST_OFFSET = timedelta(hours=5, minutes=30)
ist_midnight = target_date.replace(hour=0, minute=0, second=0, microsecond=0)
day_start = ist_midnight - IST_OFFSET # IST midnight in UTC
day_end = day_start + timedelta(days=1)
records = db.collection(ATTENDANCE_COLLECTION).where(
filter=FieldFilter('check_in_time', '>=', day_start)