Exemple #1
0
def test_party_role_json(session):
    """Assert the json format of party role."""
    identifier = 'CP1234567'
    business = factory_business(identifier)
    member = Party(
        first_name='Michael',
        last_name='Crane',
        middle_initial='Joe',
        title='VP',
    )
    member.save()
    # sanity check
    assert member.id
    party_role = PartyRole(
        role=PartyRole.RoleTypes.DIRECTOR.value,
        appointment_date=datetime.datetime(2017, 5, 17),
        cessation_date=None,
        party_id=member.id,
        business_id=business.id
    )
    party_role.save()

    party_role_json = {
        'appointmentDate': party_role.appointment_date.date().isoformat(),
        'cessationDate': party_role.cessation_date,
        'role': party_role.role,
        'officer': {
            'firstName': member.first_name,
            'lastName': member.last_name,
            'middleInitial': member.middle_initial
        },
        'title': member.title
    }

    assert party_role.json == party_role_json
Exemple #2
0
def test_party_member_save(session):
    """Assert that the party role saves correctly."""
    party_role = PartyRole(
        role=PartyRole.RoleTypes.DIRECTOR.value,
        appointment_date=datetime.datetime(2017, 5, 17),
        cessation_date=None
    )

    party_role.save()
    assert party_role.id
Exemple #3
0
def update_director(director: PartyRole, new_info: dict) -> PartyRole:
    """Update director with new info."""
    director.party.first_name = new_info['officer'].get('firstName',
                                                        '').upper()
    director.party.middle_initial = new_info['officer'].get(
        'middleInitial', '').upper()
    director.party.last_name = new_info['officer'].get('lastName', '').upper()
    director.party.title = new_info.get('title', '').upper()

    if director.party.delivery_address:
        director.party.delivery_address = update_address(
            director.party.delivery_address, new_info['deliveryAddress'])
    else:
        director.party.delivery_address = create_address(
            new_info['deliveryAddress'], Address.DELIVERY)

    if new_info.get('mailingAddress', None):
        if director.party.mailing_address is None:
            director.party.mailing_address = create_address(
                new_info['mailingAddress'], Address.MAILING)
        else:
            director.party.mailing_address = update_address(
                director.party.mailing_address, new_info['mailingAddress'])
    director.cessation_date = new_info.get('cessationDate')

    return director
Exemple #4
0
async def test_transition_filing(app, session):
    """Assert we can create a business based on transition filing."""
    filing_data = copy.deepcopy(TRANSITION_FILING_TEMPLATE)

    business = create_business(filing_data['filing']['business']['identifier'])

    payment_id = str(random.SystemRandom().getrandbits(0x58))
    filing = (create_filing(payment_id, filing_data, business.id))

    filing_msg = {'filing': {'id': filing.id}}

    # Test
    await process_filing(filing_msg, app)

    # Check outcome
    filing = Filing.find_by_id(filing.id)
    business = Business.find_by_internal_id(filing.business_id)

    filing_json = filing.filing_json
    assert business
    assert filing
    assert filing.status == Filing.Status.COMPLETED.value
    assert business.restriction_ind is False
    assert len(business.share_classes.all()) == len(
        filing_json['filing']['transition']['shareStructure']['shareClasses'])
    assert len(business.offices.all()) == len(
        filing_json['filing']['transition']['offices'])
    assert len(business.aliases.all()) == len(
        filing_json['filing']['transition']['nameTranslations'])
    assert len(business.resolutions.all()) == len(
        filing_json['filing']['transition']['shareStructure']
        ['resolutionDates'])
    assert len(PartyRole.get_parties_by_role(business.id, 'director')) == 2
