Esempio n. 1
0
def process(correction_filing: Filing, filing: Dict):
    """Render the correction filing onto the business model objects."""
    local_timezone = pytz.timezone('US/Pacific')

    # link to original filing
    original_filing = Filing.find_by_id(
        filing['correction']['correctedFilingId'])
    original_filing.parent_filing = correction_filing

    # add comment to the original filing
    original_filing.comments.append(
        Comment(
            comment=f'This filing was corrected on '
            f'{correction_filing.filing_date.astimezone(local_timezone).date().isoformat()}.',
            staff_id=correction_filing.submitter_id))

    # add comment to the correction filing
    correction_filing.comments.append(
        Comment(comment=filing['correction']['comment'],
                staff_id=correction_filing.submitter_id))
    if not any('incorporationApplication' in x
               for x in correction_filing.legal_filings()):
        # set correction filing to PENDING_CORRECTION, for manual intervention
        # - include flag so that listener in Filing model does not change state automatically to COMPLETE
        correction_filing._status = Filing.Status.PENDING_CORRECTION.value  # pylint: disable=protected-access
        setattr(correction_filing, 'skip_status_listener', True)

    original_filing.save_to_session()
    return correction_filing
Esempio n. 2
0
def test_minimal_comment(session):
    """Assert that a minimal comment can be created."""
    comment = Comment()
    comment.comment = 'some words'
    comment.save()

    assert comment.id is not None
Esempio n. 3
0
def test_comment_delete_is_blocked(session):
    """Assert that an AR filing can be saved."""
    c = Comment()

    with pytest.raises(BusinessException) as excinfo:
        c.delete()

    assert excinfo.value.status_code == HTTPStatus.FORBIDDEN
    assert excinfo.value.error == 'Deletion not allowed.'
Esempio n. 4
0
def test_comment_save_to_session(session):
    """Assert that the comment is saved to the session but not committed."""
    from sqlalchemy.orm.session import Session

    comment = Comment()

    assert not session.new
    assert not Session.object_session(comment)

    comment.save_to_session()

    assert comment.id is None
    assert session.new
    assert Session.object_session(comment)
Esempio n. 5
0
def test_comment_save_to_session(session):
    """Assert the comment is saved toThe session, but not committed."""
    from sqlalchemy.orm.session import Session
    # b = factory_business('CP1234567')
    # filing = factory_filing(b, AR_FILING)

    comment = Comment()

    assert not session.new
    assert not Session.object_session(comment)

    comment.save_to_session()

    assert comment.id is None
    assert session.new
    assert Session.object_session(comment)
Esempio n. 6
0
def load_ledger(business, founding_date):
    """Create a ledger of all filing types."""
    i = 0
    for k, filing_meta in Filing.FILINGS.items():
        filing = copy.deepcopy(FILING_TEMPLATE)
        filing['filing']['header']['name'] = filing_meta['name']
        f = factory_completed_filing(business,
                                     filing,
                                     filing_date=founding_date +
                                     datedelta.datedelta(months=i))
        for c in range(i):
            comment = Comment()
            comment.comment = f'this comment {c}'
            f.comments.append(comment)
        f.save()
        i += 1
    return i
def test_ledger_comment_count(session, client, jwt):
    """Assert that the ledger returns the correct number of comments."""
    # setup
    identifier = 'BC1234567'
    number_of_comments = 10
    business, filing_storage = ledger_element_setup_help(identifier)
    for c in range(number_of_comments):
        comment = Comment()
        comment.comment = f'this comment {c}'
        filing_storage.comments.append(comment)
    filing_storage.save()

    # test
    rv = client.get(f'/api/v2/businesses/{identifier}/filings',
                    headers=create_header(jwt, [UserRoles.SYSTEM.value],
                                          identifier))

    # validate
    assert rv.json['filings'][0]['commentsCount'] == number_of_comments
Esempio n. 8
0
    def post(identifier, filing_id):
        """Create a new comment for the filing."""
        # basic checks
        err_msg, err_code = CommentResource._basic_checks(
            identifier, filing_id, request)
        if err_msg:
            return jsonify(err_msg), err_code

        json_input = request.get_json()

        # check authorization
        if not authorized(identifier, jwt, action=['add_comment']):
            return jsonify({'message':
                            f'You are not authorized to submit a comment for {identifier}.'}), \
                HTTPStatus.UNAUTHORIZED

        # validate comment
        err = validate(json_input, True)
        if err:
            json_input['errors'] = err.msg
            return jsonify(json_input), err.code

        # confirm that the filing ID in the URL is the same as in the json
        if json_input['comment']['filingId'] != filing_id:
            json_input['errors'] = [
                {
                    'error': 'Invalid filingId in request'
                },
            ]
            return jsonify(json_input), HTTPStatus.BAD_REQUEST

        # save comment
        user = User.get_or_create_user_by_jwt(g.jwt_oidc_token_info)
        try:
            comment = Comment()
            comment.comment = json_input['comment']['comment']
            comment.staff_id = user.id
            comment.filing_id = filing_id
            comment.timestamp = datetime.datetime.utcnow()

            comment.save()
        except BusinessException as err:
            reply = json_input
            reply['errors'] = [
                {
                    'error': err.error
                },
            ]
            return jsonify(reply), err.status_code or \
                (HTTPStatus.CREATED if (request.method == 'POST') else HTTPStatus.ACCEPTED)

        # all done
        return jsonify(comment.json), HTTPStatus.CREATED
