Exemplo n.º 1
0
def test_add_json_and_payment_after_saved_filing(session):
    """Assert that the json can be added in the same session that a paymentToken was applied."""
    filing = Filing()
    filing.filing_date = EPOCH_DATETIME
    filing.save()

    # sanity check starting value
    assert filing.status == Filing.Status.DRAFT.value

    filing.payment_token = 'payment token'
    filing.filing_json = ANNUAL_REPORT

    assert filing.json
    assert filing.status == Filing.Status.PENDING.value
Exemplo n.º 2
0
def create_filing(token, json_filing=None, business_id=None, filing_date=EPOCH_DATETIME):
    """Return a test filing."""
    from legal_api.models import Filing
    filing = Filing()
    filing.payment_token = str(token)
    filing.filing_date = filing_date

    if json_filing:
        filing.filing_json = json_filing
    if business_id:
        filing.business_id = business_id

    filing.save()
    return filing
Exemplo n.º 3
0
    def _create_invoice(business: Business,
                        filing: Filing,
                        filing_types: list,
                        user_jwt: JwtManager) \
            -> Tuple[int, dict, int]:
        """Create the invoice for the filing submission.

        Returns: {
            int: the paymentToken (id), or None
            dict: a dict of errors, or None
            int: the HTTPStatus error code, or None
        }
        """
        payment_svc_url = current_app.config.get('PAYMENT_SVC_URL')
        mailing_address = business.mailing_address.one_or_none()

        payload = {
            'paymentInfo': {'methodOfPayment': 'CC'},
            'businessInfo': {
                'businessIdentifier': f'{business.identifier}',
                'corpType': f'{business.identifier[:-7]}',
                'businessName': f'{business.legal_name}',
                'contactInfo': {'city': mailing_address.city,
                                'postalCode': mailing_address.postal_code,
                                'province': mailing_address.region,
                                'addressLine1': mailing_address.street,
                                'country': mailing_address.country}
            },
            'filingInfo': {
                'filingTypes': filing_types
            }
        }
        try:
            token = user_jwt.get_token_auth_header()
            headers = {'Authorization': 'Bearer ' + token}
            rv = requests.post(url=payment_svc_url,
                               json=payload,
                               headers=headers,
                               timeout=20.0)
        except (exceptions.ConnectionError, exceptions.Timeout) as err:
            current_app.logger.error(f'Payment connection failure for {business.identifier}: filing:{filing.id}', err)
            return {'message': 'unable to create invoice for payment.'}, HTTPStatus.PAYMENT_REQUIRED

        if rv.status_code == HTTPStatus.OK or rv.status_code == HTTPStatus.CREATED:
            pid = rv.json().get('id')
            filing.payment_token = pid
            filing.save()
            return None, None
        return {'message': 'unable to create invoice for payment.'}, HTTPStatus.PAYMENT_REQUIRED
Exemplo n.º 4
0
def test_get_filings_by_status__default_order(session):
    """Assert that a filing can be retrieved.

    by status and is returned in the default order.
    default order is submission_date, and then effective_date.
    """
    # setup
    base_filing = copy.deepcopy(FILING_HEADER)
    base_filing['specialResolution'] = SPECIAL_RESOLUTION
    uow = versioning_manager.unit_of_work(session)
    business = factory_business('CP1234567')

    completion_date = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc)

    # setup - create multiple filings on the same day & time
    filing_ids = []
    file_counter = -1
    with freeze_time(completion_date):
        for i in range(0, 5):
            transaction = uow.create_transaction(session)
            payment_token = str(i)
            effective_date = f'200{i}-04-15T00:00:00+00:00'

            base_filing['filing']['header']['effectiveDate'] = effective_date
            filing = Filing()
            filing._filing_date = completion_date
            filing.business_id = business.id
            filing.filing_json = base_filing
            filing.effective_date = datetime.datetime.fromisoformat(
                effective_date)
            filing.payment_token = payment_token
            filing.transaction_id = transaction.id
            filing.payment_completion_date = completion_date
            filing.save()

            filing_ids.append(filing.id)
            file_counter += 1

    # test
    rv = Filing.get_filings_by_status(business.id,
                                      [Filing.Status.COMPLETED.value])

    # check
    assert rv
    # filings should be in newest to oldest effective date order
    for filing in rv:
        assert filing.id == filing_ids[file_counter]
        file_counter -= 1