Exemple #5
0
def create_party(business_id: int,
                 party_info: dict,
                 create: bool = True) -> Party:
    """Create a new party or get them if they already exist."""
    party = None
    if create:
        party = PartyRole.find_party_by_name(
            business_id=business_id,
            first_name=party_info['officer'].get('firstName', '').upper(),
            last_name=party_info['officer'].get('lastName', '').upper(),
            middle_initial=party_info['officer'].get('middleInitial',
                                                     '').upper(),
            org_name=party_info.get('orgName', '').upper())
    if not party:
        party = Party(
            first_name=party_info['officer'].get('firstName', '').upper(),
            last_name=party_info['officer'].get('lastName', '').upper(),
            middle_initial=party_info['officer'].get('middleInitial',
                                                     '').upper(),
            title=party_info.get('title', '').upper(),
            organization_name=party_info.get('orgName', '').upper())

    # add addresses to party
    if party_info.get('deliveryAddress', None):
        address = create_address(party_info['deliveryAddress'],
                                 Address.DELIVERY)
        party.delivery_address = address
    if party_info.get('mailingAddress', None):
        mailing_address = create_address(party_info['mailingAddress'],
                                         Address.MAILING)
        party.mailing_address = mailing_address
    return party
Exemple #6
0
def get_directors(identifier, director_id=None):
    """Return a JSON of the directors."""
    business = Business.find_by_identifier(identifier)

    if not business:
        return jsonify({'message':
                        f'{identifier} not found'}), HTTPStatus.NOT_FOUND

    # return the matching director
    if director_id:
        director, msg, code = _get_director(business, director_id)
        return jsonify(director or msg), code

    # return all active directors as of date query param
    end_date = datetime.utcnow().strptime(request.args.get('date'), '%Y-%m-%d').date()\
        if request.args.get('date') else datetime.utcnow().date()

    party_list = []
    active_directors = PartyRole.get_active_directors(business.id, end_date)
    for director in active_directors:
        director_json = director.json
        if business.legal_type == Business.LegalTypes.COOP.value:
            del director_json['mailingAddress']
        party_list.append(director_json)

    return jsonify(directors=party_list)
Exemple #7
0
def add_business_directors(business, directors_json):
    for director in directors_json['directors']:
        delivery_address = create_delivery_address(director['deliveryAddress'])

        # create person/organization get them if they already exist
        party = Party.find_by_name(
            first_name=director['officer'].get('firstName', '').upper(),
            last_name=director['officer'].get('lastName', '').upper(),
            organization_name=director.get('organization_name', '').upper())
        if not party:
            party = Party(
                first_name=director['officer'].get('firstName', '').upper(),
                last_name=director['officer'].get('lastName', '').upper(),
                middle_initial=director['officer'].get('middleInitial',
                                                       '').upper(),
                title=director.get('title', '').upper(),
                organization_name=director.get('organization_name',
                                               '').upper())

        # add addresses to party
        party.delivery_address = delivery_address

        # create party role and link party to it
        party_role = PartyRole(
            role=PartyRole.RoleTypes.DIRECTOR.value,
            appointment_date=director.get('appointmentDate'),
            cessation_date=director.get('cessationDate'),
            party=party)

        business.party_roles.append(party_role)
Exemple #8
0
def create_role(party: Party, role_info: dict) -> PartyRole:
    """Create a new party role and link to party."""
    party_role = PartyRole(role=JSON_ROLE_CONVERTER.get(
        role_info.get('roleType').lower(), ''),
                           appointment_date=role_info['appointmentDate'],
                           cessation_date=role_info['cessationDate'],
                           party=party)
    return party_role
    def _get_director(business, director_id=None):
        # find by ID
        director = None
        if director_id:
            rv = PartyRole.find_by_internal_id(internal_id=director_id)
            if rv:
                director = {'director': rv.json}

        if not director:
            return None, {'message': f'{business.identifier} director not found'}, HTTPStatus.NOT_FOUND

        return director, None, HTTPStatus.OK
