示例#1
0
def save_words_list_name(words_list, queue=False):
    from namex.models import Request as RequestDAO, State, Name as NameDAO
    num = 0
    req = 1460775
    for record in words_list:
        nr_num_label = 'NR 00000'
        num += 1
        req += 1
        nr_num = nr_num_label + str(num)

        nr = RequestDAO()
        nr.nrNum = nr_num
        if queue:
            nr.stateCd = State.DRAFT
            nr.expirationDate = datetime.date.today() + datetime.timedelta(days=1)
        else:
            nr.stateCd = State.APPROVED
        nr.requestId = req
        nr.requestTypeCd = EntityTypes.CORPORATION.value
        nr._source = 'NAMEREQUEST'

        name = NameDAO()
        name.choice = 1
        name.name = record
        name.state = State.APPROVED
        name.corpNum = '0652480'
        nr.names = [name]
        nr.save_to_db()
示例#2
0
def create_nr(nr_num: str, request_state: str, names: list, names_state: list):

    now = datetime.utcnow()

    with freeze_time(now):

        name_request = Request()
        name_request.nrNum = nr_num
        name_request.stateCd = request_state
        name_request._source = 'NRO'
        name_request.expirationDate = add_years(now, 1)
        name_request.entity_type_cd = 'CR'
        # name_request.priorityCd = start_priority
        name_request.save_to_db()

        for index, name in enumerate(names):
            name_state = names_state[index]
            choice = index + 1

            name_obj = Name()
            name_obj.nrId = name_request.id
            name_obj.name = name
            name_obj.state = name_state
            name_obj.choice = choice
            name_obj.name_type_cd = 'CO'
            name_obj.save_to_db()

        return name_request
def test_nr_state_actions():
    nr_model = Request()
    nr_model.expirationDate = datetime.utcnow() + timedelta(days=3)
    nr_model.priorityCd = None
    nr_model.priorityDate = None

    print('\n Draft state actions \n')
    print(repr(NameRequestDraftActions.list()))
    actions = get_nr_state_actions(State.DRAFT, nr_model)
    print(repr(actions))

    print('\n Reserved state actions \n')
    print(repr(NameRequestReservedActions.list()))
    actions = get_nr_state_actions(State.RESERVED, nr_model)
    print(repr(actions))

    print('\n Conditionally reserved state actions \n')
    print(repr(NameRequestReservedActions.list()))
    actions = get_nr_state_actions(State.COND_RESERVE, nr_model)
    print(repr(actions))

    print('\n Conditional state actions \n')
    print(repr(NameRequestActiveActions.list()))
    actions = get_nr_state_actions(State.CONDITIONAL, nr_model)
    print(repr(actions))

    print('\n Approved state actions \n')
    print(repr(NameRequestActiveActions.list()))
    actions = get_nr_state_actions(State.APPROVED, nr_model)
    print(repr(actions))

    print('\n In Progress state actions \n')
    print(repr(NameRequestInProgressActions.list()))
    actions = get_nr_state_actions(State.INPROGRESS, nr_model)
    print(repr(actions))

    print('\n Hold state actions \n')
    print(repr(NameRequestHoldActions.list()))
    actions = get_nr_state_actions(State.HOLD, nr_model)
    print(repr(actions))

    print('\n Historical state actions \n')
    print(repr(NameRequestHistoricalActions.list()))
    actions = get_nr_state_actions(State.HISTORICAL, nr_model)
    print(repr(actions))

    print('\n Cancelled state actions \n')
    print(repr(NameRequestCancelledActions.list()))
    actions = get_nr_state_actions(State.CANCELLED, nr_model)
    print(repr(actions))

    print('\n Rejected state actions \n')
    print(repr(NameRequestActiveRejectedActions.list()))
    actions = get_nr_state_actions(State.REJECTED, nr_model)
    print(repr(actions))