Esempio n. 9
0
def factory_business_comment(business: Business = None, comment_text: str = 'some text', user: User = None):
    """Create a comment."""
    if not business:
        business = factory_business('CP1234567')

    c = Comment()
    c.business_id = business.id
    c.timestamp = EPOCH_DATETIME
    c.comment = comment_text
    if user:
        c.staff_id = user.id
    c.save()

    return c
Esempio n. 10
0
def process(court_order_filing: Filing, filing: Dict):
    """Render the court order filing into the business model objects."""
    court_order_filing.court_order_file_number = filing['courtOrder'].get(
        'fileNumber')
    court_order_filing.court_order_effect_of_order = filing['courtOrder'].get(
        'effectOfOrder')

    with suppress(IndexError, KeyError, TypeError, ValueError):
        court_order_filing.court_order_date = datetime.fromisoformat(
            filing['courtOrder'].get('orderDate'))

    # add comment to the court order filing
    court_order_filing.comments.append(
        Comment(comment=filing['courtOrder']['orderDetails'],
                staff_id=court_order_filing.submitter_id))
Esempio n. 11
0
def process(registrars_notation_filing: Filing, filing: Dict):
    """Render the registrars notation filing into the business model objects."""
    registrars_notation_filing.court_order_file_number = filing[
        'registrarsNotation'].get('fileNumber')
    registrars_notation_filing.court_order_effect_of_order = filing[
        'registrarsNotation'].get('effectOfOrder')

    with suppress(IndexError, KeyError, TypeError, ValueError):
        registrars_notation_filing.court_order_date = datetime.fromisoformat(
            filing['registrarsNotation'].get('orderDate'))

    # add comment to the registrars notation filing
    registrars_notation_filing.comments.append(
        Comment(comment=filing['registrarsNotation']['orderDetails'],
                staff_id=registrars_notation_filing.submitter_id))
Esempio n. 12
0
def factory_comment(
        business: Business = None, filing: Filing = None, comment_text: str = 'some text', user: User = None):
    """Create a comment."""
    if not business:
        business = factory_business('CP1234567')

    if not filing:
        filing = factory_filing(business, ANNUAL_REPORT)

    c = Comment()
    c.filing_id = filing.id
    c.timestamp = EPOCH_DATETIME
    c.comment = comment_text
    if user:
        c.staff_id = user.id
    c.save()

    return c
Esempio n. 13
0
    def post(identifier):
        """Create a new comment for the business."""
        # basic checks
        business = Business.find_by_identifier(identifier)
        err_msg, err_code = BusinessCommentResource._basic_checks(
            identifier, business, request)
        if err_msg:
            return jsonify(err_msg), err_code

        json_input = request.get_json()

        # check authorization
        if not authorized(identifier, jwt, action=['add_comment']):
            return jsonify({'message':
                            f'You are not authorized to submit a comment for {identifier}.'}), \
                HTTPStatus.UNAUTHORIZED

        # validate comment
        err = validate(json_input, False)
        if err:
            json_input['errors'] = err.msg
            return jsonify(json_input), err.code

        # save comment
        user = User.get_or_create_user_by_jwt(g.jwt_oidc_token_info)
        try:
            comment = Comment()
            comment.comment = json_input['comment']['comment']
            comment.staff_id = user.id
            comment.business_id = business.id
            comment.timestamp = datetime.datetime.utcnow()
            comment.save()
        except BusinessException as err:
            reply = json_input
            reply['errors'] = [
                {
                    'error': err.error
                },
            ]
            return jsonify(reply), err.status_code

        # all done
        return jsonify(comment.json), HTTPStatus.CREATED
Esempio n. 14
0
def test_comment_dump_json(session):
    """Assert the comment json serialization works correctly."""
    identifier = 'CP7654321'
    b = factory_business(session, identifier)
    c = Comment()
    c.business_id = b.id
    c.timestamp = EPOCH_DATETIME
    c.comment = 'a comment'

    assert c.json() == {'comment': 'a comment',
                        'id': None,
                        'staff': 'unknown',
                        'timestamp': datetime.datetime(1970, 1, 1, 0, 0)}
Esempio n. 15
0
def test_comment_block_orm_delete(session):
    """Assert that attempting to delete a filing will raise a BusinessException."""
    from legal_api.exceptions import BusinessException

    b = factory_business('CP1234567')
    c = Comment()
    c.business_id = b.id
    c.timestamp = EPOCH_DATETIME
    c.comment = 'a comment'
    c.save()

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

    assert excinfo.value.status_code == HTTPStatus.FORBIDDEN
    assert excinfo.value.error == 'Deletion not allowed.'
Esempio n. 16
0
def test_comment_save(session):
    """Assert that the comment was saved."""
    from sqlalchemy.orm.session import Session
    b = factory_business('CP1234567')

    comment = Comment()
    comment.business_id = b.id
    comment.timestamp = EPOCH_DATETIME
    comment.comment = 'a comment'

    assert not session.new
    assert not Session.object_session(comment)

    comment.save()

    assert comment.id
    assert not session.dirty
    assert Session.object_session(comment)
Esempio n. 17
0
def test_comment_save(session):
    """Assert that the comment was saved."""
    from sqlalchemy.orm.session import Session

    comment = Comment()
    comment.timestamp = EPOCH_DATETIME
    comment.comment = 'a comment'

    assert not session.new
    assert not Session.object_session(comment)

    comment.save()

    assert comment.id
    assert not session.dirty
    assert Session.object_session(comment)