Example #1
0
def process(business: Business, filing: Dict, filing_meta: FilingMeta):
    """Render the annual_report onto the business model objects."""
    legal_filing_name = 'annualReport'
    agm_date = filing[legal_filing_name].get('annualGeneralMeetingDate')
    ar_date = filing[legal_filing_name].get('annualReportDate')
    if ar_date:
        ar_date = datetime.date.fromisoformat(ar_date)
    else:
        # should never get here (schema validation should prevent this from making it to the filer)
        logger.error(
            'No annualReportDate given for in annual report. Filing id: %s',
            filing.id)

    # save the annual report date to the filing meta info
    filing_meta.application_date = ar_date
    filing_meta.annual_report = {
        'annualReportDate': ar_date.isoformat(),
        'annualGeneralMeetingDate': agm_date
    }
    business.last_ar_date = ar_date
    if agm_date and validations.annual_report.requires_agm(business):
        with suppress(ValueError):
            agm_date = datetime.date.fromisoformat(agm_date)
            business.last_agm_date = agm_date
            business.last_ar_date = agm_date

    business.last_ar_year = business.last_ar_year + 1 if business.last_ar_year else business.founding_date.year + 1
Example #2
0
def process(business: Business,
            filing_submission: Filing,
            filing: Dict,
            filing_meta: FilingMeta,
            correction: bool = False):  # pylint: disable=W0613
    """Render the Alteration onto the model objects."""
    filing_meta.alteration = {}
    # Alter the corp type, if any
    with suppress(IndexError, KeyError, TypeError):
        business_json = dpath.util.get(filing, '/alteration/business')
        filing_meta.alteration = {
            **filing_meta.alteration,
            **{
                'fromLegalType': business.legal_type,
                'toLegalType': business_json.get('legalType')
            }
        }
        business_info.set_corp_type(business, business_json)

    # Alter the corp name, if any
    with suppress(IndexError, KeyError, TypeError):
        name_request_json = dpath.util.get(filing, '/alteration/nameRequest')
        if legal_name := name_request_json.get('legalName', None):
            filing_meta.alteration = {
                **filing_meta.alteration,
                **{
                    'fromLegalName': business.legal_name,
                    'toLegalName': legal_name
                }
            }
        name_request.set_legal_name(business, name_request_json)
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.'
            )
def test_process_ar_filing(app, session):
    """Assert that an AR filling can be applied to the model correctly."""
    from entity_filer.worker import APP_CONFIG
    from entity_filer.filing_processors import annual_report
    # vars
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    identifier = 'CP1234567'

    # setup
    business = create_business(identifier, 'CP')
    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()

    filing_meta = FilingMeta()

    # TEST
    with freeze_time(now):
        filing = create_filing(payment_id, ar, business.id)
        filing_id = filing.id
        filing_msg = {'filing': {'id': filing_id}}
        annual_report.process(business,
                              filing.filing_json['filing'],
                              filing_meta=filing_meta)

    # check it out
    # NOTE: until we save or convert the dates, they are FakeDate objects, so casting to str()
    assert str(business.last_agm_date) == str(agm_date)
    assert str(business.last_ar_date) == str(agm_date)
Example #5
0
def test_conversion_process_with_nr(app, session):
    """Assert that the incorporation object is correctly populated to model objects."""
    # setup
    filing = copy.deepcopy(CONVERSION_FILING_TEMPLATE)
    identifier = 'BC1234567'
    nr_num = 'NR 1234567'
    filing['filing']['business']['identifier'] = identifier
    filing['filing']['conversion']['nameRequest']['nrNumber'] = nr_num
    filing['filing']['conversion']['nameRequest']['legalName'] = 'Test'
    create_filing('123', filing)

    effective_date = datetime.utcnow()
    filing_rec = Filing(effective_date=effective_date, filing_json=filing)
    filing_meta = FilingMeta(application_date=effective_date)

    # test
    business, filing_rec = conversion.process(None, filing, filing_rec,
                                              filing_meta)

    # Assertions
    assert business.identifier == identifier
    assert business.founding_date == effective_date
    assert business.legal_type == filing['filing']['conversion'][
        'nameRequest']['legalType']
    assert business.legal_name == filing['filing']['conversion'][
        'nameRequest']['legalName']
    assert len(business.share_classes.all()) == 2
    assert len(business.offices.all()
               ) == 2  # One office is created in create_business method.
