def test_validate_effective_date_not_before_other_AR_with_COD(
        session):  # noqa: N802; COD is an acronym
    """Assert that the filing ordering rules are correct.

    Rules:
     - The effective date of change cannot be a date that is farther
            in the past as a previous COD filing(Standalone or AR).
    """
    # setup
    identifier = 'CP1234567'
    now = datetime(2001, 8, 5, 0, 0, 0, 0, tzinfo=timezone.utc)
    filing_ar = copy.deepcopy(ANNUAL_REPORT)
    filing_ar['filing']['changeOfDirectors'] = copy.deepcopy(
        CHANGE_OF_DIRECTORS)

    business = Business(identifier=identifier,
                        founding_date=now - datedelta.datedelta(years=4))
    business.save()

    # create a COD
    factory_completed_filing(business=business,
                             data_dict=filing_ar,
                             filing_date=now)

    # move the COD BACK a MONTH
    filing_ar['filing']['header']['effectiveDate'] = (
        now - datedelta.MONTH).isoformat()

    # The effective date of change cannot be before the previous COD
    with freeze_time(now):
        err = validate_effective_date(business, filing_ar)
    assert err
def test_effective_date_sanity_check(session):
    """Assert that a COD with a valid effective date passes validation."""
    # setup
    identifier = 'CP1234567'
    now = datetime(2001, 8, 5, 0, 0, 0, 0, tzinfo=timezone.utc)
    filing_json = copy.deepcopy(FILING_HEADER)
    filing_json['filing']['header']['effectiveDate'] = (
        now - datedelta.MONTH).isoformat()
    filing_json['filing']['changeOfDirectors'] = copy.deepcopy(
        CHANGE_OF_DIRECTORS)

    business = Business(identifier=identifier,
                        founding_date=now - datedelta.datedelta(years=4))
    business.save()

    # create a COD
    factory_completed_filing(business=business,
                             data_dict=filing_json,
                             filing_date=(now - datedelta.MONTH))

    # move the COD to now
    filing_json['filing']['header']['effectiveDate'] = now.isoformat()

    with freeze_time(now):
        err = validate_effective_date(business, filing_json)
    assert not err
Esempio n. 3
0
    def _create_business(incorporation_body, client_request):
        """Create a business from an incorporation filing."""
        # Check that there is a JSON filing
        if not incorporation_body:
            return None, {'message': f'No filing json data in body of post for incorporation'}, \
                HTTPStatus.BAD_REQUEST

        temp_corp_num = incorporation_body['filing']['incorporationApplication']['nameRequest']['nrNumber']

        # check authorization
        if not authorized(temp_corp_num, jwt, action=['edit']):
            return None, {'message': f'You are not authorized to incorporate for {temp_corp_num}.'}, \
                   HTTPStatus.UNAUTHORIZED

        # Ensure there are no current businesses with the NR/random identifier
        business = Business.find_by_identifier(temp_corp_num)

        if business:
            return None, {'message': f'Incorporation filing for {temp_corp_num} already exists'}, \
                HTTPStatus.BAD_REQUEST

        # Create an empty business record, to be updated by the filer
        business = Business()
        business.identifier = temp_corp_num
        business.save()

        return business, None, (HTTPStatus.CREATED if (client_request.method == 'POST') else HTTPStatus.ACCEPTED)
def test_validate_cod_basic(session, test_name, now, delivery_country_1,
                            delivery_country_2, expected_code, expected_msg):  # pylint: disable=too-many-arguments
    """Assert that a basic COD can be validated."""
    # setup
    identifier = 'CP1234567'
    founding_date = now - datedelta.YEAR
    business = Business(identifier=identifier,
                        last_ledger_timestamp=founding_date)
    business.founding_date = founding_date

    f = copy.deepcopy(FILING_HEADER)
    f['filing']['header']['date'] = now.isoformat()
    f['filing']['header']['name'] = 'changeOfDirectors'
    f['filing']['business']['identifier'] = identifier

    cod = copy.deepcopy(CHANGE_OF_DIRECTORS)
    cod['directors'][0]['deliveryAddress'][
        'addressCountry'] = delivery_country_1
    cod['directors'][1]['deliveryAddress'][
        'addressCountry'] = delivery_country_2
    f['filing']['changeOfDirectors'] = cod

    # perform test
    with freeze_time(now):
        err = validate(business, f)

    # validate outcomes
    if expected_code:
        assert err.code == expected_code
        assert lists_are_equal(err.msg, expected_msg)
    else:
        assert err is None
