Пример #1
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
Пример #2
0
    def post(identifier, filing_id=None):
        """Create a new filing for the business."""
        json_input = request.get_json()
        if not json_input:
            return jsonify({'message':
                            f'No filing json data in body of post for {identifier}.'}), \
                HTTPStatus.BAD_REQUEST

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

        if filing_id:  # checked since we're overlaying routes
            return jsonify({'message':
                            f'Illegal to attempt to create a new filing over an existing filing for {identifier}.'}), \
                HTTPStatus.FORBIDDEN

        try:
            filing = Filing()
            filing.business_id = business.id
            filing.filing_date = datetime.datetime.utcnow()
            filing.filing_json = json_input
            filing.save()
        except BusinessException as err:
            return jsonify({'message': err.error}), err.status_code

        return jsonify(filing.filing_json), HTTPStatus.CREATED
Пример #3
0
def factory_business_model(legal_name,
                           identifier,
                           founding_date,
                           fiscal_year_end_date=None,
                           tax_id=None,
                           dissolution_date=None):
    """Return a valid Business object stamped with the supplied designation."""
    from legal_api.models import Business as BusinessModel
    b = BusinessModel(legal_name=legal_name,
                      identifier=identifier,
                      founding_date=founding_date,
                      fiscal_year_end_date=fiscal_year_end_date,
                      dissolution_date=dissolution_date,
                      tax_id=tax_id)
    b.save()
    return b
Пример #4
0
    def put(identifier, filing_id):
        """Create a new filing for the business."""
        json_input = request.get_json()
        if not json_input:
            return jsonify({'message':
                            f'No filing json data in body of post for {identifier}.'}), \
                HTTPStatus.BAD_REQUEST

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

        rv = db.session.query(Business, Filing). \
            filter(Business.id == Filing.business_id).\
            filter(Business.identifier == identifier).\
            filter(Filing.id == filing_id).\
            one_or_none()
        if not rv:
            return jsonify({'message': f'{identifier} no filings found'
                            }), HTTPStatus.NOT_FOUND

        try:
            filing = rv[1]
            filing.filing_date = datetime.datetime.utcnow()
            filing.filing_json = json_input
            filing.save()
        except BusinessException as err:
            return jsonify({'message': err.error}), err.status_code

        return jsonify(filing.filing_json), HTTPStatus.ACCEPTED
Пример #5
0
    def get(identifier, filing_id=None):
        """Return a JSON object with meta information about the Service."""
        business = Business.find_by_identifier(identifier)

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

        if filing_id:
            rv = db.session.query(Business, Filing). \
                filter(Business.id == Filing.business_id).\
                filter(Business.identifier == identifier).\
                filter(Filing.id == filing_id).\
                one_or_none()
            if not rv:
                return jsonify({'message': f'{identifier} no filings found'
                                }), HTTPStatus.NOT_FOUND

            return jsonify(rv[1].filing_json)

        rv = []
        filings = business.filings.all()
        for filing in filings:
            rv.append(filing.json())

        return jsonify(filings=rv)
Пример #6
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)

        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)
Пример #7
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
        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)
Пример #8
0
    def patch(identifier, filing_id=None):
        """Cancel the payment and resets the filing status to DRAFT."""
        if not filing_id:
            return ({'message':
                     _('No filing id provided for:') + identifier},
                    HTTPStatus.BAD_REQUEST)

        # check authorization
        if not authorized(identifier, jwt, action=['edit']):
            return jsonify({'message':
                            _('You are not authorized to delete a filing for:') + identifier}), \
                HTTPStatus.UNAUTHORIZED

        filing = Business.get_filing_by_id(identifier, filing_id)

        if not filing:
            return jsonify({'message': ('Filing Not Found.')}), \
                HTTPStatus.NOT_FOUND

        try:
            payment_svc_url = '{}/{}'.format(current_app.config.get('PAYMENT_SVC_URL'), filing.payment_token)
            token = jwt.get_token_auth_header()
            headers = {'Authorization': 'Bearer ' + token}
            rv = requests.delete(url=payment_svc_url, headers=headers, timeout=20.0)
            if rv.status_code == HTTPStatus.OK or rv.status_code == HTTPStatus.ACCEPTED:
                filing.reset_filing_to_draft()

        except (exceptions.ConnectionError, exceptions.Timeout) as err:
            current_app.logger.error(f'Payment connection failure for {identifier}: filing:{filing.id}', err)
            return {'message': 'Unable to cancel payment for the filing.'}, HTTPStatus.INTERNAL_SERVER_ERROR

        except BusinessException as err:
            return {'message': err.error}, err.status_code

        return jsonify(filing.json), HTTPStatus.ACCEPTED
