Ejemplo n.º 1
0
def test_director_save_to_business(session):
    """Assert that the director saves correctly."""
    identifier = 'CP1234567'
    business = factory_business(identifier)

    director1 = Director(first_name='Michael',
                         last_name='Crane',
                         middle_initial='Joe',
                         title='VP',
                         appointment_date=datetime.datetime(2020, 5, 17),
                         cessation_date=None)

    director2 = Director(first_name='Scott',
                         last_name='James',
                         middle_initial=None,
                         title='AVP',
                         appointment_date=datetime.datetime(2017, 5, 17),
                         cessation_date=None)

    business.directors.append(director1)
    business.directors.append(director2)
    business.save()

    directors = business.directors.all()
    assert len(directors) == 2
Ejemplo n.º 2
0
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'
    end_date = datetime.datetime.utcnow().date()
    # prep director for no change
    filing_data = copy.deepcopy(COD_FILING)
    director1 = create_director(
        filing_data['filing']['changeOfDirectors']['directors'][0])
    # prep director for name change
    director2 = filing_data['filing']['changeOfDirectors']['directors'][1]
    director2['officer']['firstName'] = director2['officer']['prevFirstName']
    director2['officer']['middleInitial'] = director2['officer'][
        'prevMiddleInitial']
    director2['officer']['lastName'] = director2['officer']['prevLastName']
    director2 = create_director(director2)
    # prep director for cease
    director3 = create_director(
        filing_data['filing']['changeOfDirectors']['directors'][2])
    director_ceased_id = director3.id
    # prep director for address change
    director4 = filing_data['filing']['changeOfDirectors']['directors'][3]
    director4['deliveryAddress']['streetAddress'] = 'should get changed'
    director4 = create_director(director4)

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

    # setup
    business = create_business(identifier)
    business.directors.append(director1)
    business.directors.append(director2)
    business.directors.append(director3)
    business.directors.append(director4)
    business.save()
    # check that adding the director during setup was successful
    directors = Director.get_active_directors(business.id, end_date)
    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
    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 = Director.get_active_directors(business.id, end_date)
    check_directors(business, directors, director_ceased_id, ceased_directors,
                    active_directors)
Ejemplo n.º 3
0
def test_director_save(session):
    """Assert that the director saves correctly."""
    director = Director(first_name='Michael',
                        last_name='Crane',
                        middle_initial='Joe',
                        title='VP',
                        appointment_date=datetime.datetime(2017, 5, 17),
                        cessation_date=None)

    director.save()
    assert director.id