Esempio n. 5
0
def test_business_json():
    """Assert that the business model is saved correctly."""
    epoch_date = datetime.utcfromtimestamp(0)
    business = Business(legal_name='legal_name',
                        founding_date=epoch_date,
                        identifier='CP1234567',
                        last_modified=epoch_date)

    d = {
        'legalName': 'legal_name',
        'identifier': 'CP1234567',
        'foundingDate': epoch_date.isoformat(),
        'lastModified': epoch_date.isoformat(),
    }
    assert business.json() == d

    business.dissolution_date = epoch_date
    d['dissolutionDate'] = datetime.date(business.dissolution_date).isoformat()
    assert business.json() == d
    business.dissolution_date = None
    d.pop('dissolutionDate')

    business.fiscal_year_end_date = epoch_date
    d['fiscalYearEndDate'] = datetime.date(
        business.fiscal_year_end_date).isoformat()
    assert business.json() == d
    business.fiscal_year_end_date = None
    d.pop('fiscalYearEndDate')

    business.tax_id = '123456789'
    d['taxId'] = business.tax_id
    assert business.json() == d
    business.tax_id = None
    d.pop('taxId')
Esempio n. 6
0
def factory_business(identifier,
                     founding_date=EPOCH_DATETIME,
                     last_ar_date=None,
                     entity_type=Business.LegalTypes.COOP.value):
    """Create a business entity with a versioned business."""
    last_ar_year = None
    if last_ar_date:
        last_ar_year = last_ar_date.year
    business = Business(
        legal_name=f'legal_name-{identifier}',
        founding_date=founding_date,
        last_ar_date=last_ar_date,
        last_ar_year=last_ar_year,
        last_ledger_timestamp=EPOCH_DATETIME,
        # dissolution_date=EPOCH_DATETIME,
        identifier=identifier,
        tax_id='BN123456789',
        fiscal_year_end_date=FROZEN_DATETIME,
        legal_type=entity_type)

    # Versioning business
    uow = versioning_manager.unit_of_work(db.session)
    uow.create_transaction(db.session)

    business.save()
    return business
Esempio n. 7
0
def test_business_relationships_json(session):
    """Assert that the business model is saved correctly."""
    from legal_api.models import Address, Office

    business = Business(legal_name='legal_name',
                        founding_date=EPOCH_DATETIME,
                        last_ledger_timestamp=EPOCH_DATETIME,
                        identifier='CP1234567',
                        last_modified=EPOCH_DATETIME)

    office = Office(office_type='registeredOffice')
    mailing_address = Address(city='Test City',
                              address_type=Address.MAILING,
                              business_id=business.id)
    office.addresses.append(mailing_address)
    business.offices.append(office)
    business.save()

    assert business.mailing_address.one_or_none()

    delivery_address = Address(city='Test City',
                               address_type=Address.DELIVERY,
                               business_id=business.id)
    office.addresses.append(delivery_address)
    business.save()

    assert business.delivery_address.one_or_none()
Esempio n. 8
0
def test_validate_ar_year(app, test_name, current_ar_date, previous_ar_date,
                          founding_date, expected_code, expected_msg):
    """Assert that ARs filing/annualReport/annualReportDate is valid."""
    # setup
    identifier = 'CP1234567'
    business = Business(identifier=identifier,
                        last_ledger_timestamp=previous_ar_date)
    business.founding_date = datetime.fromisoformat(founding_date)

    if previous_ar_date:
        business.last_ar_date = datetime.fromisoformat(previous_ar_date)
        business.last_ar_year = datetime.fromisoformat(previous_ar_date).year

    previous_ar = copy.deepcopy(ANNUAL_REPORT)
    current_ar = copy.deepcopy(previous_ar)

    current_ar['filing']['annualReport']['annualReportDate'] = current_ar_date

    # Test it
    with app.app_context():
        err = validate_ar_year(business=business,
                               current_annual_report=current_ar)
    # Validate the outcome
    if not expected_code and not err:
        assert err is expected_code
    else:
        assert err.code == expected_code
        assert err.msg == expected_msg