Exemplo n.º 5
0
def factory_completed_filing(business, data_dict, filing_date=FROZEN_DATETIME):
    """Create a completed filing."""
    filing = Filing()
    filing.business_id = business.id
    filing.filing_date = filing_date
    filing.filing_json = data_dict
    filing.save()

    uow = versioning_manager.unit_of_work(db.session)
    transaction = uow.create_transaction(db.session)
    filing.transaction_id = transaction.id
    filing.payment_token = 1
    filing.payment_completion_date = (datetime.now()).replace(tzinfo=timezone.utc)
    filing.save()
    return filing
Exemplo n.º 6
0
def test_add_payment_completion_date_after_payment(session):
    """Assert that the json can be added in the same session that a paymentToken was applied."""
    filing = Filing()
    filing.filing_date = EPOCH_DATETIME
    filing.save()

    filing.payment_token = 'payment token'
    filing.filing_json = ANNUAL_REPORT

    # sanity check starting position
    assert filing.json
    assert filing.status == Filing.Status.PENDING.value

    filing.payment_completion_date = EPOCH_DATETIME
    print(filing.status)
    assert filing.status == Filing.Status.COMPLETED.value
Exemplo n.º 7
0
def create_filing(token=None, filing_json=None, business_id=None, filing_date=EPOCH_DATETIME, bootstrap_id: str = None):
    """Return a test filing."""
    filing = Filing()
    if token:
        filing.payment_token = str(token)
    filing.filing_date = filing_date

    if filing_json:
        filing.filing_json = filing_json
    if business_id:
        filing.business_id = business_id
    if bootstrap_id:
        filing.temp_reg = bootstrap_id

    filing.save()
    return filing
Exemplo n.º 8
0
def create_filing(token=None, json_filing=None, business_id=None, filing_date=EPOCH_DATETIME, bootstrap_id: str = None):
    """Return a test filing."""
    from legal_api.models import Filing
    filing = Filing()
    if token:
        filing.payment_token = str(token)
    filing.filing_date = filing_date

    if json_filing:
        filing.filing_json = json_filing
    if business_id:
        filing.business_id = business_id
    if bootstrap_id:
        filing.temp_reg = bootstrap_id

    filing.save()
    return filing
Exemplo n.º 9
0
def test_get_filings_by_status(session):
    """Assert that a filing can be retrieved by status."""
    uow = versioning_manager.unit_of_work(session)
    transaction = uow.create_transaction(session)
    business = factory_business('CP1234567')
    payment_token = '1000'
    filing = Filing()
    filing.business_id = business.id
    filing.filing_json = ANNUAL_REPORT
    filing.payment_token = payment_token
    filing.transaction_id = transaction.id
    filing.payment_completion_date = datetime.datetime.utcnow()
    filing.save()

    rv = Filing.get_filings_by_status(business.id, [Filing.Status.COMPLETED.value])

    assert rv
    assert rv[0].status == Filing.Status.COMPLETED.value
Exemplo n.º 10
0
def test_filing_orm_delete_blocked_if_invoiced(session):
    """Assert that attempting to delete a filing will raise a BusinessException."""
    from legal_api.exceptions import BusinessException

    b = factory_business('CP1234567')

    filing = Filing()
    filing.business_id = b.id
    filing.filing_date = datetime.datetime.utcnow()
    filing.filing_json = ANNUAL_REPORT
    filing.payment_token = 'a token'
    filing.save()

    with pytest.raises(BusinessException) as excinfo:
        session.delete(filing)
        session.commit()

    assert excinfo.value.status_code == HTTPStatus.FORBIDDEN
    assert excinfo.value.error == 'Deletion not allowed.'