Exemple #10
0
def test_process_incorporation_parties(app, session):
    """Assert we successfully add parties in incorporation filing."""
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    filing = copy.deepcopy(INCORP_FILING)
    schema_incorp = copy.deepcopy(INCORPORATION)
    filing['filing']['incorporationApplication']['parties'] = schema_incorp['parties']

    identifier = filing['filing']['incorporationApplication']['nameRequest']['nrNumber']
    business = create_business(identifier)
    filing_id = (create_filing(payment_id, filing, business.id)).id
    filing_msg = {'filing': {'id': filing_id}}

    process_filing(filing_msg, app)
    filing = Filing.find_by_id(filing_id)
    business = Business.find_by_internal_id(filing.business_id)
    assert len(PartyRole.get_parties_by_role(business.id, 'director')) == 1
    assert len(PartyRole.get_parties_by_role(business.id, 'incorporator')) == 1
    assert len(PartyRole.get_parties_by_role(business.id, 'completing_party')) == 1
    director = (PartyRole.get_parties_by_role(business.id, 'director'))[0]
    incorporator = (PartyRole.get_parties_by_role(business.id, 'incorporator'))[0]
    completing_party = (PartyRole.get_parties_by_role(business.id, 'completing_party'))[0]
    assert director.appointment_date
    assert incorporator.appointment_date
    assert completing_party.appointment_date
async def test_incorporation_filing(app, session, bootstrap):
    """Assert we can retrieve a new corp number from COLIN and incorporate a business."""
    filing = copy.deepcopy(INCORPORATION_FILING_TEMPLATE)
    filing['filing']['incorporationApplication']['nameRequest'][
        'nrNumber'] = 'NR 0000021'
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    filing_id = (create_filing(payment_id, filing, bootstrap_id=bootstrap)).id

    filing_msg = {'filing': {'id': filing_id}}

    # Test
    await process_filing(filing_msg, app)

    # Check outcome
    filing = Filing.find_by_id(filing_id)
    business = Business.find_by_internal_id(filing.business_id)

    filing_json = filing.filing_json
    assert business
    assert filing
    assert filing.status == Filing.Status.COMPLETED.value
    assert business.identifier == filing_json['filing']['business'][
        'identifier']
    assert business.founding_date.isoformat(
    ) == filing_json['filing']['business']['foundingDate']
    assert len(business.share_classes.all()) == len(
        filing_json['filing']['incorporationApplication']['shareClasses'])
    assert len(business.offices.all()) == len(
        filing_json['filing']['incorporationApplication']['offices'])

    assert len(PartyRole.get_parties_by_role(business.id, 'director')) == 1
    assert len(PartyRole.get_parties_by_role(business.id, 'incorporator')) == 1
    assert len(PartyRole.get_parties_by_role(business.id,
                                             'completing_party')) == 1
    incorporator = (PartyRole.get_parties_by_role(business.id,
                                                  'incorporator'))[0]
    completing_party = (PartyRole.get_parties_by_role(business.id,
                                                      'completing_party'))[0]
    assert incorporator.appointment_date
    assert completing_party.appointment_date
def copy_over_dirs():
    # add directors as party members
    select_string = 'select * from directors'
    directors = db.session.execute(select_string)
    count = 0
    for row in directors:
        first_name = row[1]
        middle_initial = row[2]
        last_name = row[3]
        title = row[4]
        appointment_date = row[5]
        cessation_date = row[6]
        business_id = row[7]
        address_id = row[8]
        mailing_address_id = row[9]

        try:
            member = Party.find_by_name(
                first_name=first_name.upper(),
                last_name=last_name.upper(),
                organization_name=None
            )
            
            if not member:
                # initialize member
                member = Party(
                    first_name=first_name,
                    middle_initial=middle_initial,
                    last_name=last_name,
                    title=title,
                    delivery_address_id=address_id,
                    mailing_address_id=mailing_address_id
                )
            # initialize member role
            member_role = PartyRole(
                role=PartyRole.RoleTypes.DIRECTOR.value,
                appointment_date=appointment_date,
                cessation_date=cessation_date,
                business_id=business_id,
                party=member
            )
            db.session.add(member_role)
            db.session.commit()
        except Exception as err:
            print(f'Error: {err}')
            print(f'director: {row}')
            print(f'party: {member}')
            count += 1
            continue
    print(f'failed to add {count}')