Esempio n. 9
0
def test_dissolution_statement_type(session, test_status, legal_type, dissolution_type, dissolution_statement_type,
                                    identifier, expected_code, expected_msg):  # pylint: disable=too-many-arguments
    """Assert that a VD can be validated."""
    # setup
    business = Business(identifier=identifier)

    filing = copy.deepcopy(FILING_HEADER)
    filing['filing']['header']['name'] = 'dissolution'
    filing['filing']['business']['legalType'] = legal_type
    filing['filing']['dissolution'] = copy.deepcopy(DISSOLUTION)
    filing['filing']['dissolution']['dissolutionStatementType'] = dissolution_statement_type
    filing['filing']['dissolution']['dissolutionType'] = dissolution_type
    filing['filing']['dissolution']['parties'][1]['deliveryAddress'] = \
        filing['filing']['dissolution']['parties'][1]['mailingAddress']

    if legal_type != Business.LegalTypes.COOP.value:
        del filing['filing']['dissolution']['dissolutionStatementType']

    # perform test
    with patch.object(dissolution, 'validate_affidavit', return_value=None):
        err = validate(business, filing)

    # validate outcomes
    if expected_code or expected_msg:
        assert expected_code == err.code
        assert expected_msg == err.msg[0]['error']
    else:
        assert not err
Esempio n. 10
0
def test_dissolution_court_orders(session, test_status, file_number, effect_of_order, expected_code, expected_msg):
    """Assert valid court orders."""
    business = Business(identifier='BC1234567')

    filing = copy.deepcopy(FILING_HEADER)
    filing['filing']['header']['name'] = 'dissolution'
    filing['filing']['business']['legalType'] = 'BC'
    filing['filing']['dissolution'] = copy.deepcopy(DISSOLUTION)
    filing['filing']['dissolution']['parties'][1]['deliveryAddress'] = \
        filing['filing']['dissolution']['parties'][1]['mailingAddress']

    court_order = {
        'effectOfOrder': effect_of_order
    }

    if file_number:
        court_order['fileNumber'] = file_number

    filing['filing']['dissolution']['courtOrder'] = court_order

    with patch.object(dissolution, 'validate_affidavit', return_value=None):
        err = validate(business, filing)

    # validate outcomes
    if test_status == 'FAIL':
        assert expected_code == err.code
        assert expected_msg == err.msg[0]['error']
    else:
        assert not err
Esempio n. 11
0
def check_valid_agm_date(app, test_name, ar_date, agm_date, last_agm_date, submission_date,
                         expected_code, expected_msg):
    """Assert that the AGM date for the filing is valid, or that valid warnings are returned."""
    # setup
    identifier = 'CP1234567'
    business = Business(identifier=identifier,
                        last_ledger_timestamp=datetime(last_agm_date.year, last_agm_date.month, last_agm_date.day))
    business.last_agm_date = last_agm_date

    current_ar = copy.deepcopy(ANNUAL_REPORT)
    current_ar['filing']['business']['identifier'] = identifier
    current_ar['filing']['header']['date'] = submission_date.isoformat()
    current_ar['filing']['annualReport']['annualReportDate'] = ar_date.isoformat()
    if agm_date:
        current_ar['filing']['annualReport']['annualGeneralMeetingDate'] = agm_date.isoformat()
    else:
        current_ar['filing']['annualReport']['annualGeneralMeetingDate'] = None

    # Test it
    with app.app_context():
        err = validate_agm_year(business=business,
                                annual_report=current_ar)
    # Validate the outcome
    if expected_msg:  # examples check
        assert err.msg == expected_msg
        assert err.code == expected_code
    else:  # fuzzer check
        assert err is None or err.code == HTTPStatus.BAD_REQUEST
Esempio n. 12
0
def test_manage_parties_structure__parties(
        app, session,
        test_name, parties_structure, expected_error):
    """Assert that the parties and party roles gets set."""
    business = Business()
    business.save()
    update_and_validate_party_and_roles(business, parties_structure, 3, 1)