Пример #9
0
def test_process_ar_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'

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

    # TEST
    with freeze_time(now):
        filing = create_filing(payment_id, ar, business.id)
        filing_id = filing.id
        filing_msg = {'filing': {'id': filing_id}}
        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
Пример #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
Пример #11
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
Пример #12
0
    def get(identifier, resolution_id=None):
        """Return a JSON of the resolutions."""
        business = Business.find_by_identifier(identifier)

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

        # return the matching resolution
        if resolution_id:
            resolution, msg, code = ResolutionResource._get_resolution(
                business, resolution_id)
            return jsonify(resolution or msg), code

        resolution_list = []

        resolution_type = request.args.get('type')
        if resolution_type:
            resolutions = Resolution.find_by_type(business.id,
                                                  resolution_type.upper())
        else:
            resolutions = business.resolutions.all()

        for resolution in resolutions:
            resolution_json = resolution.json
            resolution_list.append(resolution_json)

        return jsonify(resolutions=resolution_list)
Пример #13
0
    def get_pdf(self, report_type=None):
        """Render a pdf for the report."""
        self._report_key = report_type if report_type else self._filing.filing_type
        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
Пример #14
0
    def get(identifier, filing_id=None):
        """Return a JSON object with meta information about the Service."""
        business = Business.find_by_identifier(identifier)

        if not business:
            return jsonify(filings=[]), HTTPStatus.OK

        if filing_id:
            rv = db.session.query(Business, Filing). \
                filter(Business.id == Filing.business_id).\
                filter(Business.identifier == identifier).\
                filter(Filing.id == filing_id).\
                one_or_none()
            if not rv:
                return jsonify({'message': f'{identifier} no filings found'
                                }), HTTPStatus.NOT_FOUND

            if str(request.accept_mimetypes) == 'application/pdf':
                return legal_api.reports.get_pdf(rv[1])

            return jsonify(rv[1].json)

        # Does it make sense to get a PDF of all filings?
        if str(request.accept_mimetypes) == 'application/pdf':
            return jsonify({'message': _('Cannot return a single PDF of multiple filing submissions.')}),\
                HTTPStatus.NOT_ACCEPTABLE

        rv = []
        filings = Filing.get_filings_by_status(
            business.id,
            [Filing.Status.COMPLETED.value, Filing.Status.PAID.value])
        for filing in filings:
            rv.append(filing.json)

        return jsonify(filings=rv)
Пример #15
0
    def get(identifier, addresses_id=None):
        """Return a JSON of the addresses on file."""
        business = Business.find_by_identifier(identifier)

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

        address_type = request.args.get('addressType', None)
        if address_type and address_type not in Address.JSON_ADDRESS_TYPES:
            return jsonify({
                'message':
                f'{address_type} not a valid address type'
            }), HTTPStatus.BAD_REQUEST

        if addresses_id or address_type:
            addresses, msg, code = AddressResource._get_address(
                business, addresses_id, address_type)
            return jsonify(addresses or msg), code

        # return all active addresses
        rv = {}
        mailing = business.mailing_address.one_or_none()
        if mailing:
            rv[Address.JSON_MAILING] = mailing.json
        delivery = business.delivery_address.one_or_none()
        if delivery:
            rv[Address.JSON_DELIVERY] = delivery.json
        if not rv:
            return jsonify({'message': f'{identifier} address not found'
                            }), HTTPStatus.NOT_FOUND
        return jsonify(rv)
def test_post_new_incorporation(session, client, jwt):
    """Assert that an incorporation filing can be posted to businesses."""
    nr_number = 'NR1234567'
    filing = copy.deepcopy(INCORPORATION_FILING_TEMPLATE)
    filing['filing']['incorporationApplication'] = INCORPORATION

    regoffice = filing['filing']['incorporationApplication']['offices'][
        'registeredOffice']
    regoffice['deliveryAddress']['addressRegion'] = 'BC'
    regoffice['deliveryAddress']['addressCountry'] = 'CA'
    regoffice['mailingAddress']['addressRegion'] = 'BC'
    regoffice['mailingAddress']['addressCountry'] = 'CA'

    recoffice = filing['filing']['incorporationApplication']['offices'][
        'recordsOffice']
    recoffice['deliveryAddress']['addressRegion'] = 'BC'
    recoffice['deliveryAddress']['addressCountry'] = 'CA'
    recoffice['mailingAddress']['addressRegion'] = 'BC'
    recoffice['mailingAddress']['addressCountry'] = 'CA'

    filing['filing']['incorporationApplication']['nameRequest'][
        'nrNumber'] = nr_number
    # Post initial filing
    rv = client.post(f'/api/v1/businesses',
                     json=filing,
                     headers=create_header(jwt, [STAFF_ROLE], nr_number))

    assert rv.status_code == HTTPStatus.CREATED
    assert rv.json['filing']['header']['status'] == 'DRAFT'

    # verify business has actually been inserted
    business = Business.find_by_identifier(nr_number)

    assert business
    assert business.identifier == nr_number