Ejemplo n.º 4
0
    def get(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 = DirectorResource._get_director(
                business, director_id)
            return jsonify(director or msg), code

        # return all active directors as of date query param
        res = []
        end_date = datetime.utcnow().strptime(request.args.get('date'), '%Y-%m-%d').date()\
            if request.args.get('date') else datetime.utcnow().date()
        director_list = Director.get_active_directors(business.id, end_date)
        for director in director_list:
            director_json = director.json
            if business.legal_type == 'CP':
                del director_json['mailingAddress']
            res.append(director_json)

        return jsonify(directors=res)
Ejemplo n.º 5
0
def process(business: Business, filing: Filing):
    """Render the change_of_directors onto the business model objects."""
    new_directors = filing['changeOfDirectors'].get('directors')

    for new_director in new_directors:
        if 'appointed' in new_director['actions']:
            # create address
            address = create_address(new_director['deliveryAddress'], Address.DELIVERY)

            director_to_add = Director(first_name=new_director['officer'].get('firstName', '').upper(),
                                       middle_initial=new_director['officer'].get('middleInitial', '').upper(),
                                       last_name=new_director['officer'].get('lastName', '').upper(),
                                       title=new_director.get('title', '').upper(),
                                       appointment_date=new_director.get('appointmentDate'),
                                       cessation_date=new_director.get('cessationDate'),
                                       delivery_address=address)

            if 'mailingAddress' in new_director.keys():
                mailing_address = create_address(new_director['mailingAddress'], Address.MAILING)
                director_to_add.mailing_address = mailing_address

            # add new director to the list
            business.directors.append(director_to_add)

        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 business.directors:
                # get name of director in database for comparison *
                director_name = director.first_name + director.middle_initial + director.last_name
                if director_name.upper() == new_director_name.upper():
                    update_director(director, new_director)
                    break
Ejemplo n.º 6
0
def create_director(director):
    """Create a director."""
    from legal_api.models import Address, Director
    new_address = Address(
        street=director['deliveryAddress']['streetAddress'],
        city=director['deliveryAddress']['addressCity'],
        country='CA',
        postal_code=director['deliveryAddress']['postalCode'],
        region=director['deliveryAddress']['addressRegion'],
        delivery_instructions=director['deliveryAddress'].get(
            'deliveryInstructions', '').upper())
    new_address.save()
    new_director = Director(
        first_name=director['officer'].get('firstName', '').upper(),
        last_name=director['officer'].get('lastName', '').upper(),
        middle_initial=director['officer'].get('middleInitial', '').upper(),
        appointment_date=director['appointmentDate'],
        cessation_date=None,
        delivery_address=new_address)
    new_director.save()
    return new_director
Ejemplo n.º 7
0
def add_business_directors(business, directors_json):
    for director in directors_json['directors']:
        delivery_address = create_delivery_address(director['deliveryAddress'])

        officer = director['officer']
        d = Director()
        d.first_name = officer['firstName']
        d.last_name = officer['lastName']
        d.middle_initial = officer['middleInitial']
        d.appointment_date = datetime.date.fromisoformat(
            director['appointmentDate'])
        d.title = director['title']
        d.delivery_address = delivery_address
        business.directors.append(d)
Ejemplo n.º 8
0
def update_director(director: Director, new_info: dict):
    """Update director with new info."""
    director.first_name = new_info['officer'].get('firstName', '').upper()
    director.middle_initial = new_info['officer'].get('middleInitial', '').upper()
    director.last_name = new_info['officer'].get('lastName', '').upper()
    director.title = new_info.get('title', '').upper()
    # director.appointment_date = new_info.get('appointmentDate')
    director.cessation_date = new_info.get('cessationDate')
    director.delivery_address = update_address(director.delivery_address, new_info['deliveryAddress'])
    if 'mailingAddress' in new_info.keys():
        if director.mailing_address is None:
            director.mailing_address = create_address(new_info['mailingAddress'], Address.MAILING)
        else:
            director.mailing_address = update_address(director.mailing_address, new_info['mailingAddress'])

    return director
Ejemplo n.º 9
0
def update_director(director: Director, new_info: dict):
    """Update director with new info."""
    director.first_name = new_info['officer'].get('firstName', '').upper()
    director.middle_initial = new_info['officer'].get('middleInitial',
                                                      '').upper()
    director.last_name = new_info['officer'].get('lastName', '').upper()
    director.title = new_info.get('title', '').upper()
    # director.appointment_date = new_info.get('appointmentDate')
    director.cessation_date = new_info.get('cessationDate')
    director.delivery_address = update_address(director.delivery_address,
                                               new_info['deliveryAddress'])

    return director
Ejemplo n.º 10
0
def test_director_json(session):
    """Assert the json format of director."""
    director = Director(first_name='Michael',
                        last_name='Crane',
                        middle_initial='Joe',
                        title='VP',
                        appointment_date=datetime.datetime(2017, 5, 17),
                        cessation_date=None)

    director_json = {
        'appointmentDate': director.appointment_date.date().isoformat(),
        'cessationDate': director.cessation_date,
        'officer': {
            'firstName': director.first_name,
            'lastName': director.last_name,
            'middleInitial': director.middle_initial
        },
        'title': director.title
    }

    assert director.json == director_json
Ejemplo n.º 11
0
def test_process_combined_filing(app, session):
    """Assert that an AR filling can be applied to the model correctly."""
    from legal_api.models import Business, Director, Filing
    from entity_filer.worker import process_filing

    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    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)
    director1 = create_director(
        filing_data['filing']['changeOfDirectors']['directors'][0])
    # prep director for name change
    director2 = filing_data['filing']['changeOfDirectors']['directors'][1]
    director2['officer']['firstName'] = director2['officer']['prevFirstName']
    director2['officer']['middleInitial'] = director2['officer'][
        'prevMiddleInitial']
    director2['officer']['lastName'] = director2['officer']['prevLastName']
    director2 = create_director(director2)
    # prep director for cease
    director3 = create_director(
        filing_data['filing']['changeOfDirectors']['directors'][2])
    director_ceased_id = director3.id
    # prep director for address change
    director4 = filing_data['filing']['changeOfDirectors']['directors'][3]
    director4['deliveryAddress']['streetAddress'] = 'should get changed'
    director4 = create_director(director4)

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

    # setup
    business = create_business(identifier)
    business.directors.append(director1)
    business.directors.append(director2)
    business.directors.append(director3)
    business.directors.append(director4)
    business.save()
    # check that adding the director during setup was successful
    directors = Director.get_active_directors(business.id, end_date)
    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
    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) == agm_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 = Director.get_active_directors(business.id, end_date)
    check_directors(business, directors, director_ceased_id, ceased_directors,
                    active_directors)