def test_incorporation_filing_bc_company_from_colin(app, session, legal_type):
    """Assert that an existing bc company(LTD, ULC, CCC) incorporation is loaded corrrectly."""
    # setup
    corp_num = 'BC0000001'
    colind_id = 1
    filing = copy.deepcopy(INCORPORATION_FILING_TEMPLATE)

    # Change the template to be LTD, ULC or CCC
    filing['filing']['business']['legalType'] = legal_type
    filing['filing']['business']['identifier'] = corp_num
    filing['filing']['incorporationApplication']['nameRequest']['legalType'] = legal_type
    effective_date = datetime.utcnow()
    # Create the Filing object in the DB
    filing_rec = Filing(effective_date=effective_date,
                        filing_json=filing)
    colin_event = ColinEventId()
    colin_event.colin_event_id = colind_id
    filing_rec.colin_event_ids.append(colin_event)
    # Override the state setting mechanism
    filing_rec.skip_status_listener = True
    filing_rec._status = 'PENDING'
    filing_rec.save()
    filing_meta = FilingMeta(application_date=filing_rec.effective_date)

    # test
    business, filing_rec, filing_meta = incorporation_filing.process(None, filing, filing_rec, filing_meta=filing_meta)

    # Assertions
    assert business.identifier == corp_num
    assert business.founding_date.replace(tzinfo=None) == effective_date
    assert business.legal_type == filing['filing']['incorporationApplication']['nameRequest']['legalType']
    assert business.legal_name == business.identifier[2:] + ' B.C. LTD.'
    assert len(business.offices.all()) == 2  # One office is created in create_business method.
    assert len(business.share_classes.all()) == 2
    assert len(business.party_roles.all()) == 3
def test_incorporation_filing_process_no_nr(app, session):
    """Assert that the incorporation object is correctly populated to model objects."""
    # setup
    next_corp_num = 'BC0001095'
    with patch.object(incorporation_filing, 'get_next_corp_num', return_value=next_corp_num) as mock_get_next_corp_num:
        filing = copy.deepcopy(INCORPORATION_FILING_TEMPLATE)
        create_filing('123', filing)

        effective_date = datetime.utcnow()
        filing_rec = Filing(effective_date=effective_date, filing_json=filing)
        filing_meta = FilingMeta(application_date=filing_rec.effective_date)

        # test
        business, filing_rec, filing_meta = incorporation_filing.process(None, filing, filing_rec, filing_meta)

        # Assertions
        assert business.identifier == next_corp_num
        assert business.founding_date == effective_date
        assert business.legal_type == filing['filing']['incorporationApplication']['nameRequest']['legalType']
        assert business.legal_name == business.identifier[2:] + ' B.C. LTD.'
        assert len(business.share_classes.all()) == 2
        assert len(business.offices.all()) == 2  # One office is created in create_business method.

        # Parties
        parties = filing_rec.filing_json['filing']['incorporationApplication']['parties']
        assert parties[0]['officer']['firstName'] == 'Joe'
        assert parties[0]['officer']['lastName'] == 'Swanson'
        assert parties[0]['officer']['middleName'] == 'P'
        assert parties[0]['officer']['partyType'] == 'person'
        assert parties[1]['officer']['partyType'] == 'organization'
        assert parties[1]['officer']['organizationName'] == 'Xyz Inc.'


    mock_get_next_corp_num.assert_called_with(filing['filing']['incorporationApplication']['nameRequest']['legalType'])
