forked from cds-snc/notification-api
-
Notifications
You must be signed in to change notification settings - Fork 9
/
models.py
2236 lines (1818 loc) · 87.5 KB
/
models.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
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
import datetime
import uuid
import itertools
from typing import Dict, Any
from app import (
DATETIME_FORMAT,
encryption,
)
from app.db import db
from app.encryption import (
check_hash,
hashpw,
)
from app.history_meta import Versioned
from app.model import User, EMAIL_AUTH_TYPE
from app.va.identifier import IdentifierType
from flask import url_for, current_app
from notifications_utils.columns import Columns
from notifications_utils.letter_timings import get_letter_timings
from notifications_utils.recipients import (
InvalidEmailError,
InvalidPhoneError,
try_validate_and_format_phone_number,
validate_email_address,
validate_phone_number,
)
from notifications_utils.template import (
LetterPrintTemplate,
PlainTextEmailTemplate,
SMSMessageTemplate,
)
from notifications_utils.timezones import convert_local_timezone_to_utc, convert_utc_to_local_timezone
from sqlalchemy import and_, CheckConstraint, Index, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSON, JSONB, UUID
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm.collections import attribute_mapped_collection, InstrumentedList
EMAIL_TYPE = 'email'
LETTER_TYPE = 'letter'
MOBILE_TYPE = 'mobile'
PUSH_TYPE = 'push'
SMS_TYPE = 'sms'
VA_NOTIFY_TO_VA_PROFILE_NOTIFICATION_TYPES = {
EMAIL_TYPE: 'Email',
SMS_TYPE: 'Text',
}
TEMPLATE_TYPES = [SMS_TYPE, EMAIL_TYPE, LETTER_TYPE]
template_types = db.Enum(*TEMPLATE_TYPES, name='template_type')
NORMAL = 'normal'
PRIORITY = 'priority'
TEMPLATE_PROCESS_TYPE = [NORMAL, PRIORITY]
DELIVERY_STATUS_CALLBACK_TYPE = 'delivery_status'
COMPLAINT_CALLBACK_TYPE = 'complaint'
INBOUND_SMS_CALLBACK_TYPE = 'inbound_sms'
SERVICE_CALLBACK_TYPES = [DELIVERY_STATUS_CALLBACK_TYPE, COMPLAINT_CALLBACK_TYPE, INBOUND_SMS_CALLBACK_TYPE]
UNKNOWN_COMPLAINT_TYPE = 'unknown complaint type'
WEBHOOK_CHANNEL_TYPE = 'webhook'
QUEUE_CHANNEL_TYPE = 'queue'
CALLBACK_CHANNEL_TYPES = [WEBHOOK_CHANNEL_TYPE, QUEUE_CHANNEL_TYPE]
def filter_null_value_fields(obj):
return dict(filter(lambda x: x[1] is not None, obj.items()))
class HistoryModel:
@classmethod
def from_original(
cls,
original,
):
history = cls()
history.update_from_original(original)
return history
def update_from_original(
self,
original,
):
for c in self.__table__.columns:
# in some cases, columns may have different names to their underlying db column - so only copy those
# that we can, and leave it up to subclasses to deal with any oddities/properties etc.
if hasattr(original, c.name):
setattr(self, c.name, getattr(original, c.name))
else:
current_app.logger.debug('{} has no column {} to copy from'.format(original, c.name))
class ServiceUser(db.Model):
__tablename__ = 'user_to_service'
user_id = db.Column(UUID(as_uuid=True), db.ForeignKey('users.id'), primary_key=True)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), primary_key=True)
__table_args__ = (UniqueConstraint('user_id', 'service_id', name='uix_user_to_service'),)
user_to_organisation = db.Table(
'user_to_organisation',
db.Model.metadata,
db.Column('user_id', UUID(as_uuid=True), db.ForeignKey('users.id')),
db.Column('organisation_id', UUID(as_uuid=True), db.ForeignKey('organisation.id')),
UniqueConstraint('user_id', 'organisation_id', name='uix_user_to_organisation'),
)
user_folder_permissions = db.Table(
'user_folder_permissions',
db.Model.metadata,
db.Column('user_id', UUID(as_uuid=True), primary_key=True),
db.Column('template_folder_id', UUID(as_uuid=True), db.ForeignKey('template_folder.id'), primary_key=True),
db.Column('service_id', UUID(as_uuid=True), primary_key=True),
db.ForeignKeyConstraint(['user_id', 'service_id'], ['user_to_service.user_id', 'user_to_service.service_id']),
db.ForeignKeyConstraint(['template_folder_id', 'service_id'], ['template_folder.id', 'template_folder.service_id']),
)
BRANDING_GOVUK = 'govuk' # Deprecated outside migrations
BRANDING_ORG = 'org'
BRANDING_BOTH = 'both'
BRANDING_ORG_BANNER = 'org_banner'
BRANDING_NO_BRANDING = 'no_branding'
BRANDING_TYPES = [BRANDING_ORG, BRANDING_BOTH, BRANDING_ORG_BANNER, BRANDING_NO_BRANDING]
class BrandingTypes(db.Model):
__tablename__ = 'branding_type'
name = db.Column(db.String(255), primary_key=True)
class EmailBranding(db.Model):
__tablename__ = 'email_branding'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
colour = db.Column(db.String(7), nullable=True)
logo = db.Column(db.String(255), nullable=True)
name = db.Column(db.String(255), unique=True, nullable=False)
text = db.Column(db.String(255), nullable=True)
brand_type = db.Column(
db.String(255), db.ForeignKey('branding_type.name'), index=True, nullable=False, default=BRANDING_ORG
)
def serialize(self):
serialized = {
'id': str(self.id),
'colour': self.colour,
'logo': self.logo,
'name': self.name,
'text': self.text,
'brand_type': self.brand_type,
}
return serialized
service_email_branding = db.Table(
'service_email_branding',
db.Model.metadata,
# service_id is a primary key as you can only have one email branding per service
db.Column('service_id', UUID(as_uuid=True), db.ForeignKey('services.id'), primary_key=True, nullable=False),
db.Column('email_branding_id', UUID(as_uuid=True), db.ForeignKey('email_branding.id'), nullable=False),
)
INTERNATIONAL_SMS_TYPE = 'international_sms'
INBOUND_SMS_TYPE = 'inbound_sms'
SCHEDULE_NOTIFICATIONS = 'schedule_notifications'
EMAIL_AUTH = 'email_auth'
LETTERS_AS_PDF = 'letters_as_pdf'
PRECOMPILED_LETTER = 'precompiled_letter'
UPLOAD_DOCUMENT = 'upload_document'
EDIT_FOLDER_PERMISSIONS = 'edit_folder_permissions'
UPLOAD_LETTERS = 'upload_letters'
SERVICE_PERMISSION_TYPES = [
EMAIL_TYPE,
SMS_TYPE,
LETTER_TYPE,
PUSH_TYPE,
INTERNATIONAL_SMS_TYPE,
INBOUND_SMS_TYPE,
SCHEDULE_NOTIFICATIONS,
EMAIL_AUTH,
LETTERS_AS_PDF,
UPLOAD_DOCUMENT,
EDIT_FOLDER_PERMISSIONS,
UPLOAD_LETTERS,
]
class ServicePermissionTypes(db.Model):
__tablename__ = 'service_permission_types'
name = db.Column(db.String(255), primary_key=True)
class Domain(db.Model):
__tablename__ = 'domain'
domain = db.Column(db.String(255), primary_key=True)
organisation_id = db.Column('organisation_id', UUID(as_uuid=True), db.ForeignKey('organisation.id'), nullable=False)
ORGANISATION_TYPES = [
'other',
]
class OrganisationTypes(db.Model):
__tablename__ = 'organisation_types'
name = db.Column(db.String(255), primary_key=True)
is_crown = db.Column(db.Boolean, nullable=True)
annual_free_sms_fragment_limit = db.Column(db.BigInteger, nullable=False)
class Organisation(db.Model):
__tablename__ = 'organisation'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=False)
name = db.Column(db.String(255), nullable=False, unique=True, index=True)
active = db.Column(db.Boolean, nullable=False, default=True)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.datetime.utcnow)
agreement_signed = db.Column(db.Boolean, nullable=True)
agreement_signed_at = db.Column(db.DateTime, nullable=True)
agreement_signed_by_id = db.Column(
UUID(as_uuid=True),
db.ForeignKey('users.id'),
nullable=True,
)
agreement_signed_by = db.relationship('User')
agreement_signed_on_behalf_of_name = db.Column(db.String(255), nullable=True)
agreement_signed_on_behalf_of_email_address = db.Column(db.String(255), nullable=True)
agreement_signed_version = db.Column(db.Float, nullable=True)
crown = db.Column(db.Boolean, nullable=True)
organisation_type = db.Column(
db.String(255),
db.ForeignKey('organisation_types.name'),
unique=False,
nullable=True,
)
request_to_go_live_notes = db.Column(db.Text)
domains = db.relationship(
'Domain',
)
email_branding = db.relationship('EmailBranding')
email_branding_id = db.Column(
UUID(as_uuid=True),
db.ForeignKey('email_branding.id'),
nullable=True,
)
@property
def live_services(self):
return [service for service in self.services if service.active and not service.restricted]
@property
def domain_list(self):
return [domain.domain for domain in self.domains]
def serialize(self):
return {
'id': str(self.id),
'name': self.name,
'active': self.active,
'crown': self.crown,
'organisation_type': self.organisation_type,
'email_branding_id': self.email_branding_id,
'agreement_signed': self.agreement_signed,
'agreement_signed_at': self.agreement_signed_at,
'agreement_signed_by_id': self.agreement_signed_by_id,
'agreement_signed_on_behalf_of_name': self.agreement_signed_on_behalf_of_name,
'agreement_signed_on_behalf_of_email_address': self.agreement_signed_on_behalf_of_email_address,
'agreement_signed_version': self.agreement_signed_version,
'domains': self.domain_list,
'request_to_go_live_notes': self.request_to_go_live_notes,
'count_of_live_services': len(self.live_services),
}
def serialize_for_list(self):
return {
'name': self.name,
'id': str(self.id),
'active': self.active,
'count_of_live_services': len(self.live_services),
'domains': self.domain_list,
'organisation_type': self.organisation_type,
}
class ProviderDetails(db.Model):
__tablename__ = 'provider_details'
NOTIFICATION_TYPE = [EMAIL_TYPE, SMS_TYPE, LETTER_TYPE]
notification_types = db.Enum(*NOTIFICATION_TYPE, name='notification_type')
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
display_name = db.Column(db.String, nullable=False)
identifier = db.Column(db.String, nullable=False)
priority = db.Column(db.Integer, nullable=False)
load_balancing_weight = db.Column(db.Integer, nullable=True)
notification_type = db.Column(notification_types, nullable=False)
active = db.Column(db.Boolean, default=False, nullable=False)
version = db.Column(db.Integer, default=1, nullable=False)
updated_at = db.Column(
db.DateTime, nullable=False, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow
)
created_by_id = db.Column(UUID(as_uuid=True), db.ForeignKey('users.id'), index=True, nullable=True)
created_by = db.relationship('User')
supports_international = db.Column(db.Boolean, nullable=False, default=False)
class Service(db.Model, Versioned):
__tablename__ = 'services'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = db.Column(db.String(255), nullable=False, unique=True)
created_at = db.Column(db.DateTime, index=False, unique=False, nullable=False, default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime, index=False, unique=False, nullable=True, onupdate=datetime.datetime.utcnow)
active = db.Column(db.Boolean, index=False, unique=False, nullable=False, default=True)
message_limit = db.Column(db.BigInteger, index=False, unique=False, nullable=False)
restricted = db.Column(db.Boolean, index=False, unique=False, nullable=False)
research_mode = db.Column(db.Boolean, index=False, unique=False, nullable=False, default=False)
email_from = db.Column(db.Text, index=False, unique=False, nullable=True)
created_by_id = db.Column(UUID(as_uuid=True), db.ForeignKey('users.id'), index=True, nullable=False)
created_by = db.relationship('User', foreign_keys=[created_by_id])
prefix_sms = db.Column(db.Boolean, nullable=False, default=False)
organisation_type = db.Column(
db.String(255),
db.ForeignKey('organisation_types.name'),
unique=False,
nullable=True,
)
crown = db.Column(db.Boolean, index=False, nullable=True)
rate_limit = db.Column(db.Integer, index=False, nullable=False, default=3000)
contact_link = db.Column(db.String(255), nullable=True, unique=False)
volume_sms = db.Column(db.Integer(), nullable=True, unique=False)
volume_email = db.Column(db.Integer(), nullable=True, unique=False)
volume_letter = db.Column(db.Integer(), nullable=True, unique=False)
consent_to_research = db.Column(db.Boolean, nullable=True)
count_as_live = db.Column(db.Boolean, nullable=False, default=True)
go_live_user_id = db.Column(UUID(as_uuid=True), db.ForeignKey('users.id'), nullable=True)
go_live_user = db.relationship('User', foreign_keys=[go_live_user_id])
go_live_at = db.Column(db.DateTime, nullable=True)
sending_domain = db.Column(db.String(255), nullable=True, unique=False)
smtp_user = db.Column(db.String(255), nullable=True, unique=False)
email_provider_id = db.Column(UUID(as_uuid=True), db.ForeignKey('provider_details.id'), nullable=True)
sms_provider_id = db.Column(UUID(as_uuid=True), db.ForeignKey('provider_details.id'), nullable=True)
organisation_id = db.Column(UUID(as_uuid=True), db.ForeignKey('organisation.id'), index=True, nullable=True)
organisation = db.relationship('Organisation', backref='services')
p2p_enabled = db.Column(db.Boolean, nullable=True, default=False)
email_branding = db.relationship(
'EmailBranding', secondary=service_email_branding, uselist=False, backref=db.backref('services', lazy='dynamic')
)
@classmethod
def from_json(
cls,
data,
):
"""
Assumption: data has been validated appropriately.
Returns a Service object based on the provided data. Deserialises created_by to created_by_id as marshmallow
would.
"""
# validate json with marshmallow
fields = data.copy()
fields['created_by_id'] = fields.pop('created_by')
return cls(**fields)
def get_default_sms_sender(self):
"""
service_sms_senders is a back reference from the ServiceSmsSender table.
"""
# there should only be one default sms sender per service
for sms_sender in self.service_sms_senders:
if sms_sender.is_default:
return sms_sender.sms_sender
return None
def get_default_sms_sender_id(self):
"""
service_sms_senders is a back reference from the ServiceSmsSender table.
"""
# there should only be one default sms sender per service
for sms_sender in self.service_sms_senders:
if sms_sender.is_default:
return sms_sender.id
return None
def get_default_reply_to_email_address(self):
# there should only be one default reply to email per service
for default_reply_to in self.reply_to_email_addresses:
if default_reply_to.is_default:
return default_reply_to.email_address
return None
def get_default_letter_contact(self):
# there should only be one default letter contact per service
for default_letter_contact in self.letter_contacts:
if default_letter_contact.is_default:
return default_letter_contact.contact_block
return None
def has_permissions(
self,
permissions_to_check_for,
):
if isinstance(permissions_to_check_for, InstrumentedList):
_permissions_to_check_for = [p.permission for p in permissions_to_check_for]
elif not isinstance(permissions_to_check_for, list):
_permissions_to_check_for = [permissions_to_check_for]
else:
_permissions_to_check_for = permissions_to_check_for
if isinstance(self.permissions, InstrumentedList):
_permissions = [p.permission for p in self.permissions]
else:
_permissions = self.permissions
return frozenset(_permissions_to_check_for).issubset(frozenset(_permissions))
def serialize_for_org_dashboard(self):
return {
'id': str(self.id),
'name': self.name,
'active': self.active,
'restricted': self.restricted,
'research_mode': self.research_mode,
}
def serialize_for_user(self):
return {'id': str(self.id), 'name': self.name, 'research_mode': self.research_mode}
class ReplyToInbox(db.Model):
__tablename__ = 'reply_to_inbox'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
inbox = db.Column(db.String, nullable=False)
service = db.relationship(Service)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), nullable=False, index=True, unique=False)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.datetime.utcnow)
class Session(db.Model):
__tablename__ = 'sessions'
id = db.Column(db.Integer, primary_key=True)
session_id = db.Column(db.String, nullable=False, index=True)
data = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime, nullable=True, index=True, onupdate=datetime.datetime.utcnow)
class TemplateP2PChecklist(db.Model):
__tablename__ = 'template_p2p_checklist'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
template_id = db.Column(UUID(as_uuid=True), db.ForeignKey('templates.id'), nullable=False, index=True, unique=False)
checklist = db.Column(JSONB)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.datetime.utcnow)
class AnnualBilling(db.Model):
__tablename__ = 'annual_billing'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=False)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), unique=False, index=True, nullable=False)
financial_year_start = db.Column(db.Integer, nullable=False, default=True, unique=False)
free_sms_fragment_limit = db.Column(db.Integer, nullable=False, index=False, unique=False)
updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.datetime.utcnow)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
UniqueConstraint('financial_year_start', 'service_id', name='ix_annual_billing_service_id')
service = db.relationship(Service, backref=db.backref('annual_billing', uselist=True))
def serialize_free_sms_items(self):
return {
'free_sms_fragment_limit': self.free_sms_fragment_limit,
'financial_year_start': self.financial_year_start,
}
def serialize(self):
def serialize_service():
return {'id': str(self.service_id), 'name': self.service.name}
return {
'id': str(self.id),
'free_sms_fragment_limit': self.free_sms_fragment_limit,
'service_id': self.service_id,
'financial_year_start': self.financial_year_start,
'created_at': self.created_at.strftime(DATETIME_FORMAT),
'updated_at': self.updated_at.strftime(DATETIME_FORMAT) if self.updated_at else None,
'service': serialize_service() if self.service else None,
}
class InboundNumber(db.Model):
__tablename__ = 'inbound_numbers'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
number = db.Column(db.String(12), unique=True, nullable=False)
provider = db.Column(db.String(), nullable=False)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), index=True, nullable=True)
service = db.relationship(Service, backref=db.backref('inbound_numbers', uselist=True))
active = db.Column(db.Boolean, index=False, unique=False, nullable=False, default=True)
created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, nullable=False)
updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.datetime.utcnow)
url_endpoint = db.Column(db.String(), nullable=True)
self_managed = db.Column(db.Boolean, nullable=False, default=False)
auth_parameter = db.Column(db.String(), nullable=True)
def serialize(self):
return {
'id': str(self.id),
'number': self.number,
'provider': self.provider,
'service': {
'id': str(self.service_id),
'name': self.service.name,
}
if self.service
else None,
'active': self.active,
'url_endpoint': self.url_endpoint,
'self_managed': self.self_managed,
'auth_parameter': self.auth_parameter,
}
class ServiceSmsSender(db.Model):
"""Define the service_sms_senders table."""
__tablename__ = 'service_sms_senders'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
archived = db.Column(db.Boolean, nullable=False, default=False)
created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, nullable=False)
description = db.Column(db.String(256))
inbound_number = db.relationship(InboundNumber, backref=db.backref('inbound_number', uselist=False))
inbound_number_id = db.Column(UUID(as_uuid=True), db.ForeignKey('inbound_numbers.id'), unique=True, index=True)
is_default = db.Column(db.Boolean, nullable=False, default=True)
provider = db.relationship(ProviderDetails, backref=db.backref('provider_details'))
provider_id = db.Column(UUID(as_uuid=True), db.ForeignKey('provider_details.id'))
rate_limit = db.Column(db.Integer, nullable=True)
rate_limit_interval = db.Column(db.Integer, nullable=True)
service = db.relationship(Service, backref=db.backref('service_sms_senders', uselist=True))
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), index=True, nullable=False)
sms_sender = db.Column(db.String(12), nullable=False, doc="This is the sender's phone number.")
sms_sender_specifics = db.Column(db.JSON(), doc='A placeholder for any service provider we might want to use.')
updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.datetime.utcnow)
def get_reply_to_text(self):
return try_validate_and_format_phone_number(self.sms_sender)
def serialize(self):
return {
'archived': self.archived,
'created_at': self.created_at.strftime(DATETIME_FORMAT),
'description': self.description,
'id': str(self.id),
'inbound_number_id': str(self.inbound_number_id) if self.inbound_number_id else None,
'is_default': self.is_default,
'provider_id': str(self.provider_id),
'rate_limit': self.rate_limit if self.rate_limit else None,
'rate_limit_interval': self.rate_limit_interval if self.rate_limit_interval else None,
'service_id': str(self.service_id),
'sms_sender': self.sms_sender,
'sms_sender_specifics': self.sms_sender_specifics,
'updated_at': self.updated_at.strftime(DATETIME_FORMAT) if self.updated_at else None,
}
class ServicePermission(db.Model):
__tablename__ = 'service_permissions'
service_id = db.Column(
UUID(as_uuid=True), db.ForeignKey('services.id'), primary_key=True, index=True, nullable=False
)
permission = db.Column(
db.String(255), db.ForeignKey('service_permission_types.name'), index=True, primary_key=True, nullable=False
)
created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, nullable=False)
service_permission_types = db.relationship(Service, backref=db.backref('permissions', cascade='all, delete-orphan'))
def __repr__(self):
return '<{} has service permission: {}>'.format(self.service_id, self.permission)
WHITELIST_RECIPIENT_TYPE = [MOBILE_TYPE, EMAIL_TYPE]
whitelist_recipient_types = db.Enum(*WHITELIST_RECIPIENT_TYPE, name='recipient_type')
class ServiceWhitelist(db.Model):
__tablename__ = 'service_whitelist'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), index=True, nullable=False)
service = db.relationship('Service', backref='whitelist')
recipient_type = db.Column(whitelist_recipient_types, nullable=False)
recipient = db.Column(db.String(255), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
@classmethod
def from_string(
cls,
service_id,
recipient_type,
recipient,
):
instance = cls(service_id=service_id, recipient_type=recipient_type)
try:
if recipient_type == MOBILE_TYPE:
validate_phone_number(recipient, international=True)
instance.recipient = recipient
elif recipient_type == EMAIL_TYPE:
validate_email_address(recipient)
instance.recipient = recipient
else:
raise ValueError('Invalid recipient type')
except InvalidPhoneError:
raise ValueError('Invalid whitelist: "{}"'.format(recipient))
except InvalidEmailError:
raise ValueError('Invalid whitelist: "{}"'.format(recipient))
else:
return instance
def __repr__(self):
return 'Recipient {} of type: {}'.format(self.recipient, self.recipient_type)
class ServiceCallback(db.Model, Versioned):
__tablename__ = 'service_callback'
def __init__(
self,
**kwargs,
):
if 'notification_statuses' not in kwargs:
if kwargs.get('callback_type') == DELIVERY_STATUS_CALLBACK_TYPE:
self.notification_statuses = NOTIFICATION_STATUS_TYPES_COMPLETED
super().__init__(**kwargs)
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), index=True, nullable=False)
service = db.relationship('Service', backref='service_callback')
url = db.Column(db.String(), nullable=False)
callback_type = db.Column(db.String(), db.ForeignKey('service_callback_type.name'), nullable=True)
_bearer_token = db.Column('bearer_token', db.String(), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, nullable=False)
updated_at = db.Column(db.DateTime, nullable=True)
updated_by = db.relationship('User')
updated_by_id = db.Column(UUID(as_uuid=True), db.ForeignKey('users.id'), index=True, nullable=False)
notification_statuses = db.Column('notification_statuses', JSONB, nullable=True)
callback_channel = db.Column(db.String(), db.ForeignKey('service_callback_channel.channel'), nullable=False)
include_provider_payload = db.Column(db.Boolean, nullable=False, default=False)
__table_args__ = (
UniqueConstraint('service_id', 'callback_type', name='uix_service_callback_type'),
UniqueConstraint('service_id', 'callback_channel', name='uix_service_callback_channel'),
)
@property
def bearer_token(self):
if self._bearer_token:
return encryption.decrypt(self._bearer_token)
return None
@bearer_token.setter
def bearer_token(
self,
bearer_token,
):
if bearer_token:
self._bearer_token = encryption.encrypt(str(bearer_token))
def send(
self,
payload: dict,
logging_tags: dict,
):
from app.callback.queue_callback_strategy import QueueCallbackStrategy
from app.callback.webhook_callback_strategy import WebhookCallbackStrategy
callback_strategies = {WEBHOOK_CHANNEL_TYPE: WebhookCallbackStrategy, QUEUE_CHANNEL_TYPE: QueueCallbackStrategy}
strategy = callback_strategies[self.callback_channel]
strategy.send_callback(self, payload, logging_tags)
class ServiceCallbackType(db.Model):
__tablename__ = 'service_callback_type'
name = db.Column(db.String, primary_key=True)
class ServiceCallbackChannel(db.Model):
__tablename__ = 'service_callback_channel'
channel = db.Column(db.String, primary_key=True)
class ApiKey(db.Model, Versioned):
__tablename__ = 'api_keys'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = db.Column(db.String(255), nullable=False)
_secret = db.Column('secret', db.String(255), unique=True, nullable=False)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), index=True, nullable=False)
service = db.relationship('Service', backref='api_keys')
key_type = db.Column(db.String(255), db.ForeignKey('key_types.name'), index=True, nullable=False)
expiry_date = db.Column(db.DateTime)
created_at = db.Column(db.DateTime, index=False, unique=False, nullable=False, default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime, index=False, unique=False, nullable=True, onupdate=datetime.datetime.utcnow)
created_by = db.relationship('User')
created_by_id = db.Column(UUID(as_uuid=True), db.ForeignKey('users.id'), index=True, nullable=False)
__table_args__ = (
Index('uix_service_to_key_name', 'service_id', 'name', unique=True, postgresql_where=expiry_date.is_(None)),
)
@property
def secret(self):
if self._secret:
return encryption.decrypt(self._secret)
return None
@secret.setter
def secret(
self,
secret,
):
if secret:
self._secret = encryption.encrypt(str(secret))
KEY_TYPE_NORMAL = 'normal'
KEY_TYPE_TEAM = 'team'
KEY_TYPE_TEST = 'test'
class KeyTypes(db.Model):
__tablename__ = 'key_types'
name = db.Column(db.String(255), primary_key=True)
class TemplateProcessTypes(db.Model):
__tablename__ = 'template_process_type'
name = db.Column(db.String(255), primary_key=True)
class TemplateFolder(db.Model):
__tablename__ = 'template_folder'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
service_id = db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), nullable=False)
name = db.Column(db.String, nullable=False)
parent_id = db.Column(UUID(as_uuid=True), db.ForeignKey('template_folder.id'), nullable=True)
service = db.relationship('Service', backref='all_template_folders')
parent = db.relationship('TemplateFolder', remote_side=[id], backref='subfolders')
users = db.relationship(
'ServiceUser',
uselist=True,
backref=db.backref('folders', foreign_keys='user_folder_permissions.c.template_folder_id'),
secondary='user_folder_permissions',
primaryjoin='TemplateFolder.id == user_folder_permissions.c.template_folder_id',
)
__table_args__ = (UniqueConstraint('id', 'service_id', name='ix_id_service_id'), {})
def serialize(self):
return {
'id': self.id,
'name': self.name,
'parent_id': self.parent_id,
'service_id': self.service_id,
'users_with_permission': self.get_users_with_permission(),
}
def is_parent_of(
self,
other,
):
while other.parent is not None:
if other.parent == self:
return True
other = other.parent
return False
def get_users_with_permission(self):
service_users = self.users
users_with_permission = [str(service_user.user_id) for service_user in service_users]
return users_with_permission
template_folder_map = db.Table(
'template_folder_map',
db.Model.metadata,
# template_id is a primary key as a template can only belong in one folder
db.Column('template_id', UUID(as_uuid=True), db.ForeignKey('templates.id'), primary_key=True, nullable=False),
db.Column('template_folder_id', UUID(as_uuid=True), db.ForeignKey('template_folder.id'), nullable=False),
)
PRECOMPILED_TEMPLATE_NAME = 'Pre-compiled PDF'
class TemplateBase(db.Model):
__abstract__ = True
def __init__(
self,
**kwargs,
):
if 'template_type' in kwargs:
self.template_type = kwargs.pop('template_type')
super().__init__(**kwargs)
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = db.Column(db.String(255), nullable=False)
template_type = db.Column(template_types, nullable=False)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime, onupdate=datetime.datetime.utcnow)
content = db.Column(db.Text, nullable=False)
archived = db.Column(db.Boolean, nullable=False, default=False)
hidden = db.Column(db.Boolean, nullable=False, default=False)
onsite_notification = db.Column(db.Boolean, nullable=False, default=False)
subject = db.Column(db.Text)
postage = db.Column(db.String, nullable=True)
reply_to_email = db.Column(db.String(254), nullable=True)
CheckConstraint(
"""
CASE WHEN template_type = 'letter' THEN
postage is not null and postage in ('first', 'second')
ELSE
postage is null
END
"""
)
@declared_attr
def provider_id(cls):
return db.Column(UUID(as_uuid=True), db.ForeignKey('provider_details.id'), nullable=True)
@declared_attr
def communication_item_id(cls):
return db.Column(UUID(as_uuid=True), db.ForeignKey('communication_items.id'), nullable=True)
@declared_attr
def service_id(cls):
return db.Column(UUID(as_uuid=True), db.ForeignKey('services.id'), index=True, nullable=False)
@declared_attr
def created_by_id(cls):
return db.Column(UUID(as_uuid=True), db.ForeignKey('users.id'), index=True, nullable=False)
@declared_attr
def created_by(cls):
return db.relationship('User')
@declared_attr
def process_type(cls):
return db.Column(
db.String(255), db.ForeignKey('template_process_type.name'), index=True, nullable=False, default=NORMAL
)
redact_personalisation = association_proxy('template_redacted', 'redact_personalisation')
@declared_attr
def service_letter_contact_id(cls):
return db.Column(UUID(as_uuid=True), db.ForeignKey('service_letter_contacts.id'), nullable=True)
@declared_attr
def service_letter_contact(cls):
return db.relationship('ServiceLetterContact', viewonly=True)
@property
def reply_to(self):
if self.template_type == LETTER_TYPE:
return self.service_letter_contact_id
else:
return None
@reply_to.setter
def reply_to(
self,
value,
):
if self.template_type == LETTER_TYPE:
self.service_letter_contact_id = value
elif value is None:
pass
else:
raise ValueError('Unable to set sender for {} template'.format(self.template_type))
def get_reply_to_text(self) -> str:
if self.template_type == LETTER_TYPE:
return self.service_letter_contact.contact_block if self.service_letter_contact else None
elif self.template_type == EMAIL_TYPE:
return self.service.get_default_reply_to_email_address()
elif self.template_type == SMS_TYPE:
return try_validate_and_format_phone_number(self.service.get_default_sms_sender())
else:
return None
# https://docs.sqlalchemy.org/en/13/orm/extensions/hybrid.html
# https://stackoverflow.com/questions/55690796/sqlalchemy-typeerror-boolean-value-of-this-clause-is-not-defined/55692795#55692795
@hybrid_property
def is_precompiled_letter(self):
"""
This is for instance level evaluation.
"""
return self.hidden and self.name == PRECOMPILED_TEMPLATE_NAME and self.template_type == LETTER_TYPE
@is_precompiled_letter.expression
def is_precompiled_letter(cls):
"""
This is for class level evaluation (i.e. for queries).
"""
return and_(cls.hidden, cls.name == PRECOMPILED_TEMPLATE_NAME, cls.template_type == LETTER_TYPE)
@is_precompiled_letter.setter
def is_precompiled_letter(
self,
value,
):
pass
def _as_utils_template(self):
if self.template_type == EMAIL_TYPE:
return PlainTextEmailTemplate({'content': self.content, 'subject': self.subject})
if self.template_type == SMS_TYPE:
return SMSMessageTemplate({'content': self.content})
if self.template_type == LETTER_TYPE:
return LetterPrintTemplate(
{'content': self.content, 'subject': self.subject},
contact_block=self.service.get_default_letter_contact(),
)
def serialize(self):
serialized = {
'id': str(self.id),
'type': self.template_type,
'created_at': self.created_at.strftime(DATETIME_FORMAT),
'updated_at': self.updated_at.strftime(DATETIME_FORMAT) if self.updated_at else None,
'created_by': self.created_by.email_address,
'version': self.version,
'body': self.content,
'subject': self.subject if self.template_type != SMS_TYPE else None,
'name': self.name,
'personalisation': {
key: {
'required': True,
}
for key in self._as_utils_template().placeholders
},
'postage': self.postage,
}
return serialized
class Template(TemplateBase):
__tablename__ = 'templates'
service = db.relationship('Service', backref='templates')
version = db.Column(db.Integer, default=0, nullable=False)
folder = db.relationship(
'TemplateFolder',
secondary=template_folder_map,
uselist=False,
# eagerly load the folder whenever the template object is fetched
lazy='joined',
backref=db.backref('templates'),
)