def get_documents(identifier: str,
                  filing_id: int,
                  legal_filing_name: str = None):
    """Return a JSON object with meta information about the Service."""
    # basic checks
    if not authorized(identifier, jwt, [
            'view',
    ]):
        return jsonify(message=get_error_message(ErrorCode.NOT_AUTHORIZED, **{
            'identifier': identifier
        })), HTTPStatus.UNAUTHORIZED

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

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

    if not (filing := Filing.get(identifier, filing_id)):
        return jsonify(message=get_error_message(
            ErrorCode.FILING_NOT_FOUND, **{
                'filing_id': filing_id,
                'identifier': identifier
            })), HTTPStatus.NOT_FOUND
def test_get_receipt(session, client, jwt, requests_mock):
    """Assert that a receipt is generated."""
    from legal_api.resources.v2.business.business_filings.business_documents import _get_receipt

    # Setup
    identifier = 'CP7654321'
    business = factory_business(identifier)
    filing_name = 'incorporationApplication'
    payment_id = '12345'

    filing_json = copy.deepcopy(FILING_HEADER)
    filing_json['filing']['header']['name'] = filing_name
    filing_json['filing'][filing_name] = INCORPORATION
    filing_json['filing'].pop('business')

    filing_date = datetime.utcnow()
    filing = factory_filing(business, filing_json, filing_date=filing_date)
    filing.skip_status_listener = True
    filing._status = 'PAID'
    filing._payment_token = payment_id
    filing.save()
    filing_core = Filing()
    filing_core._storage = filing

    requests_mock.post(f"{current_app.config.get('PAYMENT_SVC_URL')}/{payment_id}/receipts",
                       json={'foo': 'bar'},
                       status_code=HTTPStatus.CREATED)

    token = helper_create_jwt(jwt, roles=[STAFF_ROLE], username='******')

    content, status_code = _get_receipt(business, filing_core, token)

    assert status_code == HTTPStatus.CREATED
    assert requests_mock.called_once
Exemple #3
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)
Exemple #4
0
def test_simple_ledger_search(session):
    """Assert that the ledger returns values for all the expected keys."""
    # setup
    identifier = 'BC1234567'
    founding_date = datetime.utcnow() - datedelta.datedelta(
        months=len(Filing.FILINGS.keys()))
    business = factory_business(identifier=identifier,
                                founding_date=founding_date,
                                last_ar_date=None,
                                entity_type=Business.LegalTypes.BCOMP.value)
    num_of_files = load_ledger(business, founding_date)

    # test
    ledger = CoreFiling.ledger(business.id)

    # Did we get the full set
    assert len(ledger) == num_of_files

    # Fully examine 1 filing - alteration
    alteration = next((f for f in ledger if f.get('name') == 'alteration'),
                      None)

    assert alteration
    assert 15 == len(alteration.keys())
    assert 'availableOnPaperOnly' in alteration
    assert 'effectiveDate' in alteration
    assert 'filingId' in alteration
    assert 'name' in alteration
    assert 'paymentStatusCode' in alteration
    assert 'status' in alteration
    assert 'submittedDate' in alteration
    assert 'submitter' in alteration
Exemple #5
0
def test_diff_of_stored_completed_filings(session):
    """Assert that the filing diff works correctly."""
    identifier = 'CP1234567'
    business = factory_business(identifier,
                                founding_date=(datetime.utcnow() -
                                               datedelta.YEAR))
    factory_business_mailing_address(business)
    json1 = copy.deepcopy(MINIMAL_FILING_JSON)
    original_filing = factory_completed_filing(business, json1)

    json2 = copy.deepcopy(CORRECTION_FILING_JSON)
    json2['filing']['correction']['correctedFilingId'] = str(
        original_filing.id)
    correction_filing = factory_completed_filing(business, json2)

    filing = Filing.find_by_id(correction_filing.id)
    filing_json = filing.json

    assert filing_json
    assert filing_json['filing']['correction']['diff'] == [{
        'newValue':
        'Be it resolved, and now it is.',
        'oldValue':
        'Be it resolved, that it is resolved to be resolved.',
        'path':
        RESOLUTION_PATH
    }]
Exemple #6
0
def test_filing_type(session):
    """Assert that filing_type is empty on a new filing."""
    identifier = 'CP7654321'
    business = factory_business(identifier)
    factory_completed_filing(business, ANNUAL_REPORT)

    filings = Filing.get_filings_by_status(business.id, [Filing.Status.DRAFT.value, Filing.Status.COMPLETED.value])
    assert filings[0].filing_type == 'annualReport'