Example #8
0
def test_alteration_process(app, session, orig_legal_type, new_legal_type):
    """Assert that the business legal type is altered."""
    # setup
    identifier = 'BC1234567'
    business = create_business(identifier)
    business.legal_type = orig_legal_type

    alteration_filing = copy.deepcopy(FILING_HEADER)
    alteration_filing['filing']['business']['legalType'] = orig_legal_type
    alteration_filing['filing']['alteration'] = copy.deepcopy(ALTERATION)
    alteration_filing['filing']['alteration']['business'][
        'legalType'] = new_legal_type
    payment_id = str(random.SystemRandom().getrandbits(0x58))
    filing_submission = create_filing(payment_id,
                                      alteration_filing,
                                      business_id=business.id)

    filing_meta = FilingMeta()

    # test
    alteration.process(business=business,
                       filing_submission=filing_submission,
                       filing=alteration_filing['filing'],
                       filing_meta=filing_meta)

    # validate
    assert business.legal_type == new_legal_type
def test_incorporation_filing_process_with_nr(app, session, minio_server, legal_type, filing):
    """Assert that the incorporation object is correctly populated to model objects."""
    # setup
    next_corp_num = 'BC0001095'
    with patch.object(incorporation_filing, 'get_next_corp_num', return_value=next_corp_num) as mock_get_next_corp_num:
        identifier = 'NR 1234567'
        filing['filing']['incorporationApplication']['nameRequest']['nrNumber'] = identifier
        filing['filing']['incorporationApplication']['nameRequest']['legalName'] = 'Test'
        if legal_type == 'CP':
            rules_file_key_uploaded_by_user = _upload_file()
            memorandum_file_key_uploaded_by_user = _upload_file()
            filing['filing']['incorporationApplication']['cooperative']['rulesFileKey'] = \
                rules_file_key_uploaded_by_user
            filing['filing']['incorporationApplication']['cooperative']['rulesFileName'] = 'Rules_File.pdf'
            filing['filing']['incorporationApplication']['cooperative']['memorandumFileKey'] = \
                memorandum_file_key_uploaded_by_user
            filing['filing']['incorporationApplication']['cooperative']['memorandumFileName'] = 'Memorandum_File.pdf'
        create_filing('123', filing)

        effective_date = datetime.utcnow()
        filing_rec = Filing(effective_date=effective_date, filing_json=filing)
        filing_meta = FilingMeta(application_date=effective_date)

        # test
        business, filing_rec, filing_meta = incorporation_filing.process(None, filing, filing_rec, filing_meta)

        # Assertions
        assert business.identifier == next_corp_num
        assert business.founding_date == effective_date
        assert business.legal_type == filing['filing']['incorporationApplication']['nameRequest']['legalType']
        assert business.legal_name == filing['filing']['incorporationApplication']['nameRequest']['legalName']
        if legal_type == 'BC':
            assert len(business.share_classes.all()) == 2
            assert len(business.offices.all()) == 2  # One office is created in create_business method.
        elif legal_type == 'CP':
            assert len(business.offices.all()) == 1
            documents = business.documents.all()
            assert len(documents) == 2
            for document in documents:
                if document.type == DocumentType.COOP_RULES.value:
                    original_rules_key = filing['filing']['incorporationApplication']['cooperative']['rulesFileKey']
                    assert document.file_key == original_rules_key
                    assert MinioService.get_file(document.file_key)
                elif document.type == DocumentType.COOP_MEMORANDUM.value:
                    original_memorandum_key = \
                        filing['filing']['incorporationApplication']['cooperative']['memorandumFileKey']
                    assert document.file_key == original_memorandum_key
                    assert MinioService.get_file(document.file_key)

            rules_files_obj = MinioService.get_file(rules_file_key_uploaded_by_user)
            assert rules_files_obj
            _assert_pdf_contains_text('Filed on ', rules_files_obj.read())
            memorandum_file_obj = MinioService.get_file(memorandum_file_key_uploaded_by_user)
            assert memorandum_file_obj
            _assert_pdf_contains_text('Filed on ', memorandum_file_obj.read())

    mock_get_next_corp_num.assert_called_with(filing['filing']['incorporationApplication']['nameRequest']['legalType'])
