Ejemplo n.º 1
0
def test_process_filing_completed(app, session):
    """Assert that an AR filling status is set to completed once processed."""
    from entity_filer.worker import process_filing
    from legal_api.models import Business, Filing

    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'

    # setup
    business = create_business(identifier)
    business_id = business.id
    filing_id = (create_filing(payment_id, AR_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.business_id == business_id
    assert filing.status == Filing.Status.COMPLETED.value
    assert filing.transaction_id
    assert business.last_agm_date
    assert business.last_ar_date
Ejemplo n.º 2
0
def test_process_coa_filing(app, session):
    """Assert that an AR filling can be applied to the model correctly."""
    from entity_filer.worker import process_filing
    from entity_filer.worker import get_filing_by_payment_id
    from legal_api.models import Business, Filing

    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    new_delivery_address = COA_FILING['filing']['changeOfAddress']['deliveryAddress']
    new_mailing_address = COA_FILING['filing']['changeOfAddress']['mailingAddress']

    # setup
    business = create_business(identifier)
    business_id = business.id
    create_filing(payment_id, COA_FILING, business.id)
    payment_token = {'paymentToken': {'id': payment_id, 'statusCode': Filing.Status.COMPLETED.value}}

    # TEST
    process_filing(payment_token, app)

    # Get modified data
    filing = get_filing_by_payment_id(payment_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

    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)
Ejemplo n.º 3
0
    def _get_report(self):
        if self._report_key == 'correction':
            self._report_key = self._filing.filing_json['filing'][
                'correction']['correctedFilingType']
        elif self._report_key == 'alteration':
            self._report_key = 'alterationNotice'
        if self._filing.business_id:
            self._business = Business.find_by_internal_id(
                self._filing.business_id)
            Report._populate_business_info_to_filing(self._filing,
                                                     self._business)
        headers = {
            'Authorization': 'Bearer {}'.format(jwt.get_token_auth_header()),
            'Content-Type': 'application/json'
        }
        data = {
            'reportName':
            self._get_report_filename(),
            'template':
            "'" +
            base64.b64encode(bytes(self._get_template(), 'utf-8')).decode() +
            "'",
            'templateVars':
            self._get_template_data()
        }
        response = requests.post(url=current_app.config.get('REPORT_SVC_URL'),
                                 headers=headers,
                                 data=json.dumps(data))

        if response.status_code != HTTPStatus.OK:
            return jsonify(message=str(response.content)), response.status_code
        return response.content, response.status_code
Ejemplo n.º 4
0
async def test_process_ar_filing_no_agm(app, session):
    """Assert that a no agm AR filling can be applied to the model correctly."""
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'

    # setup
    business = create_business(identifier)
    business_id = business.id
    now = datetime.date(2020, 9, 17)
    ar_date = datetime.date(2020, 8, 5)
    agm_date = None
    ar = copy.deepcopy(ANNUAL_REPORT)
    ar['filing']['business']['identifier'] = identifier
    ar['filing']['annualReport']['annualReportDate'] = ar_date.isoformat()
    ar['filing']['annualReport']['annualGeneralMeetingDate'] = None

    # TEST
    with freeze_time(now):
        filing = create_filing(payment_id, ar, business.id)
        filing_id = filing.id
        filing_msg = {'filing': {'id': filing_id}}
        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 business.last_agm_date == agm_date
    assert datetime.datetime.date(business.last_ar_date) == ar_date
Ejemplo n.º 5
0
async def test_process_coa_filing(app, session):
    """Assert that a COD filling can be applied to the model correctly."""
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    new_delivery_address = COA_FILING['filing']['changeOfAddress']['offices']['registeredOffice']['deliveryAddress']
    new_mailing_address = COA_FILING['filing']['changeOfAddress']['offices']['registeredOffice']['mailingAddress']

    # setup
    business = create_business(identifier)
    business_id = business.id
    filing_id = (create_filing(payment_id, COA_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

    register_office = business.offices.filter_by(office_type='registeredOffice').one_or_none()

    delivery_address = register_office.addresses.filter_by(address_type='delivery').one_or_none().json
    compare_addresses(delivery_address, new_delivery_address)
    mailing_address = register_office.addresses.filter_by(address_type='mailing').one_or_none().json
    compare_addresses(mailing_address, new_mailing_address)
Ejemplo n.º 6
0
def get_comments(identifier, comment_id=None):
    """Return a JSON object with meta information about the Service."""
    # basic checks
    if identifier.startswith('T'):
        filing_model = FilingModel.get_temp_reg_filing(identifier)
        business = Business.find_by_internal_id(filing_model.business_id)
    else:
        business = Business.find_by_identifier(identifier)
    err_msg, err_code = _basic_checks(identifier, business, request)
    if err_msg:
        return jsonify(err_msg), err_code

    comments = db.session.query(Comment).filter(
        Comment.business_id == business.id, Comment.filing_id.is_(None))

    if comment_id:
        comment = comments.filter(Comment.id == comment_id).one_or_none()
        if not comment:
            return jsonify({'message': f'Comment {comment_id} not found'
                            }), HTTPStatus.NOT_FOUND

        return jsonify(comment.json)

    rv = []
    for comment in comments:
        rv.append(comment.json)

    return jsonify(comments=rv)
Ejemplo n.º 7
0
def test_process_ar_filing(app, session):
    """Assert that an AR filling can be applied to the model correctly."""
    from entity_filer.worker import process_filing
    from entity_filer.worker import get_filing_by_payment_id
    from legal_api.models import Business, Filing

    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    agm_date = datetime.date.fromisoformat(AR_FILING['filing']['annualReport'].get('annualGeneralMeetingDate'))
    ar_date = datetime.date.fromisoformat(COMBINED_FILING['filing']['annualReport'].get('annualReportDate'))

    # setup
    business = create_business(identifier)
    business_id = business.id
    create_filing(payment_id, AR_FILING, business.id)
    payment_token = {'paymentToken': {'id': payment_id, 'statusCode': Filing.Status.COMPLETED.value}}

    # TEST
    process_filing(payment_token, app)

    # Get modified data
    filing = get_filing_by_payment_id(payment_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
Ejemplo n.º 8
0
def _basic_checks(identifier, filing_id, client_request) -> Tuple[dict, int]:
    """Perform basic checks to ensure put can do something."""
    json_input = client_request.get_json()
    if client_request.method == 'POST' and not json_input:
        return ({
            'message':
            f'No filing json data in body of post for {identifier}.'
        }, HTTPStatus.BAD_REQUEST)

    if client_request.method == 'GET' and identifier.startswith('T'):
        filing_model = Filing.get_temp_reg_filing(identifier)
        business = Business.find_by_internal_id(filing_model.business_id)
    else:
        business = Business.find_by_identifier(identifier)

    filing = Filing.find_by_id(filing_id)

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

    # check that filing belongs to this business
    if not filing or filing.business_id != business.id:
        return ({
            'message': f'Filing {filing_id} not found'
        }, HTTPStatus.NOT_FOUND)

    return (None, None)
Ejemplo n.º 9
0
def test_process_ar_reminder_email(app, session):
    """Assert that the ar reminder notification can be processed."""
    # setup filing + business for email
    filing = prep_incorp_filing(session, 'BC1234567', '1', 'COMPLETED')
    business = Business.find_by_internal_id(filing.business_id)
    business.legal_type = 'BC'
    business.legal_name = 'test business'
    token = 'token'
    # test processor
    with patch.object(AccountService, 'get_bearer_token', return_value=token):
        with patch.object(ar_reminder_notification,
                          'get_recipient_from_auth',
                          return_value='*****@*****.**'):
            with patch.object(worker, 'send_email',
                              return_value='success') as mock_send_email:
                worker.process_email(
                    {
                        'email': {
                            'businessId': filing.business_id,
                            'type': 'annualReport',
                            'option': 'reminder',
                            'arFee': '100',
                            'arYear': '2021'
                        }
                    }, app)

                call_args = mock_send_email.call_args
                assert call_args[0][0]['content'][
                    'subject'] == 'test business 2021 Annual Report Reminder'
                assert call_args[0][0]['recipients'] == '*****@*****.**'
                assert call_args[0][0]['content']['body']
                assert call_args[0][0]['content']['attachments'] == []
                assert call_args[0][1] == token
Ejemplo n.º 10
0
async def test_worker_alteration(app, session, mocker, orig_legal_type,
                                 new_legal_type):
    """Assert the worker process calls the alteration correctly."""
    identifier = 'BC1234567'
    business = create_business(identifier, legal_type=orig_legal_type)
    filing = copy.deepcopy(ALTERATION_FILING_TEMPLATE)
    filing['filing']['business']['legalType'] = orig_legal_type
    filing['filing']['alteration']['business']['legalType'] = new_legal_type

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

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

    # 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)
    mocker.patch(
        'entity_filer.filing_processors.filing_components.name_request.consume_nr',
        return_value=None)
    mocker.patch(
        'entity_filer.filing_processors.filing_components.business_profile.update_business_profile',
        return_value=None)
    mocker.patch('legal_api.services.bootstrap.AccountService.update_entity',
                 return_value=None)

    # Test
    await process_filing(filing_msg, app)

    # Check outcome
    business = Business.find_by_internal_id(business.id)
    assert business.legal_type == new_legal_type
Ejemplo n.º 11
0
def get_documents(identifier: str,
                  filing_id: int,
                  legal_filing_name: str = None):
    """Return a JSON object with meta information about the Service."""
    # basic checks
    if not authorized(identifier, jwt, [
            'view',
    ]):
        return jsonify(message=get_error_message(ErrorCode.NOT_AUTHORIZED, **{
            'identifier': identifier
        })), HTTPStatus.UNAUTHORIZED

    if identifier.startswith('T'):
        filing_model = FilingModel.get_temp_reg_filing(identifier)
        business = Business.find_by_internal_id(filing_model.business_id)
    else:
        business = Business.find_by_identifier(identifier)

    if not business and not identifier.startswith('T'):
        return jsonify(message=get_error_message(ErrorCode.MISSING_BUSINESS, **
                                                 {'identifier': identifier
                                                  })), HTTPStatus.NOT_FOUND

    if not (filing := Filing.get(identifier, filing_id)):
        return jsonify(message=get_error_message(
            ErrorCode.FILING_NOT_FOUND, **{
                'filing_id': filing_id,
                'identifier': identifier
            })), HTTPStatus.NOT_FOUND
Ejemplo n.º 12
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
Ejemplo n.º 13
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
Ejemplo n.º 14
0
def test_process_filing_failed(app, session):
    """Assert that an AR filling status is set to error if payment transaction failed."""
    from entity_filer.worker import process_filing
    from entity_filer.worker import get_filing_by_payment_id
    from legal_api.models import Business, Filing

    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'

    # setup
    business = create_business(identifier)
    business_id = business.id
    create_filing(payment_id, AR_FILING, business.id)
    payment_token = {'paymentToken': {'id': payment_id, 'statusCode': 'TRANSACTION_FAILED'}}

    # TEST
    process_filing(payment_token, app)

    # Get modified data
    filing = get_filing_by_payment_id(payment_id)
    business = Business.find_by_internal_id(business_id)

    # check it out
    assert filing.business_id == business_id
    assert filing.status == Filing.Status.ERROR.value
    assert not business.last_agm_date
    assert not business.last_ar_date
Ejemplo n.º 15
0
async def test_process_filing_completed(app, session, mocker):
    """Assert that an AR filling status is set to completed once processed."""
    from entity_filer.worker import publish_email_message
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'

    # 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)

    # setup
    business = create_business(identifier, legal_type='CP')
    business_id = business.id
    filing_id = (create_filing(payment_id, AR_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.business_id == business_id
    assert filing.status == Filing.Status.COMPLETED.value
    assert filing.transaction_id
    assert business.last_agm_date
    assert business.last_ar_date
Ejemplo n.º 16
0
def process_filing(payment_token, flask_app):
    """Render the filings contained in the submission."""
    if not flask_app:
        raise QueueException('Flask App not available.')

    with flask_app.app_context():

        # try to find the filing 5 times before putting back on the queue - in case payment token ends up on the queue
        # before it is assigned to filing.
        counter = 1
        filing_submission = None
        while not filing_submission and counter <= 5:
            filing_submission = get_filing_by_payment_id(payment_token['paymentToken'].get('id'))
            counter += 1
            sleep(0.2)
        if not filing_submission:
            raise FilingException

        if filing_submission.status == Filing.Status.COMPLETED.value:
            logger.warning('Queue: Attempting to reprocess business.id=%s, filing.id=%s payment=%s',
                           filing_submission.business_id, filing_submission.id, payment_token)
            return

        if payment_token['paymentToken'].get('statusCode') == 'TRANSACTION_FAILED':
            # TODO - need to surface TRANSACTION_FAILED, but Filings manages its own status
            # filing_submission.status = Filing.Status.ERROR
            filing_submission.payment_completion_date = datetime.datetime.utcnow()
            db.session.add(filing_submission)
            db.session.commit()
            return

        legal_filings = filing_submission.legal_filings()
        # TODO: handle case where there are no legal_filings

        uow = versioning_manager.unit_of_work(db.session)
        transaction = uow.create_transaction(db.session)

        if not payment_token['paymentToken'].get('statusCode') == 'TRANSACTION_FAILED':
            if not payment_token['paymentToken'].get('statusCode') == Filing.Status.COMPLETED.value:
                logger.error('Unknown payment status given: %s', payment_token['paymentToken'].get('statusCode'))
                raise QueueException

            business = Business.find_by_internal_id(filing_submission.business_id)

            for filing in legal_filings:
                if filing.get('annualReport'):
                    annual_report.process(business, filing)
                if filing.get('changeOfAddress'):
                    change_of_address.process(business, filing)
                if filing.get('changeOfDirectors'):
                    change_of_directors.process(business, filing)

            filing_submission.transaction_id = transaction.id
            db.session.add(business)

        filing_submission.payment_completion_date = datetime.datetime.utcnow()
        db.session.add(filing_submission)
        db.session.commit()
        return
Ejemplo n.º 17
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.º 18
0
def process_filing(filing_msg: Dict, flask_app: Flask):
    """Render the filings contained in the submission."""
    if not flask_app:
        raise QueueException('Flask App not available.')

    with flask_app.app_context():

        filing_submission = Filing.find_by_id(filing_msg['filing']['id'])

        if not filing_submission:
            raise QueueException

        if filing_submission.status == Filing.Status.COMPLETED.value:
            logger.warning('QueueFiler: Attempting to reprocess business.id=%s, filing.id=%s filing=%s',
                           filing_submission.business_id, filing_submission.id, filing_msg)
            return

        legal_filings = filing_submission.legal_filings()

        if legal_filings:

            uow = versioning_manager.unit_of_work(db.session)
            transaction = uow.create_transaction(db.session)

            business = Business.find_by_internal_id(filing_submission.business_id)

            for filing in legal_filings:
                if filing.get('annualReport'):
                    annual_report.process(business, filing)

                elif filing.get('changeOfAddress'):
                    change_of_address.process(business, filing)

                elif filing.get('changeOfDirectors'):
                    filing['colinIds'] = filing_submission.colin_event_ids
                    change_of_directors.process(business, filing)

                elif filing.get('changeOfName'):
                    change_of_name.process(business, filing)

                elif filing.get('specialResolution'):
                    pass  # nothing to do here

                elif filing.get('voluntaryDissolution'):
                    voluntary_dissolution.process(business, filing)

                elif filing.get('incorporationApplication'):
                    incorporation_filing.process(business, filing, flask_app)

            filing_submission.transaction_id = transaction.id
            filing_submission.set_processed()

            db.session.add(business)
            db.session.add(filing_submission)
            db.session.commit()

            publish_event(business, filing_submission)
        return
Ejemplo n.º 19
0
 def get_business_revision_after_filing(filing_id, business_id) -> dict:
     """Consolidates the business info as of a particular transaction."""
     business = Business.find_by_internal_id(business_id)
     filing = Filing.find_by_id(filing_id)
     business_version = version_class(Business)
     business_revision = db.session.query(business_version) \
         .filter(business_version.transaction_id > filing.transaction_id) \
         .filter(business_version.operation_type != 2) \
         .filter(business_version.id == business.id) \
         .order_by(business_version.transaction_id).one_or_none()
     return VersionedBusinessDetailsService.business_revision_json(
         business_revision, business.json())
Ejemplo n.º 20
0
 def get_business_revision_before_filing(filing_id, business_id) -> dict:
     """Consolidates the business info of the previous filing."""
     business = Business.find_by_internal_id(business_id)
     filing = Filing.find_by_id(filing_id)
     business_version = version_class(Business)
     business_revision = db.session.query(business_version) \
         .filter(business_version.transaction_id < filing.transaction_id) \
         .filter(business_version.operation_type != 2) \
         .filter(business_version.id == business.id) \
         .order_by(business_version.transaction_id.desc()).first()
     return VersionedBusinessDetailsService.business_revision_json(
         business_revision, business.json())
Ejemplo n.º 21
0
def update_and_validate_party_and_roles(business, parties_structure, roles_count, parties_count):
    """Validate that party and party roles get created."""
    party_id_list = []
    err = update_parties(business, parties_structure['parties'])
    business.save()
    check_business = Business.find_by_internal_id(business.id)
    check_party_roles = check_business.party_roles.all()
    for role in check_party_roles:
        if role.party_id not in party_id_list:
            party_id_list.append(role.party_id)
    assert len(check_party_roles) == roles_count
    assert len(party_id_list) == parties_count
    assert not err
Ejemplo n.º 22
0
    def get(status=None):
        """Get filings by status formatted in json."""
        pending_filings = []
        filings = []

        if status is None:
            pending_filings = Filing.get_completed_filings_for_colin()
            for filing in pending_filings:
                filing_json = filing.filing_json
                business = Business.find_by_internal_id(filing.business_id)
                if filing_json and filing.filing_type != 'lear_epoch' and \
                        (filing.filing_type != 'correction' or business.legal_type != business.LegalTypes.COOP.value):
                    filing_json['filingId'] = filing.id
                    filing_json['filing']['header'][
                        'learEffectiveDate'] = filing.effective_date.isoformat(
                        )
                    if not filing_json['filing']['business'].get('legalName'):
                        business = Business.find_by_internal_id(
                            filing.business_id)
                        filing_json['filing']['business'][
                            'legalName'] = business.legal_name
                    if filing.filing_type == 'correction':
                        colin_ids = \
                            ColinEventId.get_by_filing_id(filing_json['filing']['correction']['correctedFilingId'])
                        if not colin_ids:
                            continue
                        filing_json['filing']['correction'][
                            'correctedFilingColinId'] = colin_ids[
                                0]  # should only be 1
                    filings.append(filing_json)
            return jsonify(filings), HTTPStatus.OK

        pending_filings = Filing.get_all_filings_by_status(status)
        for filing in pending_filings:
            filings.append(filing.json)
        return jsonify(filings), HTTPStatus.OK
Ejemplo n.º 23
0
async def test_cb_subscription_handler(app, session, stan_server, event_loop,
                                       client_id, entity_stan, future):
    """Assert that payment tokens can be retrieved and decoded from the Queue."""
    # Call back for the subscription
    from entity_filer.worker import cb_subscription_handler
    from entity_filer.worker import get_filing_by_payment_id
    from legal_api.models import Business
    from tests.unit import create_filing, AR_FILING, create_business

    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'
    agm_date = datetime.date.fromisoformat(
        AR_FILING['filing']['annualReport'].get('annualGeneralMeetingDate'))
    ar_date = datetime.date.fromisoformat(
        AR_FILING['filing']['annualReport'].get('annualReportDate'))

    # setup
    business = create_business(identifier)
    business_id = business.id
    create_filing(payment_id, AR_FILING, business.id)

    # register the handler to test it
    entity_subject = await subscribe_to_queue(entity_stan,
                                              cb_subscription_handler)

    # add payment tokens to queue
    await helper_add_payment_to_queue(entity_stan,
                                      entity_subject,
                                      payment_id=payment_id,
                                      status_code='COMPLETED')

    try:
        await asyncio.sleep(1)
        # await asyncio.wait_for(cb_future, 2, loop=event_loop)
    except Exception as err:
        print(err)

    # Get modified data
    filing = get_filing_by_payment_id(payment_id)
    business = Business.find_by_internal_id(business_id)

    # check it out
    assert filing.transaction_id
    assert filing.business_id == business_id
    assert datetime.datetime.date(business.last_agm_date) == agm_date
    assert datetime.datetime.date(business.last_ar_date) == ar_date
Ejemplo n.º 24
0
def test_incorporation_filing(app, session):
    """Assert we can retrieve a new corp number from COLIN and incorporate a business."""
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    filing = copy.deepcopy(INCORP_FILING)
    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}}

    assert business.identifier == 'NR 1234567'

    process_filing(filing_msg, app)
    filing = Filing.find_by_id(filing_id)
    business = Business.find_by_internal_id(filing.business_id)
    assert business.identifier != 'NR 1234567'
Ejemplo n.º 25
0
def update_and_validate_office(business, office_structure):
    """Validate that office gets created."""
    err = update_offices(business, office_structure['offices'])
    business.save()
    check_business = Business.find_by_internal_id(business.id)
    check_offices = check_business.offices.all()
    assert len(check_offices) == 2
    check_office_structure = {'offices': {}}
    for s in check_offices:
        check_office_structure['offices'][s.office_type] = {}
        for address in s.addresses:
            check_office_structure['offices'][
                s.office_type][f'{address.address_type}Address'] = address.json
    stripped_dict = strip_keys_from_dict(check_office_structure,
                                         ['id', 'addressType'])
    assert stripped_dict == office_structure
    assert not err
Ejemplo n.º 26
0
 def get_company_details_revision(filing_id, business_id) -> dict:
     """Consolidates company details upto the given transaction id of a filing."""
     company_profile_json = {}
     business = Business.find_by_internal_id(business_id)
     filing = Filing.find_by_id(filing_id)
     company_profile_json['business'] = \
         VersionedBusinessDetailsService.get_business_revision(filing.transaction_id, business)
     company_profile_json['parties'] = \
         VersionedBusinessDetailsService.get_party_role_revision(filing.transaction_id, business_id)
     company_profile_json['offices'] = \
         VersionedBusinessDetailsService.get_office_revision(filing.transaction_id, business_id)
     company_profile_json['shareClasses'] = \
         VersionedBusinessDetailsService.get_share_class_revision(filing.transaction_id, business_id)
     company_profile_json['nameTranslations'] = \
         VersionedBusinessDetailsService.get_name_translations_revision(filing.transaction_id, business_id)
     company_profile_json['resolutions'] = \
         VersionedBusinessDetailsService.get_resolution_dates_revision(filing.transaction_id, business_id)
     return company_profile_json
Ejemplo n.º 27
0
def test_manage_share_structure__resolution_dates(app, session, test_name,
                                                  resolution_dates,
                                                  expected_error):
    """Assert that the corp share resolution date gets set."""
    new_data = {'shareStructure': {'resolutionDates': resolution_dates}}

    business = Business()
    business.save()
    err = shares.update_share_structure(business, new_data['shareStructure'])
    business.save()

    check_business = Business.find_by_internal_id(business.id)
    check_resolution = check_business.resolutions.all()

    if err:
        assert err == expected_error
    else:
        assert len(check_resolution) == len(resolution_dates)
        assert set(resolution_dates) == \
            set([x.resolution_date.isoformat() for x in check_resolution])
Ejemplo n.º 28
0
async def test_worker_alteration(app, session, orig_legal_type, new_legal_type):
    """Assert the worker process calls the alteration correctly."""
    identifier = 'BC1234567'
    business = create_business(identifier, legal_type=orig_legal_type)
    filing = copy.deepcopy(ALTERATION_FILING_TEMPLATE)
    filing['filing']['business']['legalType'] = orig_legal_type
    filing['filing']['alteration']['business']['legalType'] = new_legal_type
    filing['filing']['alteration']['nameTranslations'] = [{'name': 'A5 Ltd.'}]

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

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

    # Test
    await process_filing(filing_msg, app)

    # Check outcome
    business = Business.find_by_internal_id(business.id)
    assert business.legal_type == new_legal_type
Ejemplo n.º 29
0
def test_manage_share_structure__share_classes(app, session, test_name,
                                               share_structure,
                                               expected_error):
    """Assert that the corp share classes gets set."""
    business = Business()
    business.save()
    err = shares.update_share_structure(business,
                                        share_structure['shareStructure'])
    business.save()

    check_business = Business.find_by_internal_id(business.id)
    check_share_classes = check_business.share_classes.all()

    check_share_structure = {'shareStructure': {'shareClasses': []}}
    for s in check_share_classes:
        check_share_structure['shareStructure']['shareClasses'].append(s.json)

    stripped_dict = strip_keys_from_dict(check_share_structure, ['id'])
    assert stripped_dict == share_structure
    assert not err
Ejemplo n.º 30
0
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