Пример #17
0
    def delete(identifier, filing_id=None):
        """Delete a filing from the business."""
        if not filing_id:
            return ({
                'message': _('No filing id provided for:') + identifier
            }, HTTPStatus.BAD_REQUEST)

        # check authorization
        if not authorized(identifier, jwt, action=['edit']):
            return jsonify({'message':
                            _('You are not authorized to delete a filing for:') + identifier}),\
                HTTPStatus.UNAUTHORIZED

        filing = Business.get_filing_by_id(identifier, filing_id)

        if not filing:
            return jsonify({'message':
                            _('Filing Not Found.')}), \
                HTTPStatus.NOT_FOUND

        try:
            filing.delete()
            return jsonify({'message':
                            _('Filing deleted.')}), \
                HTTPStatus.OK
        except BusinessException as err:
            return jsonify({'errors': [
                {
                    'error': err.error
                },
            ]}), err.status_code

        return {}, HTTPStatus.NOT_IMPLEMENTED
Пример #18
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 legal_api.models import Business, Filing

    # 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
    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)
Пример #19
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
Пример #20
0
def test_delete_business_active(session):
    """Assert that the business can be found by name."""
    designation = '001'
    business = Business(legal_name=f'legal_name-{designation}',
                        founding_date=datetime.utcfromtimestamp(0),
                        last_ledger_timestamp=datetime.utcfromtimestamp(0),
                        dissolution_date=None,
                        identifier='CP1234567',
                        tax_id='XX',
                        fiscal_year_end_date=datetime(2001, 8, 5, 7, 7, 58,
                                                      272362))
    business.save()

    b = business.delete()

    assert b.id == business.id
Пример #21
0
def test_business_find_by_legal_name_pass(session):
    """Assert that the business can be found by name."""
    designation = '001'
    business = Business(legal_name=f'legal_name-{designation}',
                        founding_date=datetime.utcfromtimestamp(0),
                        last_ledger_timestamp=datetime.utcfromtimestamp(0),
                        dissolution_date=None,
                        identifier=f'CP1234{designation}',
                        tax_id=f'BN0000{designation}',
                        fiscal_year_end_date=datetime(2001, 8, 5, 7, 7, 58,
                                                      272362))
    session.add(business)
    session.commit()

    b = Business.find_by_legal_name('legal_name-001')
    assert b is not None