Exemple #13
0
def add_business_directors(business: Business, directors_json: dict):
    """Create directors and add them to business."""
    for director in directors_json['directors']:
        delivery_address = create_address(director['deliveryAddress'],
                                          Address.DELIVERY)
        mailing_address = create_address(director['mailingAddress'],
                                         Address.MAILING)
        # create person/organization or get them if they already exist for corp
        party = PartyRole.find_party_by_name(
            business_id=business.id,
            first_name=director['officer'].get('firstName', '').upper(),
            last_name=director['officer'].get('lastName', '').upper(),
            middle_initial=director['officer'].get('middleInitial',
                                                   '').upper(),
            org_name=director.get('organization_name', '').upper())
        if not party:
            party = Party(
                first_name=director['officer'].get('firstName', '').upper(),
                last_name=director['officer'].get('lastName', '').upper(),
                middle_initial=director['officer'].get('middleInitial',
                                                       '').upper(),
                title=director.get('title', '').upper(),
                organization_name=director.get('organization_name',
                                               '').upper())

        # add addresses to party
        party.delivery_address = delivery_address
        party.mailing_address = mailing_address

        # create party role and link party to it
        party_role = PartyRole(
            role=PartyRole.RoleTypes.DIRECTOR.value,
            appointment_date=director.get('appointmentDate'),
            cessation_date=director.get('cessationDate'),
            party=party)

        business.party_roles.append(party_role)
Exemple #14
0
def factory_party_role(delivery_address: Address, mailing_address: Address,
                       officer: dict, appointment_date: datetime,
                       cessation_date: datetime,
                       role_type: PartyRole.RoleTypes):
    """Create a role."""
    party = Party(first_name=officer['firstName'],
                  last_name=officer['lastName'],
                  middle_initial=officer['middleInitial'])
    party.delivery_address = delivery_address
    party.mailing_address = mailing_address
    party.save()
    party_role = PartyRole(role=role_type.value,
                           appointment_date=appointment_date,
                           cessation_date=cessation_date,
                           party_id=party.id)
    return party_role