Example #10
0
def process(business: Business, filing: Dict, filing_meta: FilingMeta):
    """Render the annual_report onto the business model objects."""
    logger.debug('processing Change of Name: %s', filing)

    new_name = filing['changeOfName'].get('legalName')

    filing_meta.change_of_name = {
        'fromLegalName': business.legal_name,
        'toLegalName': new_name
    }

    business.legal_name = new_name
Example #11
0
def test_added_unknown_field():
    """Assert a field added to the dataclass is in the json output, but not in the std library asdict()."""
    filing_name = 'incorporationApplication'
    filing_meta = FilingMeta()

    filing_meta.unknown = 'an unknown field'

    assert filing_meta
    # should not have the field in the asdict view
    assert not asdict(filing_meta).get('unknown')
    assert asdict(filing_meta) == {
        'application_date': None,
        'legal_filings': [],
    }

    # the field should be in the json property
    assert filing_meta.asjson.get('unknown')
    assert filing_meta.asjson == {
        'applicationDate': None,
        'legalFilings': [],
        'unknown': 'an unknown field'
    }
Example #12
0
def test_minimal_filing_meta():
    """Assert the minimal setup of the class is correct."""
    filing_name = 'incorporationApplication'
    filing_meta = FilingMeta()

    assert filing_meta
    assert asdict(filing_meta) == {
        'application_date': None,
        'legal_filings': [],
    }
    assert filing_meta.asjson == {
        'applicationDate': None,
        'legalFilings': [],
    }
def test_incorporation_filing_process_correction(app, session):
    """Assert that the incorporation correction is correctly populated to model objects."""
    # setup
    next_corp_num = 'BC0001095'
    with patch.object(incorporation_filing, 'get_next_corp_num', return_value=next_corp_num) as mock_get_next_corp_num:
        filing = copy.deepcopy(INCORPORATION_FILING_TEMPLATE)
        create_filing('123', filing)

        effective_date = datetime.utcnow()
        filing_rec = Filing(effective_date=effective_date, filing_json=filing)
        filing_meta = FilingMeta(application_date=filing_rec.effective_date)

        # test
        business, filing_rec, filing_meta = incorporation_filing.process(None, filing, filing_rec, filing_meta)

        # Assertions
        assert business.identifier == next_corp_num
        assert business.founding_date == effective_date
        assert business.legal_type == filing['filing']['incorporationApplication']['nameRequest']['legalType']
        assert business.legal_name == business.identifier[2:] + ' B.C. LTD.'
        assert len(business.share_classes.all()) == 2
        assert len(business.offices.all()) == 2  # One office is created in create_business method.

    mock_get_next_corp_num.assert_called_with(filing['filing']['incorporationApplication']['nameRequest']['legalType'])

    correction_filing = copy.deepcopy(CORRECTION_INCORPORATION)
    correction_filing['filing']['incorporationApplication']['nameTranslations'] = [{'name': 'A5 Ltd.'}]
    del correction_filing['filing']['incorporationApplication']['shareStructure']['shareClasses'][1]
    corrected_filing_rec = Filing(effective_date=effective_date, filing_json=correction_filing)
    corrected_filing_meta = FilingMeta(application_date=corrected_filing_rec.effective_date)
    corrected_business, corrected_filing_rec, corrected_filing_meta =\
        incorporation_filing.process(business, correction_filing, corrected_filing_rec, corrected_filing_meta)
    assert corrected_business.identifier == next_corp_num
    assert corrected_business.legal_name == \
        correction_filing['filing']['incorporationApplication']['nameRequest']['legalName']
    assert len(corrected_business.share_classes.all()) == 1