Пример #22
0
def test_business_find_by_legal_name_no_database_connection(app_request):
    """Assert that None is return even if the database connection does not exist."""
    app_request.config[
        'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@exist:5432/nada'
    with app_request.app_context():
        b = Business.find_by_legal_name('failure to find')
        assert b is None
Пример #23
0
def get_businesses(identifier: str):
    """Return a JSON object with meta information about the Service."""
    # check authorization
    # if not authorized(identifier, jwt, action=['view']):
    #     return jsonify({'message':
    #                     f'You are not authorized to view business {identifier}.'}), \
    #         HTTPStatus.UNAUTHORIZED

    if identifier.startswith('T'):
        return {'message': babel('No information on temp registrations.')}, 200

    business = Business.find_by_identifier(identifier)

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

    business_json = business.json()
    recent_filing_json = CoreFiling.get_most_recent_filing_json(
        business.id, None, jwt)
    if recent_filing_json:
        business_json['submitter'] = recent_filing_json['filing']['header'][
            'submitter']
        business_json['lastModified'] = recent_filing_json['filing']['header'][
            'date']
    return jsonify(business=business_json)
Пример #24
0
def test_business_find_by_legal_name_fail(session):
    """Assert that the business can not be found, once it is disolved."""
    designation = '001'
    business = Business(legal_name=f'legal_name-{designation}',
                        founding_date=datetime.utcfromtimestamp(0),
                        dissolution_date=datetime.utcfromtimestamp(0),
                        identifier=f'CP1234{designation}',
                        tax_id=f'BN0000{designation}',
                        fiscal_year_end_date=datetime(2001, 8, 5, 7, 7, 58,
                                                      272362))
    session.add(business)
    session.commit()

    # business is dissolved, it should not be found by name search
    b = Business.find_by_legal_name('legal_name-001')
    assert b is None
Пример #25
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)
Пример #26
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
Пример #27
0
class DocumentMetaService():
    """Provides service for document meta data."""

    NOTICE_OF_ARTICLES = 'Notice of Articles'

    class DocumentType(Enum):
        """Define an enum of document types."""

        REPORT = 'REPORT'

    class ReportType(Enum):
        """Define an enum of report types."""

        CERTIFICATE = 'certificate'
        NOTICE_OF_ARTICLES = 'noa'
        ALTERATION_NOTICE = 'alterationNotice'
        CERTIFICATE_OF_NAME_CHANGE = 'certificateOfNameChange'
        CERTIFIED_RULES = 'certifiedRules'
        CERTIFIED_MEMORANDUM = 'certifiedMemorandum'

    def __init__(self):
        """Create the document meta instance."""
        # init global attributes
        self._business_identifier = None
        self._legal_type = None
        self._filing_status = None
        self._filing_id = None
        self._filing_date = None

    def get_documents(self, filing: dict):
        """Return an array of document meta for a filing."""
        # look up legal type
        if not (business_identifier := filing.get('filing', {}).get(
                'business', {}).get('identifier')):
            return []

        self._business_identifier = business_identifier
        # if this is a temp registration then there is no business, so get legal type from filing
        if self._business_identifier.startswith('T'):
            self._legal_type = filing['filing']['incorporationApplication'][
                'nameRequest']['legalType']
        else:
            business = Business.find_by_identifier(self._business_identifier)
            if not business:
                return []  # business not found
            self._legal_type = business.legal_type

        self._filing_status = filing['filing']['header']['status']
        is_paper_only = filing['filing']['header'].get('availableOnPaperOnly',
                                                       False)
        is_colin_only = filing['filing']['header'].get('inColinOnly', False)

        if self._filing_status not in (Filing.Status.COMPLETED.value,
                                       Filing.Status.PAID.value,
                                       Filing.Status.CORRECTED.value) \
                or is_paper_only or is_colin_only:
            return []  # wrong filing status

        return self.get_documents2(filing)
Пример #28
0
def create_business(db, business_json):
    business = Business()
    business.identifier = business_json['business']['identifier']
    business.founding_date = business_json['business']['foundingDate']
    business.last_ledger_timestamp = business_json['business'][
        'lastLedgerTimestamp']
    business.legal_name = business_json['business']['legalName']
    business.founding_date = business_json['business']['foundingDate']
    business.last_agm_date = datetime.date.fromisoformat(
        business_json['business']['lastAgmDate'])
    business.last_ar_date = datetime.date.fromisoformat(
        business_json['business']['lastArFiledDate'])
    return business
def process(business: Business, filing: Dict):
    """Render the annual_report onto the business model objects."""
    logger.debug('processing Voluntary Dissolution: %s', filing)
    dissolution_date = date.fromisoformat(
        filing['voluntaryDissolution'].get('dissolutionDate'))
    # Currently we don't use this for anything?
    # has_liabilities = filing['voluntaryDissolution'].get('hasLiabilities')
    business.dissolution_date = dissolution_date
Пример #30
0
def create_business(business_json: dict) -> Business:
    """Create a new business in lear via the model."""
    business = Business(identifier=business_json['business']['identifier'],
                        founding_date=convert_to_datetime(
                            business_json['business']['foundingDate']),
                        last_ledger_timestamp=convert_to_datetime(
                            business_json['business']['lastLedgerTimestamp']),
                        legal_name=business_json['business']['legalName'],
                        legal_type=business_json['business']['legalType'],
                        last_modified=datetime.datetime.utcnow())
    business.last_ar_date = datetime.datetime.fromisoformat(business_json['business']['lastArDate']) \
        if business_json['business']['lastArDate'] else None
    business.last_agm_date = datetime.datetime.fromisoformat(business_json['business']['lastAgmDate']) \
        if business_json['business']['lastAgmDate'] else business.last_ar_date
    if business_json['business'].get('businessNumber', None):
        business.tax_id = business_json['business'].get('businessNumber')
    return business