Exemplo n.º 11
0
def factory_completed_filing(business, data_dict, filing_date=FROZEN_DATETIME, payment_token=None):
    """Create a completed filing."""
    if not payment_token:
        payment_token = str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', '')

    with freeze_time(filing_date):

        filing = Filing()
        filing.business_id = business.id
        filing.filing_date = filing_date
        filing.filing_json = data_dict
        filing.save()

        uow = versioning_manager.unit_of_work(db.session)
        transaction = uow.create_transaction(db.session)
        filing.transaction_id = transaction.id
        filing.payment_token = payment_token
        filing.effective_date = filing_date
        filing.payment_completion_date = filing_date
        filing.save()
    return filing
Exemplo n.º 12
0
    def _create_invoice(business: Business,  # pylint: disable=too-many-locals
                        filing: Filing,
                        filing_types: list,
                        user_jwt: JwtManager,
                        payment_account_id: str = None) \
            -> Tuple[int, dict, int]:
        """Create the invoice for the filing submission.

        Returns: {
            int: the paymentToken (id), or None
            dict: a dict of errors, or None
            int: the HTTPStatus error code, or None
        }
        """
        payment_svc_url = current_app.config.get('PAYMENT_SVC_URL')

        if filing.filing_type == Filing.FILINGS[
                'incorporationApplication'].get('name'):
            mailing_address = Address.create_address(
                filing.json['filing']['incorporationApplication']['offices']
                ['registeredOffice']['mailingAddress'])
            corp_type = filing.json['filing']['business'].get(
                'legalType', Business.LegalTypes.BCOMP.value)

            try:
                business.legal_name = filing.json['filing'][
                    'incorporationApplication']['nameRequest']['legalName']
            except KeyError:
                business.legal_name = business.identifier

        else:
            mailing_address = business.mailing_address.one_or_none()
            corp_type = business.legal_type if business.legal_type else \
                filing.json['filing']['business'].get('legalType')

        payload = {
            'businessInfo': {
                'businessIdentifier': f'{business.identifier}',
                'corpType': f'{corp_type}',
                'businessName': f'{business.legal_name}',
                'contactInfo': {
                    'city': mailing_address.city,
                    'postalCode': mailing_address.postal_code,
                    'province': mailing_address.region,
                    'addressLine1': mailing_address.street,
                    'country': mailing_address.country
                }
            },
            'filingInfo': {
                'filingTypes': filing_types
            }
        }

        folio_number = filing.json['filing']['header'].get('folioNumber', None)
        if folio_number:
            payload['filingInfo']['folioNumber'] = folio_number

        if user_jwt.validate_roles([STAFF_ROLE]) or \
                user_jwt.validate_roles([SYSTEM_ROLE]):
            account_info = {}
            routing_slip_number = get_str(filing.filing_json,
                                          'filing/header/routingSlipNumber')
            if routing_slip_number:
                account_info['routingSlip'] = routing_slip_number
            bcol_account_number = get_str(filing.filing_json,
                                          'filing/header/bcolAccountNumber')
            if bcol_account_number:
                account_info['bcolAccountNumber'] = bcol_account_number
            dat_number = get_str(filing.filing_json, 'filing/header/datNumber')
            if dat_number:
                account_info['datNumber'] = dat_number

            if account_info:
                payload['accountInfo'] = account_info
        try:
            token = user_jwt.get_token_auth_header()
            headers = {
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/json'
            }
            rv = requests.post(url=payment_svc_url,
                               json=payload,
                               headers=headers,
                               timeout=20.0)
        except (exceptions.ConnectionError, exceptions.Timeout) as err:
            current_app.logger.error(
                f'Payment connection failure for {business.identifier}: filing:{filing.id}',
                err)
            return {
                'message': 'unable to create invoice for payment.'
            }, HTTPStatus.PAYMENT_REQUIRED

        if rv.status_code in (HTTPStatus.OK, HTTPStatus.CREATED):
            pid = rv.json().get('id')
            filing.payment_token = pid
            filing.payment_status_code = rv.json().get('statusCode', '')
            filing.payment_account = payment_account_id
            filing.save()
            return {
                'isPaymentActionRequired':
                rv.json().get('isPaymentActionRequired', False)
            }, HTTPStatus.CREATED

        if rv.status_code == HTTPStatus.BAD_REQUEST:
            # Set payment error type used to retrieve error messages from pay-api
            error_type = rv.json().get('type')
            filing.payment_status_code = error_type
            filing.save()

            return {
                'payment_error_type': error_type,
                'message': rv.json().get('detail')
            }, HTTPStatus.PAYMENT_REQUIRED

        return {
            'message': 'unable to create invoice for payment.'
        }, HTTPStatus.PAYMENT_REQUIRED