Exemple #7
0
def test_filing_json_draft(session):
    """Assert that the json field gets the draft filing correctly."""
    filing = Filing()
    filing_submission = {
        'filing': {
            'header': {
                'name': 'specialResolution',
                'date': '2019-04-08'
            },
            'specialResolution': {
                'resolution': 'Year challenge is hitting oppo for the win.'
            }}}

    filing.json = filing_submission
    filing.save()

    assert filing.json == filing_submission
Exemple #8
0
def test_filing_save(session):
    """Assert that the core filing is saved to the backing store."""
    filing = Filing()
    filing_submission = {
        'filing': {
            'header': {
                'name': 'specialResolution',
                'date': '2019-04-08'
            },
            'specialResolution': {
                'resolution': 'Year challenge is hitting oppo for the win.'
            }}}

    filing.json = filing_submission

    assert not filing.id

    filing.save()

    assert filing.id
Exemple #9
0
def test_set_effective(session):
    """Assert that the core filing is saved to the backing store."""
    now = datetime(2021, 9, 17, 7, 36, 43, 903557, tzinfo=timezone.utc)

    with freeze_time(now):

        payment_date = now + datedelta.DAY

        filing = Filing()
        filing_type = 'annualReport'
        filing.json = ANNUAL_REPORT
        filing.save()

        filing.storage._payment_token = '12345'
        filing.storage._filing_type = filing_type
        filing.storage.effective_date = now
        filing._storage.skip_status_listener = True
        filing._storage.payment_completion_date = payment_date
        filing._storage.save()

        filing.storage.set_processed()

        # assert that the effective date is the payment date
        assert filing._storage.effective_date
        assert filing._storage.effective_date.replace(
            tzinfo=None) == payment_date.replace(tzinfo=None)
        assert not filing.is_future_effective

        future_date = now + datedelta.DAY
        alt_payment_date = now
        filing._storage.skip_status_listener = True
        filing._storage.payment_completion_date = alt_payment_date
        filing._storage.save()

        filing.storage.set_processed()

        # assert that the effective date is the future date
        assert filing._storage.effective_date
        assert filing._storage.effective_date.replace(
            tzinfo=None) == future_date.replace(tzinfo=None)
        assert filing.is_future_effective
Exemple #10
0
def test_filing_json_completed(session):
    """Assert that the json field gets the completed filing correctly."""
    identifier = 'CP7654321'
    business = factory_business(identifier)
    factory_completed_filing(business, ANNUAL_REPORT)

    filings = Filing.get_filings_by_status(business.id, [Filing.Status.COMPLETED.value])
    filing = filings[0]

    assert filing.json
    assert filing.json['filing']['header']['status'] == Filing.Status.COMPLETED.value
    assert filing.json['filing']['annualReport']
    assert 'directors' in filing.json['filing']['annualReport']
    assert 'offices' in filing.json['filing']['annualReport']
Exemple #11
0
def test_is_future_effective(session):
    """Assert that is_future_effective property works as expected."""
    filing = Filing()
    filing_type = 'bogus type'
    filing.storage.filing_json = {'filing': {'header': {'name': filing_type}}}
    filing.storage._payment_token = '12345'
    filing.storage._filing_type = filing_type

    now = datetime(2019, 7, 1)
    with freeze_time(now):
        filing.storage.effective_date = now
        assert not filing.is_future_effective

        filing.storage.payment_completion_date = now
        assert not filing.is_future_effective
Exemple #12
0
def test_technical_filing_json_draft(session):
    """Assert that the technical json field gets the draft filing correctly.

    technical filings should bypass all checks.

    danger Will Robinson
    
    This builds on test_filing_json_draft, so if that is broken, this wont work either.
    """
    # setup
    filing = Filing()
    filing_submission = {
        'filing': {
            'header': {
                'name': 'specialResolution',
                'date': '2019-04-08'
            },
            'specialResolution': {
                'resolution': 'Year challenge is hitting oppo for the win.'
            }
        }
    }

    filing.json = filing_submission
    filing.save()
    # sanity check
    assert filing.json['filing']['header']['name'] == filing_submission[
        'filing']['header']['name']
    assert filing.json['filing']['specialResolution'] == filing_submission[
        'filing']['specialResolution']

    # test
    non_compliant_json = {
        'dope': 'this would fail any validator, but can bypass everything.',
        'dogsLife': "do the humans really know what's best?"
    }
    filing.storage.tech_correction_json = non_compliant_json
    # over ride the state and skip state setting listeners for this test
    filing._storage.skip_status_listener = True
    filing._storage._status = Filing.Status.PENDING.value
    filing.save()

    # validate
    assert filing.json == non_compliant_json