Ejemplo n.º 12
0
def test_process_cod_mailing_address(app, session):
    """Assert that an AR filling can be applied to the model correctly."""
    from legal_api.models import Business, Director, Filing
    from entity_filer.worker import process_filing

    # 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 = Director.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
    process_filing(filing_msg, app)

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

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

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

    assert len(has_mailing) == 1
    assert has_mailing[0].mailing_address.street == 'test mailing 1'
    assert no_mailing[0].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}}
    process_filing(filing_msg, app)

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

    directors = Director.get_active_directors(business.id, end_date)
    # Get modified data
    filing = Filing.find_by_id(filing_id)
    business = Business.find_by_internal_id(business_id)

    # check it out
    assert len(list(filter(lambda x: x.mailing_address is not None,
                           directors))) == 2
    assert filing.transaction_id
    assert filing.business_id == business_id
    assert filing.status == Filing.Status.COMPLETED.value

    directors = Director.get_active_directors(business.id, end_date)
Ejemplo n.º 13
0
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('colinId'):
            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 business.directors:
                existing_director_name = director.first_name + director.middle_initial + director.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']:
            # create address
            address = create_address(new_director['deliveryAddress'], Address.DELIVERY)

            director_to_add = Director(first_name=new_director['officer'].get('firstName', '').upper(),
                                       middle_initial=new_director['officer'].get('middleInitial', '').upper(),
                                       last_name=new_director['officer'].get('lastName', '').upper(),
                                       title=new_director.get('title', '').upper(),
                                       appointment_date=new_director.get('appointmentDate'),
                                       cessation_date=new_director.get('cessationDate'),
                                       delivery_address=address)

            # if 'mailingAddress' in new_director and len(new_director['mailingAddress']): <- fails lint
            # if new_director.get('mailingAddress', None): <- slightly more pythonic
            with suppress(KeyError):  # <- since we're only going to do this if the key exists, it's easier to read
                mailing_address = create_address(new_director['mailingAddress'], Address.MAILING)
                director_to_add.mailing_address = mailing_address

            # add new director to the list
            business.directors.append(director_to_add)

        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 business.directors:
                # get name of director in database for comparison *
                director_name = director.first_name + director.middle_initial + director.last_name
                # Update only an active director
                if director_name.upper() == new_director_name.upper() and director.cessation_date is None:
                    update_director(director, new_director)
                    break

    if filing.get('colinId'):
        for director in business.directors:
            # get name of director in database for comparison *
            director_name = director.first_name + director.middle_initial + director.last_name
            if director_name.upper() not in new_director_names:
                director.cessation_date = datetime.utcnow()