Exemple #15
0
async def test_process_combined_filing(app, session, mocker):
    """Assert that an AR filling can be applied to the model correctly."""
    # mock out the email sender and event publishing
    mocker.patch('entity_filer.worker.publish_email_message',
                 return_value=None)
    mocker.patch('entity_filer.worker.publish_event', return_value=None)

    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    business = create_business(identifier, legal_type='CP')
    agm_date = datetime.date.fromisoformat(
        COMBINED_FILING['filing']['annualReport'].get(
            'annualGeneralMeetingDate'))
    ar_date = datetime.date.fromisoformat(
        COMBINED_FILING['filing']['annualReport'].get('annualReportDate'))
    new_delivery_address = COMBINED_FILING['filing']['changeOfAddress'][
        'offices']['registeredOffice'][
            'deliveryAddress']  # noqa: E501; line too long by 1 char
    new_mailing_address = COMBINED_FILING['filing']['changeOfAddress'][
        'offices']['registeredOffice']['mailingAddress']
    end_date = datetime.datetime.utcnow().date()
    # prep director for no change
    filing_data = copy.deepcopy(COMBINED_FILING)
    directors = filing_data['filing']['changeOfDirectors']['directors']
    director_party1 = create_party(business.id, directors[0])
    role1 = {
        'roleType': 'director',
        'appointmentDate': directors[0].get('appointmentDate'),
        'cessationDate': directors[0].get('cessationDate')
    }
    director1 = create_role(party=director_party1, role_info=role1)
    # prep director for name change
    director_party2_dict = directors[1]
    director_party2_dict['officer']['firstName'] = director_party2_dict[
        'officer']['prevFirstName']
    director_party2_dict['officer']['middleInitial'] = director_party2_dict[
        'officer']['prevMiddleInitial']
    director_party2_dict['officer']['lastName'] = director_party2_dict[
        'officer']['prevLastName']
    director_party2 = create_party(business.id, director_party2_dict)
    role2 = {
        'roleType': 'Director',
        'appointmentDate': director_party2_dict.get('appointmentDate'),
        'cessationDate': director_party2_dict.get('cessationDate')
    }
    director2 = create_role(party=director_party2, role_info=role2)
    # prep director for cease
    director_party3 = create_party(business.id, directors[2])
    role3 = {
        'roleType': 'director',
        'appointmentDate': directors[3].get('appointmentDate'),
        'cessationDate': directors[3].get('cessationDate')
    }
    director3 = create_role(party=director_party3, role_info=role3)
    # prep director for address change
    director_party4_dict = directors[3]
    director_party4_dict['deliveryAddress'][
        'streetAddress'] = 'should get changed'
    director_party4 = create_party(business.id, director_party4_dict)
    role4 = {
        'roleType': 'director',
        'appointmentDate': director_party4_dict.get('appointmentDate'),
        'cessationDate': director_party4_dict.get('cessationDate')
    }
    director4 = create_role(party=director_party4, role_info=role4)

    # list of active/ceased directors in test filing
    ceased_directors, active_directors = active_ceased_lists(COMBINED_FILING)

    # setup
    business.party_roles.append(director1)
    business.party_roles.append(director2)
    business.party_roles.append(director3)
    business.party_roles.append(director4)
    business.save()
    director_ceased_id = director3.id
    # check that adding the directors during setup was successful
    directors = PartyRole.get_parties_by_role(
        business.id, PartyRole.RoleTypes.DIRECTOR.value)
    assert len(directors) == 4
    business_id = business.id
    filing_id = (create_filing(payment_id, COMBINED_FILING, business.id)).id
    filing_msg = {'filing': {'id': filing_id}}

    # TEST
    await process_filing(filing_msg, app)

    # Get modified data
    filing = Filing.find_by_id(filing_id)
    business = Business.find_by_internal_id(business_id)

    # check it out
    assert filing.transaction_id
    assert filing.business_id == business_id
    assert filing.status == Filing.Status.COMPLETED.value
    assert datetime.datetime.date(business.last_agm_date) == agm_date
    assert datetime.datetime.date(business.last_ar_date) == ar_date

    # check address filing
    delivery_address = business.delivery_address.one_or_none().json
    compare_addresses(delivery_address, new_delivery_address)
    mailing_address = business.mailing_address.one_or_none().json
    compare_addresses(mailing_address, new_mailing_address)

    # check director filing
    directors = PartyRole.get_active_directors(business.id, end_date)
    check_directors(business, directors, director_ceased_id, ceased_directors,
                    active_directors)
Exemple #16
0
async def test_process_cod_mailing_address(app, session):
    """Assert that a COD address change filling can be applied to the model correctly."""
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    end_date = datetime.datetime.utcnow().date()
    # prep director for no change
    filing_data = copy.deepcopy(COD_FILING_TWO_ADDRESSES)

    # setup
    business = create_business(identifier)
    business.save()

    directors = PartyRole.get_active_directors(business.id, end_date)
    assert len(directors) == 0

    # create filing
    business_id = business.id
    filing_data['filing']['changeOfDirectors']['directors'][0]['actions'] = [
        'appointed'
    ]
    filing_data['filing']['changeOfDirectors']['directors'][1]['actions'] = [
        'appointed'
    ]
    filing_id = (create_filing(payment_id, filing_data, business_id)).id
    filing_msg = {'filing': {'id': filing_id}}
    # TEST
    await process_filing(filing_msg, app)

    business = Business.find_by_internal_id(business_id)

    directors = PartyRole.get_active_directors(business.id, end_date)

    has_mailing = list(
        filter(lambda x: x.party.mailing_address is not None, directors))
    no_mailing = list(
        filter(lambda x: x.party.mailing_address is None, directors))

    assert len(has_mailing) == 1
    assert has_mailing[0].party.mailing_address.street == 'test mailing 1'
    assert no_mailing[0].party.mailing_address is None

    # Add/update mailing address to a director

    del filing_data['filing']['changeOfDirectors']['directors'][0]
    filing_data['filing']['changeOfDirectors']['directors'][0]['actions'] = [
        'addressChanged'
    ]

    mailing_address = {
        'streetAddress': 'test mailing 2',
        'streetAddressAdditional': 'test line 1',
        'addressCity': 'testcity',
        'addressCountry': 'Canada',
        'addressRegion': 'BC',
        'postalCode': 'T3S T3R',
        'deliveryInstructions': 'director1'
    }

    filing_data['filing']['changeOfDirectors']['directors'][0][
        'mailingAddress'] = mailing_address

    payment_id = str(random.SystemRandom().getrandbits(0x58))
    filing_id = (create_filing(payment_id, filing_data, business_id)).id
    filing_msg = {'filing': {'id': filing_id}}
    await process_filing(filing_msg, app)

    business = Business.find_by_internal_id(business_id)

    directors = PartyRole.get_active_directors(business.id, end_date)
    # Get modified data
    filing = Filing.find_by_id(filing_id)

    # check it out
    assert len(
        list(filter(lambda x: x.party.mailing_address is not None,
                    directors))) == 2
    assert filing.business_id == business_id
    assert filing.status == Filing.Status.COMPLETED.value