Exemple #13
0
    def get_ledger_listing(identifier: str, user_jwt: JwtManager):
        """Return the requested ledger for the business identifier provided."""
        # 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

        ledger_start = request.args.get('start', default=None, type=int)
        ledger_size = request.args.get('size', default=None, type=int)
        business = Business.find_by_identifier(identifier)

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

        filings = CoreFiling.ledger(
            business.id,
            jwt=user_jwt,
            statuses=[Filing.Status.COMPLETED.value, Filing.Status.PAID.value],
            start=ledger_start,
            size=ledger_size)

        return jsonify(filings=filings)
Exemple #14
0
async def test_technical_correction_ar(app, session):
    """Assert we can create a business based on transition filing."""
    filing_data = copy.deepcopy(ANNUAL_REPORT)

    business = create_business(filing_data['filing']['business']['identifier'])
    business_identifier = business.identifier

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

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

    # sanity check
    # that it is an AR, and it is based on the ANNUAL_REPORT template
    assert filing.json['filing']['annualReport']
    assert filing.json['filing']['annualReport']['annualGeneralMeetingDate']  \
        == ANNUAL_REPORT['filing']['annualReport']['annualGeneralMeetingDate']
    # and the businesses last AR date is null
    assert not business.last_ar_date

    # subvert the filing
    technical_correction_filing = copy.deepcopy(FILING_HEADER)
    technical_correction_filing['specialResolution'] = copy.deepcopy(
        SPECIAL_RESOLUTION)
    filing.tech_correction_json = technical_correction_filing
    # over ride the state and skip state setting listeners for this test
    filing.skip_status_listener = True
    filing._status = 'PENDING'
    filing.save()

    # Test
    await process_filing(filing_msg, app)

    # Check outcome
    business = Business.find_by_identifier(business_identifier)
    filing = FilingCore.find_by_id(filing_id)
    assert not business.last_ar_date
    assert filing.filing_type == 'annualReport'
Exemple #15
0
class ListFilingResource():
    """Business Filings service."""
    @staticmethod
    def get_single_filing(identifier: str, filing_id: int):
        """Return a single filing and all of its components."""
        original_filing = str(request.args.get('original',
                                               None)).lower() == 'true'
        rv = CoreFiling.get(identifier, filing_id)
        if not rv:
            return jsonify({'message': f'{identifier} no filings found'
                            }), HTTPStatus.NOT_FOUND

        if original_filing:
            return jsonify(rv.redacted(rv.raw, jwt))

        if rv.filing_type == CoreFiling.FilingTypes.CORRECTION.value:
            # This is required until #5302 ticket implements
            rv.storage._filing_json['filing']['correction']['diff'] = rv.json[
                'filing']['correction']['diff']  # pylint: disable=protected-access; # noqa: E501;

        if str(request.accept_mimetypes) == 'application/pdf':
            report_type = request.args.get('type', None)
            return legal_api.reports.get_pdf(rv.storage, report_type)

        filing_json = rv.json
        if documents := DocumentMetaService().get_documents(filing_json):
            filing_json['filing']['documents'] = documents

        if filing_json.get('filing', {}).get(
                'header', {}).get('status') == Filing.Status.PENDING.value:
            ListFilingResource.get_payment_update(filing_json)

        filing_json = {
            **filing_json,
            **CoreFiling.common_ledger_items(identifier, rv.storage)
        }

        return jsonify(rv.redacted(filing_json, jwt))
Exemple #16
0
    def get_single_filing(identifier: str, filing_id: int):
        """Return a single filing and all of its components."""
        original_filing = str(request.args.get('original',
                                               None)).lower() == 'true'
        rv = CoreFiling.get(identifier, filing_id)
        if not rv:
            return jsonify({'message': f'{identifier} no filings found'
                            }), HTTPStatus.NOT_FOUND

        if original_filing:
            return jsonify(rv.redacted(rv.raw, jwt))

        if rv.filing_type == CoreFiling.FilingTypes.CORRECTION.value:
            # This is required until #5302 ticket implements
            rv.storage._filing_json['filing']['correction']['diff'] = rv.json[
                'filing']['correction']['diff']  # pylint: disable=protected-access; # noqa: E501;

        if str(request.accept_mimetypes) == 'application/pdf':
            report_type = request.args.get('type', None)
            return legal_api.reports.get_pdf(rv.storage, report_type)

        filing_json = rv.json
        if documents := DocumentMetaService().get_documents(filing_json):
            filing_json['filing']['documents'] = documents