Esempio n. 13
0
def test_dissolution_special_resolution(session, test_name, legal_type, dissolution_type,
        identifier, has_special_resolution_filing, expected_code, expected_msg):  # pylint: disable=too-many-arguments
    """Assert that special resolution can be validated."""
    from legal_api.services.filings import validate
    # setup
    business = Business(identifier=identifier)

    filing = copy.deepcopy(FILING_HEADER)
    filing['filing']['header']['name'] = 'dissolution'
    filing['filing']['business']['legalType'] = legal_type
    filing['filing']['dissolution'] = copy.deepcopy(DISSOLUTION)
    filing['filing']['dissolution']['dissolutionType'] = dissolution_type
    filing['filing']['dissolution']['parties'][1]['deliveryAddress'] = \
        filing['filing']['dissolution']['parties'][1]['mailingAddress']
    if has_special_resolution_filing:
        filing['filing']['specialResolution'] = copy.deepcopy(SPECIAL_RESOLUTION)
        resolution_date_str = filing['filing']['specialResolution']['resolutionDate']
        resolution_date_time = datetime.strptime(resolution_date_str, '%Y-%m-%d')
        business.founding_date = resolution_date_time - timedelta(days=1000)

    with patch.object(dissolution, 'validate_affidavit', return_value=None):
        err = validate(business, filing)

    # validate outcomes
    if expected_code:
        assert err.code == expected_code
        assert lists_are_equal(err.msg, expected_msg)
    else:
        assert err is None
Esempio n. 14
0
def test_validate_coa_basic(session, test_name, now, delivery_region,
                            delivery_country, mailing_region, mailing_country,
                            expected_code, expected_msg):  # pylint: disable=too-many-arguments
    """Assert that a basic COA can be validated."""
    # setup
    identifier = 'CP1234567'
    founding_date = now - datedelta.YEAR
    business = Business(identifier=identifier,
                        last_ledger_timestamp=founding_date)
    business.founding_date = founding_date

    f = copy.deepcopy(FILING_HEADER)
    f['filing']['header']['date'] = now.isoformat()
    f['filing']['header']['name'] = 'changeOfDirectors'
    f['filing']['business']['identifier'] = identifier
    f['filing']['changeOfAddress'] = CHANGE_OF_ADDRESS
    office = f['filing']['changeOfAddress']['offices']['registeredOffice']
    office['deliveryAddress']['addressRegion'] = delivery_region
    office['deliveryAddress']['addressCountry'] = delivery_country
    office['mailingAddress']['addressRegion'] = mailing_region
    office['mailingAddress']['addressCountry'] = mailing_country
    # perform test
    with freeze_time(now):
        err = validate(business, f)

    # validate outcomes
    if expected_code:
        assert err.code == expected_code
        assert lists_are_equal(err.msg, expected_msg)
    else:
        assert err is None
Esempio n. 15
0
def create_business(identifier):
    """Return a test business."""
    from legal_api.models import Address, Business
    business = Business()
    business.identifier = identifier
    business.save()
    return business
def test_validate(session, test_name, dissolution_date, has_liabilities, identifier,
                  expected_code, expected_msg):  # pylint: disable=too-many-arguments
    """Assert that a VD can be validated."""
    # setup
    business = Business(identifier=identifier)

    filing = copy.deepcopy(FILING_HEADER)
    filing['filing']['voluntaryDissolution'] = copy.deepcopy(VOLUNTARY_DISSOLUTION)
    if dissolution_date:
        filing['filing']['voluntaryDissolution']['dissolutionDate'] = dissolution_date
    else:
        del filing['filing']['voluntaryDissolution']['dissolutionDate']
    if has_liabilities:
        filing['filing']['voluntaryDissolution']['hasLiabilities'] = has_liabilities
    else:
        del filing['filing']['voluntaryDissolution']['hasLiabilities']

    # perform test
    err = validate(business, filing)

    # validate outcomes
    if expected_code or expected_msg:
        assert expected_code == err.code
        assert expected_msg == err.msg[0]['error']
    else:
        assert not err