Exemple #17
0
async def test_process_cod_filing(app, session):
    """Assert that an AR filling can be applied to the model correctly."""
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    business = create_business(identifier)
    end_date = datetime.datetime.utcnow().date()
    # prep director for no change
    filing_data = copy.deepcopy(COD_FILING)
    directors = filing_data['filing']['changeOfDirectors']['directors']
    director_party1 = create_party(business.id, directors[0])
    role1 = {
        'roleType': 'director',
        'appointmentDate': directors[0].get('appointmentDate'),
        'cessationDate': directors[0].get('cessationDate')
    }
    director1 = create_role(party=director_party1, role_info=role1)
    # prep director for name change
    director_party2_dict = directors[1]
    director_party2_dict['officer']['firstName'] = director_party2_dict[
        'officer']['prevFirstName']
    director_party2_dict['officer']['middleInitial'] = director_party2_dict[
        'officer']['prevMiddleInitial']
    director_party2_dict['officer']['lastName'] = director_party2_dict[
        'officer']['prevLastName']
    director_party2 = create_party(business.id, director_party2_dict)
    role2 = {
        'roleType': 'director',
        'appointmentDate': director_party2_dict.get('appointmentDate'),
        'cessationDate': director_party2_dict.get('cessationDate')
    }
    director2 = create_role(party=director_party2, role_info=role2)
    # prep director for cease
    director_party3 = create_party(business.id, directors[2])
    role3 = {
        'roleType': 'director',
        'appointmentDate': directors[3].get('appointmentDate'),
        'cessationDate': directors[3].get('cessationDate')
    }
    director3 = create_role(party=director_party3, role_info=role3)
    # prep director for address change
    director_party4_dict = directors[3]
    director_party4_dict['deliveryAddress'][
        'streetAddress'] = 'should get changed'
    director_party4 = create_party(business.id, director_party4_dict)
    role4 = {
        'roleType': 'director',
        'appointmentDate': director_party4_dict.get('appointmentDate'),
        'cessationDate': director_party4_dict.get('cessationDate')
    }
    director4 = create_role(party=director_party4, role_info=role4)

    # list of active/ceased directors in test filing
    ceased_directors, active_directors = active_ceased_lists(COD_FILING)

    # setup
    business.party_roles.append(director1)
    business.party_roles.append(director2)
    business.party_roles.append(director3)
    business.party_roles.append(director4)
    business.save()
    director_ceased_id = director3.id
    # check that adding the director during setup was successful
    directors = PartyRole.get_parties_by_role(
        business.id, PartyRole.RoleTypes.DIRECTOR.value)
    assert len(directors) == 4
    # create filing
    business_id = business.id
    filing_id = (create_filing(payment_id, COD_FILING, business.id)).id
    filing_msg = {'filing': {'id': filing_id}}

    # TEST
    await process_filing(filing_msg, app)

    # Get modified data
    filing = Filing.find_by_id(filing_id)
    business = Business.find_by_internal_id(business_id)

    # check it out
    assert filing.transaction_id
    assert filing.business_id == business_id
    assert filing.status == Filing.Status.COMPLETED.value

    directors = PartyRole.get_active_directors(business.id, end_date)
    check_directors(business, directors, director_ceased_id, ceased_directors,
                    active_directors)