示例#4
0
async def test_update_payment_record(
        app, session, test_name, action_code, start_request_state,
        end_request_state, start_priority, end_priority, start_datetime,
        days_after_start_datetime, start_payment_state, end_payment_state,
        start_payment_date, end_payment_has_value, error):
    """Assert that the update_payment_record works as expected."""
    from namex.models import Request, State, Payment
    from namex_pay.worker import update_payment_record

    print(test_name)

    now = datetime.utcnow()

    with freeze_time(now):
        # setup
        PAYMENT_TOKEN = 'dog'
        NR_NUMBER = 'NR B000001'
        name_request = Request()
        name_request.nrNum = NR_NUMBER
        name_request.stateCd = start_request_state
        name_request._source = 'NRO'
        name_request.expirationDate = start_datetime
        name_request.priorityCd = start_priority
        name_request.save_to_db()

        payment = Payment()
        payment.nrId = name_request.id
        payment._payment_token = PAYMENT_TOKEN
        payment._payment_status_code = start_payment_state
        payment.payment_action = action_code
        payment.furnished = False
        payment._payment_completion_date = start_payment_date
        payment.save_to_db()

        # run test
        if error:  # expecting it to raise an error
            with pytest.raises(error):
                await update_payment_record(payment)
        else:
            # else it was processable
            if not (payment_final := await update_payment_record(payment)):
                payment_final = payment

            nr_final = Request.find_by_nr(NR_NUMBER)

            assert nr_final.stateCd == end_request_state
            assert nr_final.priorityCd == end_priority
            assert nr_final.expirationDate == (
                start_datetime
                or now) + timedelta(days=days_after_start_datetime)
            assert eval(
                f'payment_final.payment_completion_date {end_payment_has_value} None'
            )
            assert payment_final.payment_status_code == end_payment_state
示例#5
0
def test_get_expiry_days(client, test_name, days, action_cd, request_type):
    """
    Test that get_expiry_date method returns a either 56 or 421 days
    """
    mock_nr = RequestDAO()

    # Set defaults, if these exist in the provided data they will be overwritten
    mock_nr.stateCd = State.APPROVED
    mock_nr.request_action_cd = action_cd
    mock_nr.requestTypeCd = request_type
    mock_nr.expirationDate = None
    mock_expiry_days = int(nr_svc.get_expiry_days(mock_nr))

    assert mock_expiry_days == days
示例#6
0
async def test_process_payment(
    app,
    session,
    mocker,
    test_name,
    action_code,
    start_request_state,
    start_priority,
    start_datetime,
    start_payment_state,
    start_payment_date,
):
    from namex.models import Request, State, Payment
    from namex_pay.worker import process_payment, FLASK_APP
    nest_asyncio.apply()

    # setup
    PAYMENT_TOKEN = 'dog'
    NR_NUMBER = 'NR B000001'
    name_request = Request()
    name_request.nrNum = NR_NUMBER
    name_request.stateCd = start_request_state
    name_request._source = 'NRO'
    name_request.expirationDate = start_datetime
    name_request.priorityCd = start_priority
    name_request.save_to_db()

    payment = Payment()
    payment.nrId = name_request.id
    payment._payment_token = PAYMENT_TOKEN
    payment._payment_status_code = start_payment_state
    payment.payment_action = action_code
    payment.furnished = False
    payment._payment_completion_date = start_payment_date
    payment.save_to_db()

    # setup mock and patch
    msg = None

    def catch(qsm, cloud_event_msg):
        nonlocal msg
        msg = cloud_event_msg

    mocker.patch('namex_pay.worker.publish_email_message', side_effect=catch)

    # Test
    pay_msg = {
        "paymentToken": {
            "id": PAYMENT_TOKEN,
            "statusCode": "COMPLETED",
            "filingIdentifier": None
        }
    }
    await process_payment(pay_msg, FLASK_APP)

    print(msg)
    # Verify message that would be sent to the email server
    assert msg['type'] == 'bc.registry.names.request'
    assert msg['source'] == '/requests/NR B000001'
    assert msg['datacontenttype'] == 'application/json'
    assert msg['identifier'] == 'NR B000001'
    assert msg['data']['request']['header']['nrNum'] == NR_NUMBER
    assert msg['data']['request']['paymentToken'] == PAYMENT_TOKEN
    assert msg['data']['request']['statusCode'] == 'DRAFT'