Esempio n. 17
0
def test_update_business_profile(app, session, requests_mock, test_name,
                                 response_json, response_status, put_status,
                                 expected_error):
    """Assert that the business profile is updated.

    WHITE BOX test, as I'm mocking out 2 end points to
    work the business logic.
    """
    from flask import current_app

    email_address = '*****@*****.**'
    new_data = {'contactPoint': {'email': email_address}}
    business = Business(identifier='BC1234567', legal_type='BEN')

    with app.app_context():
        # setup
        requests_mock.post(f'{current_app.config["ACCOUNT_SVC_AUTH_URL"]}',
                           json={'access_token': 'token'})
        requests_mock.post(
            f'{current_app.config["ACCOUNT_SVC_ENTITY_URL"]}/{business.identifier}',
            json=response_json,
            status_code=response_status)
        requests_mock.put(
            f'{current_app.config["ACCOUNT_SVC_ENTITY_URL"]}/{business.identifier}',
            status_code=put_status)

        # test
        err = business_profile.update_business_profile(
            business, new_data['contactPoint'])

        assert err == expected_error
Esempio n. 18
0
def create_business(identifier, legal_type=None, legal_name=None):
    """Return a test business."""
    business = Business()
    business.identifier = identifier
    business.legal_type = legal_type
    business.legal_name = legal_name
    business.save()
    return business
def process(
        business: Business,  # pylint: disable=too-many-branches
        filing: Dict,
        filing_rec: Filing,
        filing_meta: FilingMeta):  # pylint: disable=too-many-branches
    """Process the incoming incorporation filing."""
    # Extract the filing information for incorporation
    incorp_filing = filing.get('filing', {}).get('incorporationApplication')
    is_correction = filing_rec.filing_type == 'correction'
    filing_meta.incorporation_application = {}

    if not incorp_filing:
        raise QueueException(
            f'IA legal_filing:incorporationApplication missing from {filing_rec.id}'
        )
    if business and not is_correction:
        raise QueueException(
            f'Business Already Exist: IA legal_filing:incorporationApplication {filing_rec.id}'
        )

    business_info_obj = incorp_filing.get('nameRequest')

    if is_correction:
        business_info.set_legal_name(business.identifier, business,
                                     business_info_obj)
    else:

        if filing_rec.colin_event_ids:
            corp_num = filing['filing']['business']['identifier']

        else:
            # Reserve the Corp Number for this entity
            corp_num = get_next_corp_num(business_info_obj['legalType'])
            if not corp_num:
                raise QueueException(
                    f'incorporationApplication {filing_rec.id} unable to get a business registration number.'
                )

        # Initial insert of the business record
        business = Business()
        business = business_info.update_business_info(corp_num, business,
                                                      business_info_obj,
                                                      filing_rec)
        business = _update_cooperative(incorp_filing, business, filing_rec)

        if nr_number := business_info_obj.get('nrNumber', None):
            filing_meta.incorporation_application = {
                **filing_meta.incorporation_application,
                **{
                    'nrNumber': nr_number,
                    'legalName': business_info_obj.get('legalName', None)
                }
            }

        if not business:
            raise QueueException(
                f'IA incorporationApplication {filing_rec.id}, Unable to create business.'
            )
Esempio n. 20
0
def factory_business(designation: str = '001'):
    """Return a valid Business object stamped with the supplied designation."""
    return 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=f'BN0000{designation}',
                    fiscal_year_end_date=datetime(2001, 8, 5, 7, 7, 58, 272362))
def create_business(identifier):
    """Return a test business."""
    from legal_api.models import Address, Business
    business = Business()
    business.identifier = identifier
    business = create_business_address(business, Address.DELIVERY)
    business = create_business_address(business, Address.MAILING)
    business.save()
    return business
Esempio n. 22
0
def factory_business(identifier):
    """Create a business entity."""
    business = Business(legal_name=f'legal_name-{identifier}',
                        founding_date=EPOCH_DATETIME,
                        dissolution_date=EPOCH_DATETIME,
                        identifier=identifier,
                        tax_id='BN123456789',
                        fiscal_year_end_date=FROZEN_DATETIME)
    business.save()
    return business
Esempio n. 23
0
def test_set_corp_type(app, session, test_name, original_legal_type,
                       new_legal_type, expected_legal_type, expected_error):
    """Assert that the corp type is set correctly."""
    new_data = {'legalType': new_legal_type}

    business = Business(legal_type=original_legal_type)
    err = business_info.set_corp_type(business, new_data)

    assert business.legal_type == expected_legal_type
    assert err == expected_error