Example #14
0
def test_change_of_name_process(app, session):
    """Assert that the legal name is changed."""
    # setup
    new_name = 'new legal_name'
    identifier = 'CP1234567'
    con = {'changeOfName': {'legalName': new_name}}

    business = create_business(identifier)
    business.legal_name = 'original name'

    filing_meta = FilingMeta()

    # test
    change_of_name.process(business, con, filing_meta)

    # validate
    assert business.legal_name == new_name
def test_has_new_nr_for_correction(app, session, test_name, nr_number,
                                   expected_result):
    """Assert that the incorporation object is correctly populated to model objects."""
    # setup
    next_corp_num = 'BC0001095'
    with patch.object(incorporation_filing,
                      'get_next_corp_num',
                      return_value=next_corp_num):
        filing = copy.deepcopy(INCORPORATION_FILING_TEMPLATE)
        identifier = 'NR 1234567'
        filing['filing']['incorporationApplication']['nameRequest'][
            'nrNumber'] = identifier
        filing['filing']['incorporationApplication']['nameRequest'][
            'legalName'] = 'Test'
        original_filing = create_filing('123', filing)

        effective_date = datetime.utcnow()
        filing_rec = Filing(effective_date=effective_date, filing_json=filing)
        filing_meta = FilingMeta()

        # test
        business, filing_rec, filing_meta = incorporation_filing.process(
            None, filing, filing_rec, filing_meta)

        # Assertions
        assert business.identifier == next_corp_num
        assert business.founding_date == effective_date
        assert business.legal_type == filing['filing'][
            'incorporationApplication']['nameRequest']['legalType']
        assert business.legal_name == filing['filing'][
            'incorporationApplication']['nameRequest']['legalName']

        correction_filing = copy.deepcopy(INCORPORATION_FILING_TEMPLATE)
        correction_filing['filing']['incorporationApplication']['nameRequest'][
            'nrNumber'] = nr_number
        correction_filing['filing']['correction'] = {}
        correction_filing['filing']['correction'][
            'correctedFilingId'] = original_filing.id
        assert name_request.has_new_nr_for_correction(
            correction_filing) is expected_result
Example #16
0
def test_voluntary_dissolution(app, session):
    """Assert that the dissolution is processed.
    
    Not a very deep set of tests yet."""
    # setup
    filing_json = copy.deepcopy(FILING_HEADER)
    dissolution_date = '2021-05-06T07:01:01.000000+00:00'  # this  will be 1 min after midnight
    dissolution_type = 'voluntary'
    # dissolution_date = '2019-04-15T20:05:49.068272+00:00' # this  will be 1 min after midnight
    has_liabilities = False
    identifier = 'BC1234567'
    legal_type = 'BEN'
    filing_json['filing']['business']['identifier'] = identifier
    filing_json['filing']['business']['legalType'] = legal_type

    filing_json['filing']['dissolution'] = DISSOLUTION
    filing_json['filing']['dissolution']['dissolutionDate'] = dissolution_date
    filing_json['filing']['dissolution']['dissolutionType'] = dissolution_type
    filing_json['filing']['dissolution']['hasLiabilities'] = has_liabilities

    business = create_business(identifier, legal_type=legal_type)
    business.dissolution_date = None
    business_id = business.id

    filing_meta = FilingMeta()

    # test
    dissolution.process(business, filing_json['filing'], filing_meta)
    business.save()

    # validate
    assert business.dissolution_date == datetime.fromisoformat(
        dissolution_date)

    custodial_office = session.query(Business, Office). \
            filter(Business.id == Office.business_id). \
            filter(Business.id == business_id). \
            filter(Office.office_type == OfficeType.CUSTODIAL). \
            one_or_none()
    assert custodial_office