def process(business: Business, filing: Dict):  # pylint: disable=too-many-branches;
    """Render the change_of_directors onto the business model objects."""
    new_directors = filing['changeOfDirectors'].get('directors')
    new_director_names = []

    for new_director in new_directors:  # pylint: disable=too-many-nested-blocks;
        # Applies only for filings coming from colin.
        if filing.get('colinIds'):
            director_found = False
            current_new_director_name = \
                new_director['officer'].get('firstName') + new_director['officer'].get('middleInitial', '') + \
                new_director['officer'].get('lastName')
            new_director_names.append(current_new_director_name.upper())

            for director in PartyRole.get_parties_by_role(
                    business.id, PartyRole.RoleTypes.DIRECTOR.value):
                existing_director_name = \
                    director.party.first_name + director.party.middle_initial + director.party.last_name
                if existing_director_name.upper(
                ) == current_new_director_name.upper():
                    # Creates a new director record in Lear if a matching ceased director exists in Lear
                    # and the colin json contains the same director record with cessation date null.
                    if director.cessation_date is not None and new_director.get(
                            'cessationDate') is None:
                        director_found = False
                    else:
                        director_found = True
                        if new_director.get('cessationDate'):
                            new_director['actions'] = ['ceased']
                        else:
                            # For force updating address always as of now.
                            new_director['actions'] = ['modified']
                    break
            if not director_found:
                new_director['actions'] = ['appointed']

        if 'appointed' in new_director['actions']:

            # add new diretor party role to the business
            party = create_party(business_id=business.id,
                                 party_info=new_director)
            role = {
                'roleType': 'Director',
                'appointmentDate': new_director.get('appointmentDate'),
                'cessationDate': new_director.get('cessationDate')
            }
            new_director_role = create_role(party=party, role_info=role)
            business.party_roles.append(new_director_role)

        if any([action != 'appointed' for action in new_director['actions']]):
            # get name of director in json for comparison *
            new_director_name = \
                new_director['officer'].get('firstName') + new_director['officer'].get('middleInitial', '') + \
                new_director['officer'].get('lastName') \
                if 'nameChanged' not in new_director['actions'] \
                else new_director['officer'].get('prevFirstName') + \
                new_director['officer'].get('prevMiddleInitial') + new_director['officer'].get('prevLastName')
            if not new_director_name:
                logger.error('Could not resolve director name from json %s.',
                             new_director)
                raise QueueException

            for director in PartyRole.get_parties_by_role(
                    business.id, PartyRole.RoleTypes.DIRECTOR.value):
                # get name of director in database for comparison *
                director_name = director.party.first_name + director.party.middle_initial + director.party.last_name
                # Update only an active director
                if director_name.upper() == new_director_name.upper(
                ) and director.cessation_date is None:
                    update_director(director=director, new_info=new_director)
                    break

    if filing.get('colinIds'):
        for director in PartyRole.get_parties_by_role(
                business.id, PartyRole.RoleTypes.DIRECTOR.value):
            # get name of director in database for comparison *
            director_name = director.party.first_name + director.party.middle_initial + director.party.last_name
            if director_name.upper(
            ) not in new_director_names and director.cessation_date is None:
                director.cessation_date = datetime.utcnow()
    if not (new_directors := filing['changeOfDirectors'].get('directors')):
        return

    business.last_cod_date = filing_meta.application_date
    new_director_names = []

    for new_director in new_directors:  # pylint: disable=too-many-nested-blocks;
        # Applies only for filings coming from colin.
        if filing.get('colinIds'):
            director_found = False
            current_new_director_name = \
                new_director['officer'].get('firstName') + new_director['officer'].get('middleInitial', '') + \
                new_director['officer'].get('lastName')
            new_director_names.append(current_new_director_name.upper())

            for director in PartyRole.get_parties_by_role(business.id, PartyRole.RoleTypes.DIRECTOR.value):
                existing_director_name = \
                    director.party.first_name + director.party.middle_initial + director.party.last_name
                if existing_director_name.upper() == current_new_director_name.upper():
                    # Creates a new director record in Lear if a matching ceased director exists in Lear
                    # and the colin json contains the same director record with cessation date null.
                    if director.cessation_date is not None and new_director.get('cessationDate') is None:
                        director_found = False
                    else:
                        director_found = True
                        if new_director.get('cessationDate'):
                            new_director['actions'] = ['ceased']
                        else:
                            # For force updating address always as of now.
                            new_director['actions'] = ['modified']
                    break