Esempio n. 24
0
def test_business_json(session):
    """Assert that the business model is saved correctly."""
    business = Business(legal_name='legal_name',
                        legal_type='CP',
                        founding_date=EPOCH_DATETIME,
                        last_ledger_timestamp=EPOCH_DATETIME,
                        identifier='CP1234567',
                        last_modified=EPOCH_DATETIME,
                        last_ar_date=EPOCH_DATETIME,
                        last_agm_date=EPOCH_DATETIME,
                        restriction_ind=True)
    # basic json
    d = {
        'legalName': 'legal_name',
        'legalType': 'CP',
        'identifier': 'CP1234567',
        'foundingDate': EPOCH_DATETIME.isoformat(),
        'lastAddressChangeDate': '',
        'lastDirectorChangeDate': '',
        'lastLedgerTimestamp': EPOCH_DATETIME.isoformat(),
        'lastModified': EPOCH_DATETIME.isoformat(),
        'lastAnnualReportDate': datetime.date(EPOCH_DATETIME).isoformat(),
        'lastAnnualGeneralMeetingDate':
        datetime.date(EPOCH_DATETIME).isoformat(),
        'nextAnnualReport': '1971-01-01T08:00:00+00:00',
        'hasRestrictions': True,
        'goodStanding':
        False,  # good standing will be false because the epoch is 1970
        'arMinDate': '1971-01-01',
        'arMaxDate': '1972-04-30'
    }

    assert business.json() == d

    # include dissolutionDate
    business.dissolution_date = EPOCH_DATETIME
    d['dissolutionDate'] = datetime.date(business.dissolution_date).isoformat()
    assert business.json() == d
    business.dissolution_date = None
    d.pop('dissolutionDate')

    # include fiscalYearEndDate
    business.fiscal_year_end_date = EPOCH_DATETIME
    d['fiscalYearEndDate'] = datetime.date(
        business.fiscal_year_end_date).isoformat()
    assert business.json() == d
    business.fiscal_year_end_date = None
    d.pop('fiscalYearEndDate')

    # include taxId
    business.tax_id = '123456789'
    d['taxId'] = business.tax_id
    assert business.json() == d
    business.tax_id = None
    d.pop('taxId')
Esempio n. 25
0
async def test_publish_event(app, session, stan_server, event_loop, client_id,
                             entity_stan, future):
    """Assert that filing event is placed on the queue."""
    # Call back for the subscription
    from entity_queue_common.service import ServiceWorker
    from entity_filer.worker import APP_CONFIG, publish_event, qsm
    from legal_api.models import Business, Filing

    # file handler callback
    msgs = []

    async def cb_file_handler(msg):
        nonlocal msgs
        nonlocal future
        msgs.append(msg)
        if len(msgs) == 1:
            future.set_result(True)

    event_handler_subject = APP_CONFIG.ENTITY_EVENT_PUBLISH_OPTIONS['subject']

    await entity_stan.subscribe(
        subject=event_handler_subject,
        queue=f'entity_queue.{event_handler_subject}',
        durable_name=f'entity_durable_name.{event_handler_subject}',
        cb=cb_file_handler)

    s = ServiceWorker()
    s.sc = entity_stan
    qsm.service = s

    # Setup
    filing = Filing()
    filing.id = 101
    filing.effective_date = datetime.utcnow().replace(tzinfo=timezone.utc)
    filing.filing_json = ANNUAL_REPORT
    business = Business()
    business.identifier = 'CP1234567'
    business.legal_name = 'CP1234567 - Legal Name'

    # Test
    await publish_event(business, filing)

    try:
        await asyncio.wait_for(future, 2, loop=event_loop)
    except Exception as err:
        print(err)

    # check it out
    assert len(msgs) == 1

    event_msg = json.loads(msgs[0].data.decode('utf-8'))
    assert event_msg['filing']['filingId'] == 101
    assert event_msg['filing']['identifier'] == 'CP1234567'
    assert event_msg['filing']['legalFilings'] == ['annualReport']