Example #17
0
def test_added_filing_field():
    """Assert a field added to the dataclass is in the json output, but not in the std library asdict()."""
    filing_name = 'incorporationApplication'
    filing_meta = FilingMeta()

    setattr(filing_meta, to_snake(filing_name), {})

    assert filing_meta
    # should not have the field in the asdict view
    assert not asdict(filing_meta).get(filing_name)
    assert asdict(filing_meta) == {
        'application_date': None,
        'legal_filings': [],
    }

    # the field should be in the json property
    assert filing_meta.asjson.get(filing_name) == {}
    assert filing_meta.asjson == {
        'applicationDate': None,
        'legalFilings': [],
        filing_name: {}
    }
Example #18
0
def test_transition_filing_process(app, session):
    """Assert that the transition object is correctly populated to model objects."""
    # setup
    filing = copy.deepcopy(TRANSITION_FILING_TEMPLATE)

    business = create_business(filing['filing']['business']['identifier'])
    create_filing('123', filing)

    effective_date = datetime.datetime.utcnow()
    filing_rec = Filing(effective_date=effective_date, filing_json=filing)
    filing_meta = FilingMeta(application_date=effective_date)

    # test
    transition.process(business, filing_rec, filing['filing'], filing_meta)

    # Assertions
    assert business.restriction_ind is False
    assert len(business.share_classes.all()) == len(filing['filing']['transition']['shareStructure']['shareClasses'])
    assert len(business.offices.all()) == len(filing['filing']['transition']['offices'])
    assert len(business.aliases.all()) == len(filing['filing']['transition']['nameTranslations'])
    assert len(business.resolutions.all()) == len(filing['filing']['transition']['shareStructure']['resolutionDates'])
    assert len(business.party_roles.all()) == 2
Example #19
0
def test_conversion_coop_from_colin(app, session):
    """Assert that an existing coop incorporation is loaded corrrectly."""
    # setup
    identifier = 'CP0000001'
    colind_id = 1
    filing = copy.deepcopy(CONVERSION_FILING_TEMPLATE)

    # Change the template to be a CP == Cooperative
    filing['filing']['business']['legalType'] = 'CP'
    filing['filing']['business']['identifier'] = identifier
    filing['filing']['conversion']['nameRequest']['legalType'] = 'CP'
    filing['filing']['conversion'].pop('shareStructure')
    effective_date = datetime.utcnow()
    # Create the Filing obeject in the DB
    filing_rec = Filing(effective_date=effective_date, filing_json=filing)
    colin_event = ColinEventId()
    colin_event.colin_event_id = colind_id
    filing_rec.colin_event_ids.append(colin_event)
    # Override the state setting mechanism
    filing_rec.skip_status_listener = True
    filing_rec._status = 'PENDING'
    filing_rec.save()
    filing_meta = FilingMeta(application_date=effective_date)

    # test
    business, filing_rec = conversion.process(None, filing, filing_rec,
                                              filing_meta)

    # Assertions
    assert business.identifier == identifier
    assert business.founding_date.replace(
        tzinfo=None) == effective_date.replace(tzinfo=None)
    assert business.legal_type == filing['filing']['conversion'][
        'nameRequest']['legalType']
    assert business.legal_name == business.identifier[2:] + ' B.C. LTD.'
    assert len(business.offices.all()
               ) == 2  # One office is created in create_business method.