Exemple #17
0
def test_filing_raw():
    """Assert that raw is empty on a new filing."""
    filing = Filing()

    assert not filing.raw
def _get_document_list(business, filing):
    """Get list of document outputs."""
    if not (document_list := Filing.get_document_list(business, filing,
                                                      request)):
        return {}, HTTPStatus.NOT_FOUND
Exemple #19
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.value:
            logger.warning(
                'QueueFiler: Attempting to reprocess business.id=%s, filing.id=%s filing=%s',
                filing_submission.business_id, filing_submission.id,
                filing_msg)
            return None, None

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

            business = Business.find_by_internal_id(
                filing_submission.business_id)

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

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

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

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

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

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

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

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

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

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

            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):
                if name_request.has_new_nr_for_alteration(
                        business, filing_submission.filing_json):
                    name_request.consume_nr(
                        business, filing_submission,
                        '/filing/alteration/nameRequest/nrNumber')
                alteration.post_process(business, filing_submission)
                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
                capture_message(
                    f'Queue Error: Failed to publish event for filing:{filing_submission.id}'
                    f'on Queue with error:{err}',
                    level='error')
Exemple #20
0
    def get(identifier, filing_id=None):  # pylint: disable=too-many-return-statements,too-many-branches;
        # fix this while refactoring this whole module
        """Return a JSON object with meta information about the Service."""
        original_filing = str(request.args.get('original',
                                               None)).lower() == 'true'
        if identifier.startswith('T'):
            rv = CoreFiling.get(identifier, filing_id)

            if not rv.storage:
                return jsonify({'message': f'{identifier} no filings found'
                                }), HTTPStatus.NOT_FOUND
            if str(request.accept_mimetypes
                   ) == 'application/pdf' and filing_id:
                if rv.filing_type == 'incorporationApplication':
                    return legal_api.reports.get_pdf(rv.storage, None)

            if original_filing:
                filing_json = rv.raw
            else:
                filing_json = rv.json
                filing_json['filing']['documents'] = DocumentMetaService(
                ).get_documents(filing_json)

            if filing_json['filing']['header'][
                    'status'] == Filing.Status.PENDING.value:
                try:
                    headers = {
                        'Authorization':
                        f'Bearer {jwt.get_token_auth_header()}',
                        'Content-Type': 'application/json'
                    }
                    payment_svc_url = current_app.config.get('PAYMENT_SVC_URL')
                    pay_response = requests.get(
                        url=
                        f'{payment_svc_url}/{filing_json["filing"]["header"]["paymentToken"]}',
                        headers=headers)
                    pay_details = {
                        'isPaymentActionRequired':
                        pay_response.json().get('isPaymentActionRequired',
                                                False),
                        'paymentMethod':
                        pay_response.json().get('paymentMethod', '')
                    }
                    filing_json['filing']['header'].update(pay_details)

                except (exceptions.ConnectionError, exceptions.Timeout) as err:
                    current_app.logger.error(
                        f'Payment connection failure for getting {identifier} filing payment details. ',
                        err)

            return jsonify(filing_json)

        business = Business.find_by_identifier(identifier)

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

        if filing_id:
            rv = CoreFiling.get(identifier, filing_id)
            if not rv:
                return jsonify({'message': f'{identifier} no filings found'
                                }), HTTPStatus.NOT_FOUND

            if str(request.accept_mimetypes) == 'application/pdf':
                report_type = request.args.get('type', None)

                if rv.filing_type == CoreFiling.FilingTypes.CORRECTION.value:
                    # This is required until #5302 ticket implements
                    rv.storage._filing_json['filing']['correction'][
                        'diff'] = rv.json['filing']['correction']['diff']  # pylint: disable=protected-access; # noqa: E501;

                return legal_api.reports.get_pdf(rv.storage, report_type)
            return jsonify(rv.raw if original_filing else rv.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 = CoreFiling.get_filings_by_status(
            business.id,
            [Filing.Status.COMPLETED.value, Filing.Status.PAID.value])
        for filing in filings:
            filing_json = filing.raw
            filing_json['filing']['documents'] = DocumentMetaService(
            ).get_documents(filing_json)
            rv.append(filing_json)

        return jsonify(filings=rv)
Exemple #21
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')