forked from bcgov/sbc-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorg.py
More file actions
1146 lines (982 loc) · 48.8 KB
/
org.py
File metadata and controls
1146 lines (982 loc) · 48.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
# Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Service for managing Organization data."""
# pylint:disable=too-many-lines
import json
from datetime import datetime
from http import HTTPStatus
from flask import current_app, request
from jinja2 import Environment, FileSystemLoader
from requests.exceptions import HTTPError
from sbc_common_components.utils.enums import QueueMessageTypes
from auth_api.exceptions import BusinessException
from auth_api.exceptions.errors import Error
from auth_api.models import AccountLoginOptions as AccountLoginOptionsModel
from auth_api.models import Contact as ContactModel
from auth_api.models import ContactLink as ContactLinkModel
from auth_api.models import Membership as MembershipModel
from auth_api.models import Org as OrgModel
from auth_api.models import Task as TaskModel
from auth_api.models import User as UserModel
from auth_api.models.affidavit import Affidavit as AffidavitModel
from auth_api.models.dataclass import Activity, DeleteAffiliationRequest
from auth_api.models.org import OrgSearch
from auth_api.schemas import ContactSchema, InvitationSchema, MembershipSchema, OrgSchema
from auth_api.services.membership import Membership
from auth_api.services.user import User as UserService
from auth_api.services.validators.access_type import validate as access_type_validate
from auth_api.services.validators.account_limit import validate as account_limit_validate
from auth_api.services.validators.bcol_credentials import validate as bcol_credentials_validate
from auth_api.services.validators.duplicate_org_name import validate as duplicate_org_name_validate
from auth_api.services.validators.payment_type import validate as payment_type_validate
from auth_api.utils.account_mailer import publish_to_mailer
from auth_api.utils.enums import (
AccessType,
ActivityAction,
AffidavitStatus,
LoginSource,
OrgStatus,
OrgType,
PatchActions,
PaymentAccountStatus,
PaymentMethod,
Status,
SuspensionReasonCode,
TaskAction,
TaskRelationshipStatus,
TaskRelationshipType,
TaskStatus,
TaskTypePrefix,
)
from auth_api.utils.roles import ADMIN, EXCLUDED_FIELDS, STAFF, VALID_STATUSES, Role # noqa: I001
from auth_api.utils.user_context import UserContext, user_context
from auth_api.utils.util import camelback2snake
from .activity_log_publisher import ActivityLogPublisher
from .affidavit import Affidavit as AffidavitService
from .authorization import check_auth
from .contact import Contact as ContactService
from .keycloak import KeycloakService
from .products import Product as ProductService
from .rest_service import RestService
from .task import Task as TaskService
from .validators.validator_response import ValidatorResponse # noqa: TC001
ENV = Environment(loader=FileSystemLoader("."), autoescape=True)
class Org: # pylint: disable=too-many-public-methods
"""Manages all aspects of Org data.
This service manages creating, updating, and retrieving Org data via the Org model.
"""
def __init__(self, model):
"""Return an Org Service."""
self._model = model
def as_dict(self):
"""Return the internal Org model as a dictionary.
None fields are not included.
"""
org_schema = OrgSchema()
obj = org_schema.dump(self._model, many=False)
return obj
@staticmethod
def create_org(org_info: dict, user_id):
"""Create a new organization."""
current_app.logger.debug("<create_org ")
if Membership.has_nsf_or_suspended_membership(user_id):
raise BusinessException(Error.NSF_OR_SUSPENDED_CLIENT_CANNOT_CREATE_ACCOUNT, None)
# bcol is treated like an access type as well;so its outside the scheme
mailing_address = org_info.pop("mailingAddress", None)
product_subscriptions = org_info.pop("productSubscriptions", None)
payment_info = org_info.pop("paymentInfo", {})
type_code = org_info.get("typeCode", None)
bcol_profile_flags = None
response = Org._validate_and_raise_error(org_info)
# If the account is created using BCOL credential, verify its valid bc online account
bcol_details_response = response.get("bcol_response", None)
if bcol_details_response is not None and (bcol_details := bcol_details_response.json()) is not None:
Org._map_response_to_org(bcol_details, org_info)
bcol_profile_flags = bcol_details.get("profileFlags")
access_type = response.get("access_type")
# set premium for GOVM accounts..TODO remove if not needed this logic
# Depreciating BASIC accounts with backwards compatibility
if access_type == AccessType.GOVM.value or type_code == OrgType.BASIC.value:
org_info.update({"typeCode": OrgType.PREMIUM.value})
org = OrgModel.create_from_dict(camelback2snake(org_info))
org.access_type = access_type
# Set the status based on access type
# Check if the user is APPROVED else set the org status to PENDING
if access_type == AccessType.GOVM.value:
org.status_code = OrgStatus.PENDING_INVITE_ACCEPT.value
# If mailing address is provided, save it
if mailing_address:
Org.add_contact_to_org(mailing_address, org)
# create the membership record for this user if its not created by staff and access_type is anonymous
Org.create_membership(org, user_id)
# Send an email to staff to remind review the pending account
is_staff_review_needed = access_type == AccessType.GOVN.value or (
access_type in (AccessType.EXTRA_PROVINCIAL.value, AccessType.REGULAR_BCEID.value)
and not AffidavitModel.find_approved_by_user_id(user_id=user_id)
and current_app.config.get("SKIP_STAFF_APPROVAL_BCEID") is False
)
if product_subscriptions is not None:
ProductService.create_product_subscription(
org.id, subscription_data={"subscriptions": product_subscriptions}, skip_auth=True, staff_review_for_create_org=is_staff_review_needed
)
ProductService.create_subscription_from_bcol_profile(org.id, bcol_profile_flags)
payment_account_status, error = Org._create_payment_for_org(mailing_address, org, payment_info, True)
if payment_account_status == PaymentAccountStatus.FAILED and error is not None:
current_app.logger.warning(f"Account update payment Error: {error}")
if is_staff_review_needed:
Org._create_staff_review_task(org, UserModel.find_by_jwt_token())
else:
Org._send_account_created_notification(org, UserModel.find_by_jwt_token())
org.commit()
ProductService.update_org_product_keycloak_groups(org.id)
current_app.logger.info(f"<created_org org_id:{org.id}")
return Org(org)
@staticmethod
def _create_staff_review_task(org: OrgModel, user: UserModel):
org.status_code = OrgStatus.PENDING_STAFF_REVIEW.value
# create a staff review task for this account
task_type = (
TaskTypePrefix.GOVN_REVIEW.value
if org.access_type == AccessType.GOVN.value
else TaskTypePrefix.NEW_ACCOUNT_STAFF_REVIEW.value
)
action = (
TaskAction.AFFIDAVIT_REVIEW.value
if user.login_source == LoginSource.BCEID.value
else TaskAction.ACCOUNT_REVIEW.value
)
task_info = {
"name": org.name,
"relationshipId": org.id,
"relatedTo": user.id,
"dateSubmitted": datetime.today(),
"relationshipType": TaskRelationshipType.ORG.value,
"type": task_type,
"action": action,
"status": TaskStatus.OPEN.value,
"relationship_status": TaskRelationshipStatus.PENDING_STAFF_REVIEW.value,
}
TaskService.create_task(task_info=task_info, do_commit=False)
Org.send_staff_review_account_reminder(relationship_id=org.id)
@staticmethod
def _send_account_created_notification(org: OrgModel, user: UserModel):
"""Send account created notification to the user."""
current_app.logger.debug("<_send_account_created_notification")
app_url = current_app.config.get("WEB_APP_URL")
recipients = UserService.get_admin_emails_for_org(org.id)
login_source = user.login_source
if not recipients:
current_app.logger.warning(f"No recipient found for org {org.id}")
return
data = {
"accountId": org.id,
"orgName": org.name,
"emailAddresses": recipients,
"contextUrl": app_url,
"loginSource": login_source,
}
try:
publish_to_mailer(QueueMessageTypes.ACCOUNT_CREATED_NOTIFICATION.value, data=data)
current_app.logger.debug("_send_account_created_notification>")
except Exception as e: # noqa: B901
current_app.logger.warning(f"_send_account_created_notification failed: {e}")
@staticmethod
@user_context
def create_membership(org, user_id, **kwargs):
"""Create membership account."""
user: UserContext = kwargs["user_context"]
if not user.is_staff_admin():
membership = MembershipModel(
org_id=org.id, user_id=user_id, membership_type_code="ADMIN", membership_type_status=Status.ACTIVE.value
)
membership.add_to_session()
# Add the user to account_holders group
KeycloakService.join_account_holders_group()
@staticmethod
def _get_payment_method_descriptions(current_payment_method: str, new_payment_method: str) -> str:
"""Get payment method descriptions for activity logging."""
valid_payment_methods = [item.value for item in PaymentMethod]
new_method_description = (
PaymentMethod(new_payment_method).name if new_payment_method in valid_payment_methods else ""
)
if not current_payment_method:
return new_method_description
current_method_description = (
PaymentMethod(current_payment_method).name if current_payment_method in valid_payment_methods else ""
)
return f"{current_method_description}|{new_method_description}"
@staticmethod
def _handle_pay_http_error_raise_business_exception(http_error: HTTPError) -> None:
"""Handle HTTP error by extracting error info and raising BusinessException."""
error_payload = http_error.response.json()
error_code = next(
(error_payload[key] for key in ["error", "code"] if key in error_payload),
Error.PAYMENT_ACCOUNT_UPSERT_FAILED,
)
error_details = next(
(
error_payload[key]
for key in ["error_description", "message", "description", "type"]
if key in error_payload
),
"",
)
current_app.logger.error(f"Account create payment Error: {http_error}")
raise BusinessException(error_code, error_details) from http_error
@staticmethod
@user_context
def _create_payment_settings(
org_model: OrgModel,
payment_info: dict, # pylint: disable=too-many-positional-arguments
payment_method: str,
mailing_address=None,
is_new_org: bool = True,
**kwargs,
):
"""Add payment settings for the org."""
try:
pay_url = current_app.config.get("PAY_API_URL")
pay_request = Org._build_payment_request(org_model, payment_info, payment_method, mailing_address, **kwargs)
error_code = None
token = RestService.get_service_account_token()
user_from_context: UserContext = kwargs["user_context"]
additional_headers = {
"Original-Username": user_from_context.user_name or "",
"Original-Sub": str(user_from_context.sub or ""),
}
if is_new_org:
response = RestService.post(
endpoint=f"{pay_url}/accounts",
data=pay_request,
token=token,
raise_for_status=True,
additional_headers=additional_headers,
)
else:
response = RestService.put(
endpoint=f"{pay_url}/accounts/{org_model.id}",
data=pay_request,
token=token,
raise_for_status=True,
additional_headers=additional_headers,
)
match response.status_code:
case HTTPStatus.OK | HTTPStatus.CREATED:
payment_account_status = PaymentAccountStatus.CREATED
case HTTPStatus.ACCEPTED:
payment_account_status = PaymentAccountStatus.PENDING
case _:
payment_account_status = PaymentAccountStatus.FAILED
error_code = getattr(response, "json", lambda: {})().get("error", "UNKNOWN_ERROR")
current_app.logger.error(f"Account create payment Error: {response.text}")
return payment_account_status, error_code
except HTTPError as http_error:
return Org._handle_pay_http_error_raise_business_exception(http_error)
@staticmethod
def _build_payment_request(org_model: OrgModel, payment_info: dict, payment_method: str, mailing_address, **kwargs):
"""Build the payment request payload."""
org_name_for_pay = f"{org_model.name}-{org_model.branch_name}" if org_model.branch_name else org_model.name
pay_request = {
"accountId": org_model.id,
# pay needs the most unique idenitfier.So combine name and branch name
"accountName": org_name_for_pay,
"branchName": org_model.branch_name or "",
}
if payment_method:
pay_request["paymentInfo"] = {"methodOfPayment": payment_method}
if mailing_address:
pay_request["contactInfo"] = mailing_address
if payment_method and org_model.bcol_account_id:
pay_request["bcolAccountNumber"] = org_model.bcol_account_id
pay_request["bcolUserId"] = org_model.bcol_user_id
if (revenue_account := payment_info.get("revenueAccount")) is not None:
pay_request.setdefault("paymentInfo", {})
pay_request["paymentInfo"]["revenueAccount"] = revenue_account
if payment_method == PaymentMethod.PAD.value: # PAD has bank-related details
pay_request["paymentInfo"].update(
{
"bankTransitNumber": payment_info.get("bankTransitNumber"),
"bankInstitutionNumber": payment_info.get("bankInstitutionNumber"),
"bankAccountNumber": payment_info.get("bankAccountNumber"),
}
)
pay_request["padTosAcceptedBy"] = kwargs["user_context"].user_name
return pay_request
@staticmethod
def _validate_and_raise_error(org_info: dict):
"""Execute the validators in chain and raise error or return."""
validators = [account_limit_validate, access_type_validate, duplicate_org_name_validate]
arg_dict = {
"accessType": org_info.get("accessType", None),
"name": org_info.get("name"),
"branch_name": org_info.get("branchName"),
}
if (bcol_credential := org_info.pop("bcOnlineCredential", None)) is not None:
validators.insert(0, bcol_credentials_validate) # first validator should be bcol ,thus 0th position
arg_dict["bcol_credential"] = bcol_credential
validator_response_list: list[ValidatorResponse] = []
for validate in validators:
validator_response_list.append(validate(**arg_dict))
not_valid_obj = next((x for x in validator_response_list if getattr(x, "is_valid", None) is False), None)
if not_valid_obj:
raise BusinessException(not_valid_obj.error[0], None)
response: dict = {}
for val in validator_response_list:
response.update(val.info)
return response
@staticmethod
def _get_default_payment_method_for_creditcard():
return PaymentMethod.DIRECT_PAY.value
@staticmethod
def get_bcol_details(bcol_credential: dict, org_id=None):
"""Retrieve and validate BC Online credentials."""
arg_dict = {"bcol_credential": bcol_credential, "org_id": org_id}
validator_obj = bcol_credentials_validate(**arg_dict)
if not validator_obj.is_valid:
raise BusinessException(validator_obj.error[0], None)
return validator_obj.info.get("bcol_response", None)
@staticmethod
def _map_response_to_org(bcol_response, org_info, do_link_name=True):
org_info.update(
{
"bcol_account_id": bcol_response.get("accountNumber"),
"bcol_user_id": bcol_response.get("userId"),
}
)
if do_link_name:
org_info.update({"bcol_account_name": bcol_response.get("orgName")})
# New org who linked to BCOL account will use BCOL account name as default name
# Existing account keep their account name to avoid payment info change.
if not org_info.get("name") and do_link_name:
org_info.update({"name": bcol_response.get("orgName")})
@staticmethod
def add_contact_to_org(mailing_address, org):
"""Update the passed organization with the mailing address."""
contact = ContactModel(**camelback2snake(mailing_address))
contact = contact.add_to_session()
contact_link = ContactLinkModel()
contact_link.contact = contact
contact_link.org = org
contact_link.add_to_session()
def update_org(self, org_info): # pylint: disable=too-many-locals, too-many-statements
"""Update the passed organization with the new info."""
current_app.logger.debug("<update_org ")
has_org_updates: bool = False # update the org table if this variable is set true
has_status_changing: bool = False
org_model: OrgModel = self._model
# to enforce necessary details for govm account creation
is_govm_account = org_model.access_type == AccessType.GOVM.value
is_govm_account_creation = is_govm_account and org_model.status_code == OrgStatus.PENDING_INVITE_ACCEPT.value
# validate if name or branch name is getting updatedtest_org.py
branch_name = org_info.get("branchName", None)
org_name = org_info.get("name", None)
current_org_name = org_name or org_model.name
name_updated = branch_name or org_name
if name_updated:
arg_dict = {"name": current_org_name, "branch_name": branch_name, "org_id": org_model.id}
duplicate_org_name_validate(is_fatal=True, **arg_dict)
# If the account is created using BCOL credential, verify its valid bc online account
# If it's a valid account disable the current one and add a new one
if bcol_credential := org_info.pop("bcOnlineCredential", None):
bcol_response = Org.get_bcol_details(bcol_credential, self._model.id).json()
Org._map_response_to_org(bcol_response, org_info, do_link_name=False)
ProductService.create_subscription_from_bcol_profile(org_model.id, bcol_response.get("profileFlags"))
has_org_updates = True
product_subscriptions = org_info.pop("productSubscriptions", None)
mailing_address = org_info.pop("mailingAddress", None)
payment_info = org_info.pop("paymentInfo", {})
Org._is_govm_missing_account_data(is_govm_account_creation, mailing_address, payment_info.get("revenueAccount"))
if is_govm_account_creation:
has_org_updates = True
org_info["statusCode"] = OrgStatus.PENDING_STAFF_REVIEW.value
has_status_changing = True
self._create_gov_account_task(org_model)
if product_subscriptions is not None:
subscription_data = {"subscriptions": product_subscriptions}
ProductService.create_product_subscription(
self._model.id, subscription_data=subscription_data, skip_auth=True
)
# Depreciated (use update_org_address instead)
if mailing_address:
has_org_updates = True
contacts = self._model.contacts
if len(contacts) > 0:
contact = self._model.contacts[0].contact
contact.update_from_dict(**camelback2snake(mailing_address))
contact.save()
else:
Org.add_contact_to_org(mailing_address, self._model)
# Check for other variables
if org_info: # Once all org info are popped and variables remains, update the org.
has_org_updates = True
if has_org_updates:
excluded = ("type_code",) if has_status_changing else EXCLUDED_FIELDS
self._model.update_org_from_dict(camelback2snake(org_info), exclude=excluded)
if is_govm_account_creation:
# send mail after the org is committed to DB
Org.send_staff_review_account_reminder(relationship_id=self._model.id)
if name_updated or payment_info:
payment_account_status, error = Org._create_payment_for_org(
mailing_address, self._model, payment_info, False
)
if payment_account_status == PaymentAccountStatus.FAILED and error is not None:
current_app.logger.warning(f"Account update payment Error: {error}")
# Depreciated (use update_org_address instead)
Org._publish_activity_on_mailing_address_change(org_model.id, current_org_name, mailing_address)
Org._publish_activity_on_name_change(org_model.id, org_name)
ProductService.update_org_product_keycloak_groups(org_model.id)
current_app.logger.debug(">update_org ")
return self
def update_org_address(self, org_info):
"""Update or Create a new address for organization."""
current_app.logger.debug("<update_org_address ")
org_model: OrgModel = self._model
mailing_address = org_info.get("mailingAddress", None)
contacts = self._model.contacts
if len(contacts) > 0:
contact = self._model.contacts[0].contact
contact.update_from_dict(**camelback2snake(mailing_address))
contact.save()
else:
Org.add_contact_to_org(mailing_address, self._model)
self._model.update_org_from_dict(camelback2snake(org_info), exclude=EXCLUDED_FIELDS)
Org._publish_activity_on_mailing_address_change(org_model.id, org_model.name, mailing_address)
current_app.logger.debug(">update_org_address ")
return self
@staticmethod
def _is_govm_missing_account_data(is_govm_account_creation, mailing_address, revenue_account):
if is_govm_account_creation and (mailing_address is None or revenue_account is None):
raise BusinessException(Error.GOVM_ACCOUNT_DATA_MISSING, None)
@staticmethod
def _publish_activity_on_mailing_address_change(org_id: int, org_name: str, mailing_address: str):
if mailing_address:
ActivityLogPublisher.publish_activity(
Activity(
org_id,
ActivityAction.ACCOUNT_ADDRESS_CHANGE.value,
name=org_name,
value=json.dumps(mailing_address),
)
)
@staticmethod
def _publish_activity_on_name_change(org_id: int, org_name: str):
if org_name:
ActivityLogPublisher.publish_activity(
Activity(org_id, ActivityAction.ACCOUNT_NAME_CHANGE.value, name=org_name, value=org_name)
)
@staticmethod
def _create_payment_for_org(mailing_address, org, payment_info, is_new_org: bool = True):
"""Create Or update payment info for org."""
selected_payment_method = payment_info.get("paymentMethod", None)
payment_method = None
arg_dict = {
"selected_payment_method": selected_payment_method,
"access_type": org.access_type,
"org_type": OrgType[org.type_code],
}
if is_new_org or selected_payment_method:
validator_obj = payment_type_validate(is_fatal=True, **arg_dict)
payment_method = validator_obj.info.get("payment_type")
return Org._create_payment_settings(org, payment_info, payment_method, mailing_address, is_new_org)
@staticmethod
def _create_gov_account_task(org_model: OrgModel):
# create a staff review task for this account
task_type = TaskTypePrefix.GOVM_REVIEW.value
user: UserModel = UserModel.find_by_jwt_token()
task_info = {
"name": org_model.name,
"relationshipId": org_model.id,
"relatedTo": user.id,
"dateSubmitted": datetime.today(),
"relationshipType": TaskRelationshipType.ORG.value,
"type": task_type,
"action": TaskAction.ACCOUNT_REVIEW.value,
"status": TaskStatus.OPEN.value,
"relationship_status": TaskRelationshipStatus.PENDING_STAFF_REVIEW.value,
}
TaskService.create_task(task_info=task_info, do_commit=False)
@staticmethod
def delete_org(org_id):
"""Soft-Deletes an Org.
Only admin can perform this.
1 - All businesses gets unaffiliated.
2 - All team members removed.
3 - If there is any credit on the account then cannot be deleted.
Premium:
1 - If there is any active PAD transactions going on, then cannot be deleted.
"""
current_app.logger.debug(f"<Delete Org {org_id}")
# Affiliation uses OrgService, adding as local import
# pylint:disable=import-outside-toplevel, cyclic-import
from auth_api.services.affiliation import Affiliation as AffiliationService
check_auth(one_of_roles=(ADMIN, STAFF), org_id=org_id)
org: OrgModel = OrgModel.find_by_org_id(org_id)
if not org:
raise BusinessException(Error.DATA_NOT_FOUND, None)
if org.status_code not in (OrgStatus.ACTIVE.value, OrgStatus.PENDING_INVITE_ACCEPT.value):
raise BusinessException(Error.NOT_ACTIVE_ACCOUNT, None)
Org._delete_pay_account(org_id)
# Find all active affiliations and remove them.
entities = AffiliationService.find_affiliations_by_org_id(org_id)
for entity in entities:
delete_affiliation_request = DeleteAffiliationRequest(
org_id=org_id, business_identifier=entity["business_identifier"], reset_passcode=True
)
AffiliationService.delete_affiliation(delete_affiliation_request)
members = MembershipModel.find_members_by_org_id(org_id)
for member in members:
member.status = Status.INACTIVE.value
member.flush()
user: UserModel = UserModel.find_by_id(member.user_id)
# Remove user from keycloak group if they are not part of any orgs
if len(MembershipModel.find_orgs_for_user(member.user_id)) == 0:
KeycloakService.remove_from_account_holders_group(user.keycloak_guid)
# If the admin is BCeID user, mark the affidavit INACTIVE.
if user.login_source == LoginSource.BCEID.value and member.membership_type_code == ADMIN:
if len(MembershipModel.find_orgs_for_user(user.id)) > 0:
continue
affidavit = AffidavitModel.find_approved_by_user_id(user.id)
if affidavit:
affidavit.status_code = AffidavitStatus.INACTIVE.value
affidavit.flush()
# Set the account as INACTIVE
org.status_code = OrgStatus.INACTIVE.value
org.save()
ProductService.update_org_product_keycloak_groups(org.id)
ActivityLogPublisher.publish_activity(
Activity(
org.id,
ActivityAction.ACCOUNT_DEACTIVATION.value,
name=org.name,
value=None,
)
)
current_app.logger.debug("org Inactivated>")
@staticmethod
def _delete_pay_account(org_id):
pay_url = current_app.config.get("PAY_API_URL")
try:
token = RestService.get_service_account_token()
pay_response = RestService.delete(
endpoint=f"{pay_url}/accounts/{org_id}", token=token, raise_for_status=False
)
pay_response.raise_for_status()
except HTTPError as pay_err:
current_app.logger.info(pay_err)
response_json = pay_response.json()
error_type = response_json.get("type")
error: Error = Error[error_type] if error_type in Error.__members__ else Error.PAY_ACCOUNT_DEACTIVATE_ERROR
raise BusinessException(error, pay_err) from pay_err
def get_payment_info(self):
"""Return the Payment Details for an org by calling Pay API."""
pay_url = current_app.config.get("PAY_API_URL")
# invoke pay-api
token = RestService.get_service_account_token()
response = RestService.get(endpoint=f"{pay_url}/accounts/{self._model.id}", token=token, retry_on_failure=True)
return response.json()
@staticmethod
@user_context
def is_staff_or_external_staff(**kwargs):
"""Check is user is staff or external staff."""
user_from_context: UserContext = kwargs["user_context"]
return user_from_context.is_staff() or user_from_context.is_external_staff()
@staticmethod
def find_by_org_id(org_id, allowed_roles: tuple = None, **kwargs): # noqa: ARG004
"""Find and return an existing organization with the provided id."""
if org_id is None:
return None
org_model = OrgModel.find_by_org_id(org_id)
if not org_model:
return None
if not Org.is_staff_or_external_staff():
# Check authorization for the user
check_auth(one_of_roles=allowed_roles, org_id=org_id)
return Org(org_model)
@staticmethod
def find_by_org_name(org_name, branch_name=None):
"""Find and return an existing organization with the provided name."""
if org_name is None:
return None
org_model = OrgModel.find_similar_org_by_name(org_name, org_id=None, branch_name=branch_name)
if not org_model:
return None
orgs = {"orgs": []}
for org in org_model:
orgs["orgs"].append(Org(org).as_dict())
return orgs
@staticmethod
def get_login_options_for_org(org_id, allowed_roles: tuple = None):
"""Get the payment settings for the given org."""
current_app.logger.debug("get_login_options(>")
org = OrgModel.find_by_org_id(org_id)
if org is None:
raise BusinessException(Error.DATA_NOT_FOUND, None)
if not Org.is_staff_or_external_staff():
# Check authorization for the user
check_auth(one_of_roles=allowed_roles, org_id=org_id)
return AccountLoginOptionsModel.find_active_by_org_id(org_id)
@staticmethod
def add_login_option(org_id, login_source):
"""Create a new contact for this org."""
# check for existing contact (only one contact per org for now)
current_app.logger.debug(">add_login_option")
org = OrgModel.find_by_org_id(org_id)
if org is None:
raise BusinessException(Error.DATA_NOT_FOUND, None)
check_auth(one_of_roles=(ADMIN, STAFF), org_id=org_id)
login_option = AccountLoginOptionsModel(login_source=login_source, org_id=org_id)
login_option.save()
return login_option
@staticmethod
def update_login_option(org_id, login_source):
"""Create a new contact for this org."""
# check for existing contact (only one contact per org for now)
current_app.logger.debug(">update_login_option")
org = OrgModel.find_by_org_id(org_id)
if org is None:
raise BusinessException(Error.DATA_NOT_FOUND, None)
check_auth(one_of_roles=(ADMIN, STAFF), org_id=org_id)
existing_login_option = AccountLoginOptionsModel.find_active_by_org_id(org_id)
if existing_login_option is not None:
existing_login_option.is_active = False
existing_login_option.add_to_session()
login_option = AccountLoginOptionsModel(login_source=login_source, org_id=org_id)
login_option.save()
ActivityLogPublisher.publish_activity(
Activity(
org_id,
ActivityAction.AUTHENTICATION_METHOD_CHANGE.value,
name=org.name,
value=login_source,
id=login_option.id,
)
)
return login_option
@staticmethod
def get_contacts(org_id):
"""Get the contacts for the given org."""
current_app.logger.debug("get_contacts>")
org = OrgModel.find_by_org_id(org_id)
if org is None:
raise BusinessException(Error.DATA_NOT_FOUND, None)
collection = []
for contact_link in org.contacts:
collection.append(ContactService(contact_link.contact).as_dict())
return {"contacts": collection}
@staticmethod
def add_contact(org_id, contact_info):
"""Create a new contact for this org."""
# check for existing contact (only one contact per org for now)
current_app.logger.debug(">add_contact")
org = OrgModel.find_by_org_id(org_id)
if org is None:
raise BusinessException(Error.DATA_NOT_FOUND, None)
contact_link = ContactLinkModel.find_by_org_id(org_id)
if contact_link is not None:
raise BusinessException(Error.DATA_ALREADY_EXISTS, None)
contact = ContactModel(**camelback2snake(contact_info))
contact = contact.flush()
contact_link = ContactLinkModel()
contact_link.contact = contact
contact_link.org = org
contact_link.save()
current_app.logger.debug("<add_contact")
return ContactService(contact)
@staticmethod
def update_contact(org_id, contact_info):
"""Update the existing contact for this org."""
current_app.logger.debug(">update_contact ")
org = OrgModel.find_by_org_id(org_id)
if org is None:
raise BusinessException(Error.DATA_NOT_FOUND, None)
# find the contact link for this org
contact_link = ContactLinkModel.find_by_org_id(org_id)
if contact_link is None or contact_link.contact is None:
raise BusinessException(Error.DATA_NOT_FOUND, None)
contact = contact_link.contact
contact.update_from_dict(**camelback2snake(contact_info))
contact.save()
current_app.logger.debug("<update_contact ")
# return the updated contact
return ContactService(contact)
@staticmethod
def delete_contact(org_id):
"""Delete the contact for this org."""
current_app.logger.debug(">delete_contact ")
org = OrgModel.find_by_org_id(org_id)
if not org or not org.contacts:
raise BusinessException(Error.DATA_NOT_FOUND, None)
deleted_contact = Org.__delete_contact(org)
current_app.logger.debug("<delete_contact ")
return ContactService(deleted_contact)
@staticmethod
def __delete_contact(org):
# unlink the org from its contact
contact_link = ContactLinkModel.find_by_org_id(org.id)
if contact_link:
del contact_link.org
contact_link.save()
# clean up any orphaned contacts and links
if not contact_link.has_links():
contact = contact_link.contact
contact_link.delete()
contact.delete()
return contact
return None
@staticmethod
def get_orgs(user_id, valid_statuses=VALID_STATUSES):
"""Return the orgs associated with this user."""
return MembershipModel.find_orgs_for_user(user_id, valid_statuses)
@staticmethod
@user_context
def search_orgs(search: OrgSearch, **kwargs): # pylint: disable=too-many-locals
"""Search for orgs based on input parameters."""
orgs_result = {"orgs": [], "page": search.page, "limit": search.limit, "total": 0}
include_invitations: bool = False
user_from_context: UserContext = kwargs["user_context"]
roles = user_from_context.roles
search.access_type, is_staff_admin = Org.refine_access_type(search.access_type)
if search.statuses and OrgStatus.PENDING_ACTIVATION.value in search.statuses:
# only staff admin can see director search accounts
if not is_staff_admin and Role.VIEW_ACCOUNT_PENDING_INVITATIONS.value not in roles:
raise BusinessException(Error.INVALID_USER_CREDENTIALS, None)
org_models, orgs_result["total"] = OrgModel.search_pending_activation_orgs(name=search.name)
include_invitations = True
else:
org_models, orgs_result["total"] = OrgModel.search_org(search)
for org in org_models:
orgs_result["orgs"].append(
{
**Org(org).as_dict(),
"contacts": (
[ContactSchema(exclude=("links",)).dump(org.contacts[0].contact, many=False)]
if org.contacts
else []
),
"invitations": (
[InvitationSchema(exclude=("membership",)).dump(org.invitations[0].invitation, many=False)]
if include_invitations and org.invitations
else []
),
"members": (
MembershipSchema(exclude=("org", "user.contacts")).dump(org.members, many=True)
if search.include_members and org.members
else []
),
}
)
return orgs_result
@staticmethod
def search_orgs_by_affiliation(business_identifier, excluded_org_types):
"""Search for orgs based on input parameters."""
orgs, total = OrgModel.search_orgs_by_business_identifier(business_identifier, excluded_org_types)
return {"orgs": orgs, "total": total}
@staticmethod
@user_context
def refine_access_type(access_types, **kwargs):
"""Find Access Type."""
user_from_context: UserContext = kwargs["user_context"]
roles = user_from_context.roles
is_staff_admin = Role.STAFF_CREATE_ACCOUNTS.value in roles or Role.STAFF_MANAGE_ACCOUNTS.value in roles
if not is_staff_admin:
if len(access_types) < 1:
access_types = [item.value for item in AccessType]
return access_types, is_staff_admin
@staticmethod
def bcol_account_link_check(bcol_account_id, org_id=None):
"""Validate the BCOL id is linked or not. If already linked, return True."""
if current_app.config.get("BCOL_ACCOUNT_LINK_CHECK"):
org = OrgModel.find_by_bcol_id(bcol_account_id)
if org and org.id != org_id: # check if already taken up by different org
return True
return False
def change_org_status(self, status_code, suspension_reason_code):
"""Update the status of the org.
Used now for suspending/activate account.
1) check access .only staff can do it now
2) check org status/eligiblity
3) suspend it
"""
current_app.logger.debug("<change_org_status ")
user: UserModel = UserModel.find_by_jwt_token()
org_model = self._model
org_model.status_code = status_code
org_model.decision_made_by = user.username # not sure if a new field is needed for this.
if status_code == OrgStatus.SUSPENDED.value:
org_model.suspended_on = datetime.today()
org_model.suspension_reason_code = suspension_reason_code
org_model.save()
if status_code == OrgStatus.SUSPENDED.value:
suspension_reason_description = (
SuspensionReasonCode[suspension_reason_code].value
if suspension_reason_code in [item.name for item in SuspensionReasonCode]
else ""
)
ActivityLogPublisher.publish_activity(
Activity(
org_model.id,
ActivityAction.ACCOUNT_SUSPENSION.value,
name=org_model.name,
value=suspension_reason_description,
)
)
current_app.logger.debug("change_org_status>")
return Org(org_model)
@staticmethod
def approve_or_reject(org_id: int, is_approved: bool, task_action: str = None):
"""Mark the affidavit as approved or rejected."""
current_app.logger.debug("<find_affidavit_by_org_id ")
# Get the org and check what's the current status
org: OrgModel = OrgModel.find_by_org_id(org_id)
# Current User
user: UserModel = UserModel.find_by_jwt_token()
if task_action == TaskAction.AFFIDAVIT_REVIEW.value:
AffidavitService.approve_or_reject(org_id, is_approved, user)
if is_approved:
org.status_code = OrgStatus.ACTIVE.value
else:
org.status_code = OrgStatus.REJECTED.value
org.decision_made_by = user.username