Exemplo n.º 13
0
def test_unsaved_filing_lock(session):
    """Assert that an unsaved filing, even with an invoice, is not locked."""
    # not locked
    filing = Filing()
    filing.payment_token = 'payment_token'
    assert not filing.locked
Exemplo n.º 14
0
    def _create_invoice(business: Business,
                        filing: Filing,
                        filing_types: list,
                        user_jwt: JwtManager) \
            -> Tuple[int, dict, int]:
        """Create the invoice for the filing submission.

        Returns: {
            int: the paymentToken (id), or None
            dict: a dict of errors, or None
            int: the HTTPStatus error code, or None
        }
        """
        payment_svc_url = current_app.config.get('PAYMENT_SVC_URL')

        if filing.filing_type == Filing.FILINGS[
                'incorporationApplication'].get('name'):
            mailing_address = Address.create_address(
                filing.json['filing']['incorporationApplication']['offices']
                ['registeredOffice']['mailingAddress'])
            corp_type = filing.json['filing']['incorporationApplication'][
                'nameRequest']['legalType']
        else:
            mailing_address = business.mailing_address.one_or_none()
            corp_type = business.identifier[:-7]

        payload = {
            'paymentInfo': {
                'methodOfPayment': 'CC'
            },
            'businessInfo': {
                'businessIdentifier': f'{business.identifier}',
                'corpType': f'{corp_type}',
                'businessName': f'{business.legal_name}',
                'contactInfo': {
                    'city': mailing_address.city,
                    'postalCode': mailing_address.postal_code,
                    'province': mailing_address.region,
                    'addressLine1': mailing_address.street,
                    'country': mailing_address.country
                }
            },
            'filingInfo': {
                'filingTypes': filing_types
            }
        }

        if user_jwt.validate_roles([STAFF_ROLE]):
            routing_slip_number = get_str(filing.filing_json,
                                          'filing/header/routingSlipNumber')
            if routing_slip_number:
                payload['accountInfo'] = {'routingSlip': routing_slip_number}
        try:
            token = user_jwt.get_token_auth_header()
            headers = {
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/json'
            }
            rv = requests.post(url=payment_svc_url,
                               json=payload,
                               headers=headers,
                               timeout=20.0)
        except (exceptions.ConnectionError, exceptions.Timeout) as err:
            current_app.logger.error(
                f'Payment connection failure for {business.identifier}: filing:{filing.id}',
                err)
            return {
                'message': 'unable to create invoice for payment.'
            }, HTTPStatus.PAYMENT_REQUIRED

        if rv.status_code == HTTPStatus.OK or rv.status_code == HTTPStatus.CREATED:
            pid = rv.json().get('id')
            filing.payment_token = pid
            filing.save()
            return None, None

        if rv.status_code == HTTPStatus.BAD_REQUEST:
            return {
                'code': rv.json().get('code'),
                'message': rv.json().get('message')
            }, HTTPStatus.PAYMENT_REQUIRED

        return {
            'message': 'unable to create invoice for payment.'
        }, HTTPStatus.PAYMENT_REQUIRED