Esempio n. 26
0
    def _save_incorporation_filing(incorporation_body,
                                   client_request,
                                   business_id=None):
        """Create or update an incorporation filing."""
        # Check that there is a JSON filing
        if not incorporation_body:
            return None, {'message': f'No filing json data in body of post for incorporation'}, \
                HTTPStatus.BAD_REQUEST

        temp_corp_num = incorporation_body['filing'][
            'incorporationApplication']['nameRequest']['nrNumber']
        # temp_corp_num = business_id
        # If this is an update to an incorporation filing, a temporary business identifier is passed in
        if business_id:
            business = Business.find_by_identifier(business_id)
            if not business:
                return None, {'message': f'No incorporation filing exists for id {business_id}'}, \
                    HTTPStatus.BAD_REQUEST
        else:
            # Ensure there are no current businesses with the NR/random identifier
            business = Business.find_by_identifier(temp_corp_num)

            if business:
                return None, {'message': f'Incorporation filing for {temp_corp_num} already exists'}, \
                    HTTPStatus.BAD_REQUEST
            # Create an empty business record, to be updated by the filer
            business = Business()
            business.identifier = temp_corp_num
            business.save()

        # Ensure the business identifier matches the NR in the filing
        err = validate(business, incorporation_body)
        if err:
            return None, err.msg, err.code

        filing = Filing.get_filings_by_type(business.id,
                                            'incorporationApplication')

        # There can only be zero or one incorporation filings, if there are none, this is an
        # initial request for incorporation. Create and insert a filing.
        if not filing:
            filing = Filing()
            filing.business_id = business.id
        elif len(filing) > 1:
            return None, {
                'message': 'more than one incorporation filing found for corp'
            }, HTTPStatus.BAD_REQUEST
        else:
            filing = filing[0]
        filing.filing_json = incorporation_body
        filing.save()
        return filing, None, (HTTPStatus.CREATED if
                              (client_request.method
                               == 'POST') else HTTPStatus.ACCEPTED)
Esempio n. 27
0
async def test_publish_event():
    """Assert that publish_event is called with the correct struct."""
    import uuid
    from unittest.mock import AsyncMock
    from entity_filer.worker import APP_CONFIG, get_filing_types, publish_event, qsm
    from legal_api.utils.datetime import datetime

    mock_publish = AsyncMock()
    qsm.service = mock_publish
    with freeze_time(datetime.utcnow()), \
            patch.object(uuid, 'uuid4', return_value=1):

        business = Business(identifier='BC1234567')
        filing = Filing(id=1,
                        effective_date=datetime.utcnow(),
                        _filing_type='incorporationApplication',
                        _filing_json=INCORPORATION_FILING_TEMPLATE)

        await publish_event(business, filing)

        payload = {
            'specversion':
            '1.x-wip',
            'type':
            'bc.registry.business.' + filing.filing_type,
            'source':
            ''.join([
                APP_CONFIG.LEGAL_API_URL, '/business/', business.identifier,
                '/filing/',
                str(filing.id)
            ]),
            'id':
            str(uuid.uuid4()),
            'time':
            datetime.utcnow().isoformat(),
            'datacontenttype':
            'application/json',
            'identifier':
            business.identifier,
            'data': {
                'filing': {
                    'header': {
                        'filingId': filing.id,
                        'effectiveDate': filing.effective_date.isoformat()
                    },
                    'business': {
                        'identifier': business.identifier
                    },
                    'legalFilings': get_filing_types(filing.filing_json)
                }
            }
        }

    mock_publish.publish.assert_called_with('entity.events', payload)
Esempio n. 28
0
def test_manage_office_structure__delete_and_recreate_offices(
        app, session, test_name, office_structure, expected_error):
    """Assert that the corp offices gets deleted and recreated."""
    business = Business()
    business.save()

    update_and_validate_office(business, office_structure)
    # Change the value of address to recreate
    office_structure['offices']['recordsOffice']['mailingAddress'][
        'postalCode'] = 'L6M 5M7'
    update_and_validate_office(business, office_structure)
Esempio n. 29
0
def test_business_identifier(session):
    """Assert that setting the business identifier must be in a valid format."""
    from tests.conftest import not_raises
    valid_identifier = 'CP1234567'
    invalid_identifier = '1234567'
    b = Business()

    with not_raises(BusinessException):
        b.identifier = valid_identifier

    with pytest.raises(BusinessException):
        b.identifier = invalid_identifier
Esempio n. 30
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']) \
        if business_json['business']['lastAgmDate'] else None
    business.last_ar_date = datetime.date.fromisoformat(business_json['business']['lastArDate'])\
        if business_json['business']['lastArDate'] else business.last_agm_date
    business.legal_type = business_json['business']['legalType']
    return business