Exemple #20
0
def test_find_party_by_name(session):
    """Assert the find_party_by_name method works as expected."""
    # setup
    identifier = 'CP1234567'
    business = factory_business(identifier)
    person = Party(
        first_name='Michael',
        last_name='Crane',
        middle_initial='Joe',
        title='VP',
    )
    person.save()
    no_middle_initial = Party(
        first_name='Testing',
        last_name='NoMiddleInitial',
        middle_initial='',
    )
    no_middle_initial.save()
    org = Party(
        organization_name='testOrg',
        party_type=Party.PartyTypes.ORGANIZATION.value
    )
    org.save()
    # sanity check
    assert person.id
    assert org.id
    director1 = PartyRole(
        role=PartyRole.RoleTypes.DIRECTOR.value,
        appointment_date=datetime.datetime(2017, 5, 17),
        cessation_date=None,
        party_id=person.id,
        business_id=business.id
    )
    director1.save()
    director2 = PartyRole(
        role=PartyRole.RoleTypes.DIRECTOR.value,
        appointment_date=datetime.datetime(2017, 5, 17),
        cessation_date=None,
        party_id=no_middle_initial.id,
        business_id=business.id
    )
    director2.save()
    completing_party = PartyRole(
        role=PartyRole.RoleTypes.COMPLETING_PARTY.value,
        appointment_date=datetime.datetime(2017, 5, 17),
        cessation_date=None,
        party_id=org.id,
        business_id=business.id
    )
    completing_party.save()
    # call method
    should_be_none = PartyRole.find_party_by_name(
        business_id=business.id,
        first_name='Test',
        last_name='Test',
        middle_initial='',
        org_name=''
    )
    should_not_find_michael = PartyRole.find_party_by_name(
        business_id=business.id,
        first_name='Michael',
        last_name='Crane',
        middle_initial='',
        org_name=''
    )
    should_find_michael = PartyRole.find_party_by_name(
        business_id=business.id,
        first_name='Michael',
        last_name='Crane',
        middle_initial='Joe',
        org_name=''
    )
    should_not_find_testing = PartyRole.find_party_by_name(
        business_id=business.id,
        first_name='Testing',
        last_name='NoMiddleInitial',
        middle_initial='T',
        org_name=''
    )
    should_find_testing = PartyRole.find_party_by_name(
        business_id=business.id,
        first_name='Testing',
        last_name='NoMiddleInitial',
        middle_initial='',
        org_name=''
    )
    should_find_testorg = PartyRole.find_party_by_name(
        business_id=business.id,
        first_name='',
        last_name='',
        middle_initial='',
        org_name='testorg'
    )
    # check values
    assert not should_be_none
    assert not should_not_find_michael
    assert not should_not_find_testing
    assert should_find_michael.id == person.id
    assert should_find_testing.id == no_middle_initial.id
    assert should_find_testorg.id == org.id