Example #20
0
async def process_filing(filing_msg: Dict, flask_app: Flask):  # pylint: disable=too-many-branches,too-many-statements
    """Render the filings contained in the submission.

    Start the migration to using core/Filing
    """
    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'])
        filing_core_submission = FilingCore.find_by_id(
            filing_msg['filing']['id'])

        if not filing_core_submission:
            raise QueueException

        filing_submission = filing_core_submission.storage

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

        # convenience flag to set that the envelope is a correction
        is_correction = (filing_core_submission.filing_type ==
                         FilingCore.FilingTypes.CORRECTION)

        if legal_filings := filing_core_submission.legal_filings(
                with_diff=False):
            uow = versioning_manager.unit_of_work(db.session)
            transaction = uow.create_transaction(db.session)

            business = Business.find_by_internal_id(
                filing_submission.business_id)

            filing_meta = FilingMeta(
                application_date=filing_submission.effective_date,
                legal_filings=[
                    item
                    for sublist in [list(x.keys()) for x in legal_filings]
                    for item in sublist
                ])

            for filing in legal_filings:
                if filing.get('alteration'):
                    alteration.process(business, filing_submission, filing,
                                       filing_meta, is_correction)

                elif filing.get('annualReport'):
                    annual_report.process(business, filing, filing_meta)

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

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

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

                elif filing.get('dissolution'):
                    dissolution.process(business, filing, filing_meta)

                elif filing.get('incorporationApplication'):
                    business, filing_submission, filing_meta = incorporation_filing.process(
                        business, filing_core_submission.json,
                        filing_submission, filing_meta)

                elif filing.get('conversion'):
                    business, filing_submission = conversion.process(
                        business, filing_core_submission.json,
                        filing_submission, filing_meta)

                elif filing.get('courtOrder'):
                    court_order.process(filing_submission, filing, filing_meta)

                elif filing.get('registrarsNotation'):
                    registrars_notation.process(filing_submission, filing,
                                                filing_meta)

                elif filing.get('registrarsOrder'):
                    registrars_order.process(filing_submission, filing,
                                             filing_meta)

                elif filing.get('correction'):
                    filing_submission = correction.process(
                        filing_submission, filing, filing_meta)

                elif filing.get('transition'):
                    filing_submission = transition.process(
                        business, filing_submission, filing, filing_meta)

            filing_submission.transaction_id = transaction.id
            filing_submission.set_processed()
            filing_submission._meta_data = json.loads(  # pylint: disable=W0212
                json.dumps(filing_meta.asjson, default=json_serial))

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

            # post filing changes to other services
            if any('alteration' in x for x in legal_filings):

                alteration.post_process(business, filing_submission,
                                        correction)
                db.session.add(business)
                db.session.commit()
                AccountService.update_entity(
                    business_registration=business.identifier,
                    business_name=business.legal_name,
                    corp_type_code=business.legal_type)

            if any('incorporationApplication' in x for x in legal_filings):
                if any('correction' in x for x in legal_filings):
                    if name_request.has_new_nr_for_correction(
                            filing_submission.filing_json):
                        name_request.consume_nr(business, filing_submission)
                else:
                    filing_submission.business_id = business.id
                    db.session.add(filing_submission)
                    db.session.commit()
                    incorporation_filing.update_affiliation(
                        business, filing_submission)
                    name_request.consume_nr(business, filing_submission)
                    incorporation_filing.post_process(business,
                                                      filing_submission)
                    try:
                        await publish_email_message(
                            qsm, APP_CONFIG.EMAIL_PUBLISH_OPTIONS['subject'],
                            filing_submission, 'mras')
                    except Exception as err:  # pylint: disable=broad-except, unused-variable # noqa F841;
                        # mark any failure for human review
                        capture_message(
                            f'Queue Error: Failed to place email for filing:{filing_submission.id}'
                            f'on Queue with error:{err}',
                            level='error')

            if any('conversion' in x for x in legal_filings):
                filing_submission.business_id = business.id
                db.session.add(filing_submission)
                db.session.commit()
                conversion.post_process(business, filing_submission)

            try:
                await publish_email_message(
                    qsm, APP_CONFIG.EMAIL_PUBLISH_OPTIONS['subject'],
                    filing_submission, filing_submission.status)
            except Exception as err:  # pylint: disable=broad-except, unused-variable # noqa F841;
                # mark any failure for human review
                capture_message(
                    f'Queue Error: Failed to place email for filing:{filing_submission.id}'
                    f'on Queue with error:{err}',
                    level='error')

            try:
                await publish_event(business, filing_submission)
            except Exception as err:  # pylint: disable=broad-except, unused-variable # noqa F841;
                # mark any failure for human review
                print(err)
                capture_message(
                    f'Queue Error: Failed to publish event for filing:{filing_submission.id}'
                    f'on Queue with error:{err}',
                    level='error')