def delete_affiliation(org_id, business_identifier, email_addresses: str = None, reset_passcode: bool = False, token_info: Dict = None): """Delete the affiliation for the provided org id and business id.""" current_app.logger.info(f'<delete_affiliation org_id:{org_id} business_identifier:{business_identifier}') org = OrgService.find_by_org_id(org_id, token_info=token_info, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF)) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier, token_info=token_info, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF)) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity_id = entity.identifier affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(org_id=org_id, entity_id=entity_id) if affiliation is None: raise BusinessException(Error.DATA_NOT_FOUND, None) if reset_passcode: entity.reset_passcode(entity.business_identifier, email_addresses, token_info) affiliation.delete() entity.set_pass_code_claimed(False) publish_activity(f'{ActivityAction.REMOVE_AFFILIATION.value}-{entity.name}', entity.name, business_identifier, org_id)
def validate(is_fatal=False, **kwargs) -> ValidatorResponse: """Validate bcol credentials.""" bcol_credential = kwargs.get('bcol_credential') org_id = kwargs.get('org_id', None) user: UserContext = kwargs['user'] validator_response = ValidatorResponse() bcol_response = RestService.post( endpoint=current_app.config.get('BCOL_API_URL') + '/profiles', data=bcol_credential, token=user.bearer_token, raise_for_status=False) if bcol_response.status_code != http_status.HTTP_200_OK: error = json.loads(bcol_response.text) validator_response.add_error( CustomException(error['detail'], bcol_response.status_code)) if is_fatal: raise BusinessException( CustomException(error['detail'], bcol_response.status_code), None) else: bcol_account_number = bcol_response.json().get('accountNumber') from auth_api.services.org import Org as OrgService # pylint:disable=cyclic-import, import-outside-toplevel if OrgService.bcol_account_link_check(bcol_account_number, org_id): validator_response.add_error(Error.BCOL_ACCOUNT_ALREADY_LINKED) if is_fatal: raise BusinessException(Error.BCOL_ACCOUNT_ALREADY_LINKED, None) else: validator_response.add_info({'bcol_response': bcol_response}) return validator_response
def post(): """Post a new user using the request body (which will contain a JWT). If the user already exists, update the name. """ token = g.jwt_oidc_token_info try: request_json = request.get_json(silent=True) # For BCeID users validate schema. if token.get('loginSource', None) == LoginSource.BCEID.value and request_json is not None: valid_format, errors = schema_utils.validate(request_json, 'user') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST user = UserService.save_from_jwt_token(token, request_json) response, status = user.as_dict(), http_status.HTTP_201_CREATED # Add the user to public_users group if the user doesn't have public_user group if token.get('loginSource', '') != LoginSource.STAFF.value: KeycloakService.join_users_group(token) # For anonymous users, there are no invitation process for members, # so whenever they login perform this check and add them to corresponding groups if token.get('loginSource', '') == LoginSource.BCROS.value: if len(OrgService.get_orgs(user.identifier, [Status.ACTIVE.value])) > 0: KeycloakService.join_account_holders_group() except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status
def fetch_user_settings(user_id): """Create a new organization.""" current_app.logger.debug('<fetch_user_settings ') all_settings = [] url_origin = current_app.config.get('WEB_APP_URL') if user_id: all_orgs = OrgService.get_orgs(user_id) for org in all_orgs: all_settings.append( UserSettingsModel( org.id, org.name, url_origin, '/account/' + str(org.id) + '/settings', 'ACCOUNT', org.type_code, org.status_code, '/account/' + str(org.id) + '/restricted-product', org.branch_name # added as additonal label )) all_settings.append( UserSettingsModel(user_id, 'USER PROFILE', url_origin, '/userprofile', 'USER_PROFILE')) all_settings.append( UserSettingsModel(user_id, 'CREATE ACCOUNT', url_origin, '/setup-account', 'CREATE_ACCOUNT')) return all_settings
def post(): """Post a new user using the request body (which will contain a JWT). If the user already exists, update the name. """ token = g.jwt_oidc_token_info try: request_json = request.get_json(silent=True) # For BCeID users validate schema. if token.get('loginSource', None) == LoginSource.BCEID.value and request_json is not None: valid_format, errors = schema_utils.validate(request_json, 'user') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST user = UserService.save_from_jwt_token(token, request_json) response, status = user.as_dict(), http_status.HTTP_201_CREATED # Add the user to public_users group if the user doesn't have public_user group KeycloakService.join_users_group(token) # If the user doesn't have account_holder role check if user is part of any orgs and add to the group if token.get('loginSource', '') in \ (LoginSource.BCSC.value, LoginSource.BCROS.value, LoginSource.BCEID.value) \ and Role.ACCOUNT_HOLDER.value not in token.get('roles', []) \ and len(OrgService.get_orgs(user.identifier, [Status.ACTIVE.value])) > 0: KeycloakService.join_account_holders_group() except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status
def delete_affiliation(org_id, business_identifier, token_info: Dict = None): """Delete the affiliation for the provided org id and business id.""" current_app.logger.info( f'<delete_affiliation org_id:{org_id} business_identifier:{business_identifier}' ) org = OrgService.find_by_org_id(org_id, token_info=token_info, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF)) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier( business_identifier, token_info=token_info, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF)) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity_id = entity.identifier affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids( org_id=org_id, entity_id=entity_id) if affiliation is None: raise BusinessException(Error.DATA_NOT_FOUND, None) affiliation.delete() entity.set_pass_code_claimed(False)
def delete_affiliation(org_id, business_identifier, email_addresses: str = None, reset_passcode: bool = False, log_delete_draft: bool = False): """Delete the affiliation for the provided org id and business id.""" current_app.logger.info(f'<delete_affiliation org_id:{org_id} business_identifier:{business_identifier}') org = OrgService.find_by_org_id(org_id, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF)) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF)) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity_id = entity.identifier affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(org_id=org_id, entity_id=entity_id) if affiliation is None: raise BusinessException(Error.DATA_NOT_FOUND, None) if reset_passcode: entity.reset_passcode(entity.business_identifier, email_addresses) affiliation.delete() entity.set_pass_code_claimed(False) # When registering a business it will affiliate a NR -> unaffiliate a NR draft -> affiliate a business. # Users can also intentionally delete a draft. We want to log this action. should_publish = (log_delete_draft or not (entity.status == NRStatus.DRAFT.value and entity.corp_type == CorpType.NR.value)) if entity.corp_type != CorpType.RTMP.value and should_publish: name = entity.name if len(entity.name) > 0 else entity.business_identifier ActivityLogPublisher.publish_activity(Activity(org_id, ActivityAction.REMOVE_AFFILIATION.value, name=name, id=entity.business_identifier))
def create_affiliation(org_id, business_identifier, pass_code=None, token_info: Dict = None): """Create an Affiliation.""" # Validate if org_id is valid by calling Org Service. current_app.logger.info( f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}' ) org = OrgService.find_by_org_id(org_id, token_info=token_info, allowed_roles=CLIENT_AUTH_ROLES) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier, skip_auth=True) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) current_app.logger.debug('<create_affiliation entity found') entity_id = entity.identifier authorized = True # Authorized if the entity has been claimed if entity.as_dict()['passCodeClaimed']: authorized = False # If a passcode was provided... elif pass_code: # ... and the entity has a passcode on it, check that they match authorized = validate_passcode(pass_code, entity.pass_code) # If a passcode was not provided... else: # ... check that the entity does not have a passcode protecting it if entity.pass_code: authorized = False if not authorized: current_app.logger.debug('<create_affiliation not authorized') raise BusinessException(Error.INVALID_USER_CREDENTIALS, None) current_app.logger.debug('<create_affiliation find affiliation') # Ensure this affiliation does not already exist affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids( org_id, entity_id) if affiliation is not None: raise BusinessException(Error.DATA_ALREADY_EXISTS, None) # Retrieve entity name from Legal-API and update the entity with current name # TODO: Create subscription to listen for future name updates current_app.logger.debug('<create_affiliation sync_name') entity.sync_name() affiliation = AffiliationModel(org_id=org_id, entity_id=entity_id) affiliation.save() entity.set_pass_code_claimed(True) current_app.logger.debug('<create_affiliation affiliated') return Affiliation(affiliation)
def create_affiliation(org_id, business_identifier, pass_code=None): """Create an Affiliation.""" # Validate if org_id is valid by calling Org Service. current_app.logger.info( f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}' ) org = OrgService.find_by_org_id(org_id, allowed_roles=ALL_ALLOWED_ROLES) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier, skip_auth=True) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) current_app.logger.debug('<create_affiliation entity found') entity_id = entity.identifier authorized = True already_claimed = False # Authorized if the entity has been claimed if entity.as_dict()['pass_code_claimed']: authorized = False already_claimed = True # If a passcode was provided... elif pass_code: # ... and the entity has a passcode on it, check that they match authorized = validate_passcode(pass_code, entity.pass_code) # If a passcode was not provided... else: # ... check that the entity does not have a passcode protecting it if entity.pass_code: authorized = False if not authorized: # show a different message when the passcode is already claimed if already_claimed: current_app.logger.debug( '<create_affiliation passcode already claimed') raise BusinessException(Error.ALREADY_CLAIMED_PASSCODE, None) current_app.logger.debug('<create_affiliation not authorized') raise BusinessException(Error.INVALID_USER_CREDENTIALS, None) current_app.logger.debug('<create_affiliation find affiliation') # Ensure this affiliation does not already exist affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids( org_id, entity_id) if affiliation is not None: raise BusinessException(Error.DATA_ALREADY_EXISTS, None) affiliation = AffiliationModel(org_id=org_id, entity_id=entity_id) affiliation.save() entity.set_pass_code_claimed(True) publish_activity( f'{ActivityAction.CREATE_AFFILIATION.value}-{entity.name}', entity.name, entity_id, org_id) return Affiliation(affiliation)
def post(): """Return BC Online profile details.""" request_json = request.get_json() try: bcol_response = Org.get_bcol_details(bcol_credential=request_json) response, status = bcol_response.json(), bcol_response.status_code except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status
def find_visible_affiliations_by_org_id(org_id): """Given an org_id, this will return the entities affiliated with it.""" current_app.logger.debug( '<find_visible_affiliations_by_org_id for org_id {}'.format( org_id)) if not org_id: raise BusinessException(Error.DATA_NOT_FOUND, None) org = OrgService.find_by_org_id(org_id, allowed_roles=ALL_ALLOWED_ROLES) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) data = Affiliation.find_affiliations_by_org_id(org_id) # 3806 : Filter out the NR affiliation if there is IA affiliation for the same NR. # Dict with key as NR number and value as name nr_number_name_dict = { d['business_identifier']: d['name'] for d in data if d['corp_type']['code'] == CorpType.NR.value } # Create a list of all temporary business names tmp_business_list = [ d['name'] for d in data if d['corp_type']['code'] == CorpType.TMP.value ] # NR Numbers nr_numbers = nr_number_name_dict.keys() filtered_affiliations: list = [] for entity in data: if entity['corp_type']['code'] == CorpType.NR.value: # If there is a TMP affiliation present for the NR, do not show NR if not entity['business_identifier'] in tmp_business_list: filtered_affiliations.append(entity) elif entity['corp_type']['code'] == CorpType.TMP.value: # If affiliation is not for a named company IA, and not a Numbered company # (name and businessIdentifier same) # --> Its a Temp affiliation with incorporation complete. # In this case, a TMP affiliation will be there but the name will be BC... if entity['name'] in nr_numbers or entity['name'] == entity[ 'business_identifier']: # If temp affiliation is for an NR, change the name to NR's name if entity['name'] in nr_numbers: entity['name'] = nr_number_name_dict[entity['name']] filtered_affiliations.append(entity) else: filtered_affiliations.append(entity) current_app.logger.debug('>find_visible_affiliations_by_org_id') return filtered_affiliations
def post(): """Return BC Online profile details.""" request_json = request.get_json() bearer_token = request.headers['Authorization'].replace('Bearer ', '') try: bcol_response = Org.get_bcol_details(bcol_credential=request_json, bearer_token=bearer_token) response, status = bcol_response.json(), bcol_response.status_code except BusinessException as exception: response, status = { 'code': exception.code, 'message': exception.message }, exception.status_code return response, status
def create_affiliation(org_id, business_identifier, pass_code=None): """Create an Affiliation.""" # Validate if org_id is valid by calling Org Service. org = OrgService.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity_id = entity.identifier authorized = True # Authorized if the entity has been claimed if entity.as_dict()['passCodeClaimed']: authorized = False # If a passcode was provided... if pass_code: # ... and the entity has a passcode on it, check that they match if entity.pass_code != pass_code: authorized = False # If a passcode was not provided... else: # ... check that the entity does not have a passcode protecting it if entity.pass_code: authorized = False if not authorized: # If org being affiliated was IMPLICIT, remove it since the affiliation was not valid if org.as_dict()['org_type'] == 'IMPLICIT': org.delete_org() raise BusinessException(Error.INVALID_USER_CREDENTIALS, None) # Ensure this affiliation does not already exist affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids( org_id, entity_id) if affiliation is not None: raise BusinessException(Error.DATA_ALREADY_EXISTS, None) affiliation = AffiliationModel(org_id=org_id, entity_id=entity_id) affiliation.save() entity.set_pass_code_claimed(True) return Affiliation(affiliation)
def get(): """Get a list of orgs that the current user is associated with.""" token = g.jwt_oidc_token_info try: user = UserService.find_by_jwt_token(token) if not user: response, status = {'message': 'User not found.'}, http_status.HTTP_404_NOT_FOUND else: all_orgs = OrgService.get_orgs(user.identifier) orgs = OrgSchema().dump( all_orgs, many=True) response, status = jsonify({'orgs': orgs}), http_status.HTTP_200_OK except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status
def delete_affiliation(org_id, business_identifier): """Delete the affiliation for the provided org id and business id.""" org = OrgService.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity_id = entity.identifier affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids( org_id=org_id, entity_id=entity_id) if affiliation is None: raise BusinessException(Error.DATA_NOT_FOUND, None) affiliation.delete() entity.set_pass_code_claimed(False)
def fetch_user_settings(user_id): """Create a new organization.""" current_app.logger.debug('<fetch_user_settings ') all_orgs = OrgService.get_orgs(user_id) all_settings = [] url_origin = current_app.config.get('WEB_APP_URL') for org in all_orgs: all_settings.append( UserSettingsModel(org.id, org.name, url_origin, '/account/' + str(org.id) + '/settings', 'ACCOUNT')) all_settings.append( UserSettingsModel(user_id, 'USER PROFILE', url_origin, '/userprofile', 'USER_PROFILE')) all_settings.append( UserSettingsModel(user_id, 'CREATE ACCOUNT', url_origin, '/createaccount', 'CREATE_ACCOUNT')) return all_settings
def post(): """Post a new user using the request body (which will contain a JWT). If the user already exists, update the name. """ token = g.jwt_oidc_token_info try: user = UserService.save_from_jwt_token(token) response, status = user.as_dict(), http_status.HTTP_201_CREATED # Add the user to public_users group if the user doesn't have public_user group KeycloakService.join_users_group(g.jwt_oidc_token_info) # If the user doesn't have account_holder role check if user is part of any orgs and add to the group if token.get('loginSource', '') in (BCSC, BCROS) \ and Role.ACCOUNT_HOLDER.value not in token.get('roles', []) \ and len(OrgService.get_orgs(user.identifier, [Status.ACTIVE.value])) > 0: KeycloakService.join_account_holders_group() except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status
def find_affiliated_entities_by_org_id(org_id): """Given an org_id, this will return the entities affiliated with it.""" current_app.logger.debug( '<find_affiliations_by_org_id for org_id {}'.format(org_id)) if not org_id: raise BusinessException(Error.DATA_NOT_FOUND, None) org = OrgService.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) data = [] affiliation_models = AffiliationModel.find_affiliations_by_org_id( org_id) if affiliation_models is None: raise BusinessException(Error.DATA_NOT_FOUND, None) for affiliation_model in affiliation_models: if affiliation_model: data.append(EntityService(affiliation_model.entity).as_dict()) current_app.logger.debug('>find_affiliations_by_org_id') return data
def get(): """Get a list of orgs that the current user is associated with.""" token = g.jwt_oidc_token_info try: user = UserService.find_by_jwt_token(token) if not user: response, status = {'message': 'User not found.'}, http_status.HTTP_404_NOT_FOUND else: # response, status = jsonify(user.get_orgs()), http_status.HTTP_200_OK all_orgs = OrgService.get_orgs(user.identifier) exclude_fields = [] # only approved users should see entities.. # TODO when endpoints are separated into afilliations endpoint, this logic can be removed if all_orgs: if all_orgs[0].members and all_orgs[0].members[0].status != Status.ACTIVE.value: exclude_fields.append('affiliated_entities') orgs = OrgSchema(exclude=exclude_fields).dump( all_orgs, many=True) response, status = jsonify({'orgs': orgs}), http_status.HTTP_200_OK except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status
def create_new_business_affiliation(org_id, # pylint: disable=too-many-arguments, too-many-locals business_identifier=None, email=None, phone=None, bearer_token: str = None): """Initiate a new incorporation.""" current_app.logger.info(f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}') if not email and not phone: raise BusinessException(Error.NR_INVALID_CONTACT, None) # Validate if org_id is valid by calling Org Service. org = OrgService.find_by_org_id(org_id, allowed_roles=CLIENT_AUTH_ROLES) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier, skip_auth=True) # If entity already exists and passcode is already claimed, throw error if entity and entity.as_dict()['pass_code_claimed']: raise BusinessException(Error.NR_CONSUMED, None) # Call the legal-api to verify the NR details nr_json = Affiliation._get_nr_details(business_identifier, bearer_token) if nr_json: status = nr_json.get('state') nr_phone = nr_json.get('applicants').get('phoneNumber') nr_email = nr_json.get('applicants').get('emailAddress') if status not in (NRStatus.APPROVED.value, NRStatus.CONDITIONAL.value): raise BusinessException(Error.NR_NOT_APPROVED, None) # If consentFlag is not R, N or Null for a CONDITIONAL NR throw error if status == NRStatus.CONDITIONAL.value and nr_json.get('consentFlag', None) not in (None, 'R', 'N'): raise BusinessException(Error.NR_NOT_APPROVED, None) if (phone and phone != nr_phone) or (email and email.casefold() != nr_email.casefold()): raise BusinessException(Error.NR_INVALID_CONTACT, None) # Create an entity with the Name from NR if entity doesn't exist if not entity: # Filter the names from NR response and get the name which has status APPROVED as the name. # Filter the names from NR response and get the name which has status CONDITION as the name. nr_name_state = NRNameStatus.APPROVED.value if status == NRStatus.APPROVED.value \ else NRNameStatus.CONDITION.value name = next((name.get('name') for name in nr_json.get('names') if name.get('state', None) == nr_name_state), None) entity = EntityService.save_entity({ 'businessIdentifier': business_identifier, 'name': name, 'corpTypeCode': CorpType.NR.value, 'passCodeClaimed': True }) # Create an affiliation with org affiliation_model = AffiliationModel(org_id=org_id, entity_id=entity.identifier) affiliation_model.save() if entity.corp_type != CorpType.RTMP.value: ActivityLogPublisher.publish_activity(Activity(org_id, ActivityAction.CREATE_AFFILIATION.value, name=entity.name, id=entity.business_identifier)) entity.set_pass_code_claimed(True) else: raise BusinessException(Error.NR_NOT_FOUND, None) return Affiliation(affiliation_model)
def _get_address(account_id: str): mailing_address = OrgService.get_contacts(account_id) return mailing_address.get('contacts')[0]
def create_affiliation(org_id, business_identifier, pass_code=None, bearer_token=None): """Create an Affiliation.""" # Validate if org_id is valid by calling Org Service. current_app.logger.info(f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}') org = OrgService.find_by_org_id(org_id, allowed_roles=ALL_ALLOWED_ROLES) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) entity = EntityService.find_by_business_identifier(business_identifier, skip_auth=True) if entity is None: raise BusinessException(Error.DATA_NOT_FOUND, None) current_app.logger.debug('<create_affiliation entity found') entity_id = entity.identifier entity_type = entity.corp_type authorized = True if entity_type in ['SP', 'GP']: if not pass_code: authorized = False else: authorized = Affiliation._validate_firms_party(bearer_token, business_identifier, pass_code) else: # Unauthorized if the entity has been claimed # Leaving the code as it may come back. Removing as part of #8863 # if entity.as_dict()['pass_code_claimed']: # authorized = False # already_claimed = True # If a passcode was provided... if pass_code: # ... and the entity has a passcode on it, check that they match authorized = validate_passcode(pass_code, entity.pass_code) # If a passcode was not provided... else: # ... check that the entity does not have a passcode protecting it if entity.pass_code: authorized = False # show a different message when the passcode is already claimed # if already_claimed: # current_app.logger.debug('<create_affiliation passcode already claimed') # raise BusinessException(Error.ALREADY_CLAIMED_PASSCODE, None) if not authorized: current_app.logger.debug('<create_affiliation not authorized') raise BusinessException(Error.INVALID_USER_CREDENTIALS, None) current_app.logger.debug('<create_affiliation find affiliation') # Ensure this affiliation does not already exist affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(org_id, entity_id) if affiliation is not None: raise BusinessException(Error.DATA_ALREADY_EXISTS, None) affiliation = AffiliationModel(org_id=org_id, entity_id=entity_id) affiliation.save() if entity_type not in ['SP', 'GP']: entity.set_pass_code_claimed(True) if entity_type != CorpType.RTMP.value: name = entity.name if len(entity.name) > 0 else entity.business_identifier ActivityLogPublisher.publish_activity(Activity(org_id, ActivityAction.CREATE_AFFILIATION.value, name=name, id=entity.business_identifier)) return Affiliation(affiliation)