示例#7
0
    def post(*args, **kwargs):

        app_config = current_app.config.get('SOLR_SYNONYMS_API_URL', None)
        if not app_config:
            current_app.logger.error('ENV is not set')
            return None, 'Internal server error', 500

        test_env = 'prod'
        if test_env in app_config:
            current_app.logger.info(
                'Someone is trying to post a new request. Not available.')
            return jsonify(
                {'message': 'Not Implemented in the current environment'}), 501

        json_data = request.get_json()
        if not json_data:
            current_app.logger.error("Error when getting json input")
            return jsonify({'message': 'No input data provided'}), 400

        try:

            restricted = VirtualWordConditionService()
        except Exception as error:
            current_app.logger.error(
                "'Error initializing VirtualWordCondition Service: Error:{0}".
                format(error))
            return jsonify({"message":
                            "Virtual Word Condition Service error"}), 404

        try:
            user = User.find_by_username('name_request_service_account')
            user_id = user.id
        except Exception as error:
            current_app.logger.error(
                "Error getting user id: Error:{0}".format(error))
            return jsonify({"message": "Get User Error"}), 404

        try:
            name_request = Request()
        except Exception as error:
            current_app.logger.error(
                "Error initializing name_request object Error:{0}".format(
                    error))
            return jsonify({"message": "Name Request object error"}), 404

        try:
            nr_num = generate_nr()
            nr_id = get_request_sequence()
        except Exception as error:
            current_app.logger.error(
                "Error getting nr number. Error:{0}".format(error))
            return jsonify({"message": "Error getting nr number"}), 404

        #set the request attributes
        try:
            name_request.id = nr_id
            name_request.submittedDate = datetime.utcnow()
            name_request.requestTypeCd = set_request_type(
                json_data['entity_type'], json_data['request_action'])
            name_request.nrNum = nr_num
        except Exception as error:
            current_app.logger.error(
                "Error setting request header attributes. Error:{0}".format(
                    error))
            return jsonify(
                {"message": "Error setting request header attributes"}), 404

        try:

            if (json_data['stateCd'] == 'COND-RESERVE'):
                name_request.consentFlag = 'Y'

            if json_data['stateCd'] in [State.RESERVED, State.COND_RESERVE]:
                name_request.expirationDate = create_expiry_date(
                    start=name_request.submittedDate,
                    expires_in_days=56,
                    tz=timezone('UTC'))

            name_request.stateCd = json_data['stateCd']
            name_request.entity_type_cd = json_data['entity_type']
            name_request.request_action_cd = json_data['request_action']
        except Exception as error:
            current_app.logger.error(
                "Error setting reserve state and expiration date. Error:{0}".
                format(error))
            return jsonify(
                {"message":
                 "Error setting reserve state and expiration date"}), 404

        #set this to name_request_service_account
        name_request.userId = user_id
        try:
            lang_comment = add_language_comment(json_data['english'], user_id,
                                                nr_id)
            name_request.comments.append(lang_comment)
        except Exception as error:
            current_app.logger.error(
                "Error setting language comment. Error:{0}".format(error))
            return jsonify({"message": "Error setting language comment."}), 404

        try:
            if json_data['nameFlag'] == True:
                name_comment = add_name_comment(user_id, nr_id)
                name_request.comments.append(name_comment)

        except Exception as error:
            current_app.logger.error(
                "Error setting person name comment. Error:{0}".format(error))
            return jsonify({"message":
                            "Error setting person name comment."}), 404

        try:
            if json_data['submit_count'] is None:
                name_request.submitCount = 1
            else:
                name_request.submitCount = +1
        except Exception as error:
            current_app.logger.error(
                "Error setting submit count. Error:{0}".format(error))
            return jsonify({"message": "Error setting submit count."}), 404

        try:
            if json_data['stateCd'] == State.DRAFT:
                # set request header attributes
                name_request = set_draft_attributes(name_request, json_data,
                                                    user_id)
                name_request.save_to_db()
                nrd = Request.find_by_nr(name_request.nrNum)
                try:
                    # set applicant attributes
                    nrd_app = set_applicant_attributes(json_data, nr_id)
                    nrd.applicants.append(nrd_app)

                except Exception as error:
                    current_app.logger.error(
                        "Error setting applicant. Error:{0}".format(error))
                    return jsonify({"message":
                                    "Error setting applicant."}), 404

        except Exception as error:
            current_app.logger.error(
                "Error setting DRAFT attributes. Error:{0}".format(error))
            return jsonify({"message": "Error setting DRAFT attributes."}), 404

        try:

            if json_data['stateCd'] in [
                    State.RESERVED, State.COND_RESERVE, State.DRAFT
            ]:
                name_request.save_to_db()
                nrd = Request.find_by_nr(name_request.nrNum)

        except Exception as error:
            current_app.logger.error(
                "Error saving reservation to db. Error:{0}".format(error))
            return jsonify({"message": "Error saving reservation to db."}), 404

        try:
            nrd = Request.find_by_nr(name_request.nrNum)
        except Exception as error:
            current_app.logger.error(
                "Error retrieving the New NR from the db. Error:{0}".format(
                    error))
            return jsonify(
                {"message": "Error retrieving the New NR from the db."}), 404

        try:
            for name in json_data.get('names', None):
                try:
                    submitted_name = Name()
                    name_id = get_name_sequence()
                    submitted_name.id = name_id
                except Exception as error:
                    current_app.logger.error(
                        "Error on submitted Name object. Error:{0}".format(
                            error))
                    return jsonify(
                        {"message":
                         "Error on submitted_name and sequence."}), 404

                #common name attributes
                try:
                    submitted_name.choice = name['choice']
                    submitted_name.name = name['name']

                    if (name['name_type_cd']):
                        submitted_name.name_type_cd = name['name_type_cd']
                    else:
                        submitted_name.name_type_cd = 'CO'

                    if (json_data['stateCd'] == State.DRAFT):
                        submitted_name.state = 'NE'
                    else:
                        submitted_name.state = json_data['stateCd']

                    if name['designation']:
                        submitted_name.designation = name['designation']

                    submitted_name.nrId = nr_id
                except Exception as error:
                    current_app.logger.error(
                        "Error on common name attributes. Error:{0}".format(
                            error))
                    return jsonify(
                        {"message": "Error on common name attributes."}), 404

                decision_text = None

                if json_data['stateCd'] in [
                        State.RESERVED, State.COND_RESERVE
                ]:
                    try:
                        # only capturing one conflict
                        if (name['conflict1_num']):
                            submitted_name.conflict1_num = name[
                                'conflict1_num']
                        if name['conflict1']:
                            submitted_name.conflict1 = name['conflict1']
                        #conflict text same as Namex
                        decision_text = 'Consent is required from ' + name[
                            'conflict1'] + '\n' + '\n'
                    except Exception as error:
                        current_app.logger.error(
                            "Error on reserved conflict info. Error:{0}".
                            format(error))
                        return jsonify(
                            {"message":
                             "Error on reserved conflict info."}), 404

                else:
                    try:
                        submitted_name.conflict1_num = None
                        submitted_name.conflict1 = None
                    except Exception as error:
                        current_app.logger.error(
                            "Error on draft empty conflict info. Error:{0}".
                            format(error))
                        return jsonify(
                            {"message":
                             "Error on draft empty conflict info."}), 404

                consent_list = name['consent_words']
                if len(consent_list) > 0:
                    for consent in consent_list:
                        try:
                            cnd_instructions = None
                            if consent != "" or len(consent) > 0:
                                cnd_instructions = restricted.get_word_condition_instructions(
                                    consent)
                        except Exception as error:
                            current_app.logger.error(
                                "Error on get consent word. Consent Word[0], Error:{1}"
                                .format(consent, error))
                            return jsonify(
                                {"message":
                                 "Error on get consent words."}), 404

                        try:
                            if (decision_text is None):
                                decision_text = cnd_instructions + '\n'
                            else:
                                decision_text += consent + '- ' + cnd_instructions + '\n'

                            submitted_name.decision_text = decision_text
                        except Exception as error:
                            current_app.logger.error(
                                "Error on adding consent words to decision. Error:{0}"
                                .format(error))
                            return jsonify({
                                "message":
                                "Error on adding consent words to decision text"
                            }), 404
                try:
                    nrd.names.append(submitted_name)
                except Exception as error:
                    current_app.logger.error(
                        "Error appending names. Error:{0}".format(error))
                    return jsonify({"message": "Error appending names"}), 404

            try:
                #save names
                nrd.save_to_db()
            except Exception as error:
                current_app.logger.error(
                    "Error saving the whole nr and names. Error:{0}".format(
                        error))
                return jsonify({"message":
                                "Error saving names to the db"}), 404

        except Exception as error:
            current_app.logger.error(
                "Error setting name. Error:{0}".format(error))
            return jsonify({"message": "Error setting name."}), 404

        #TODO: Need to add verification that the save was successful.

    #update solr for reservation
        try:
            if (json_data['stateCd'] in ['RESERVED', 'COND-RESERVE']):
                solr_name = nrd.names[0].name
                solr_docs = []
                nr_doc = {
                    "id":
                    name_request.nrNum,
                    "name":
                    solr_name,
                    "source":
                    "NR",
                    "start_date":
                    name_request.submittedDate.strftime("%Y-%m-%dT%H:%M:00Z")
                }

                solr_docs.append(nr_doc)
                update_solr('possible.conflicts', solr_docs)
        except Exception as error:
            current_app.logger.error(
                "Error updating solr for reservation. Error:{0}".format(error))
            return jsonify({"message":
                            "Error updating solr for reservation."}), 404

        current_app.logger.debug(name_request.json())
        return jsonify(name_request.json()), 200