Example #1
0
def test_comment_where_no_user(client, jwt, app):
    from namex.models import Request as RequestDAO, State, Name as NameDAO, Comment as CommentDAO, User

    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.INPROGRESS
    nr.requestId = 1460775
    nr._source = 'NRO'
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'TEST NAME ONE'
    nr.names = [name1]
    nr.save_to_db()

    # create JWT & setup header with a Bearer Token using the JWT
    token = jwt.create_jwt(claims, token_header)
    headers = {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
    }

    new_comment = {"comment": "The 13th comment entered by the user."}
    rv = client.post('/api/v1/requests/NR%200000002/comments',
                     data=json.dumps(new_comment),
                     headers=headers)
    assert 404 == rv.status_code
Example #2
0
def test_name_update_via_save_to_db_method(session):
    """Test save via save_to_db() method, which does data transformations."""

    # setup
    test_name = "my good company"
    name_json = {"name": test_name, "state": "NE", "conflict1": "conflict1", "conflict2": "conflict2", "conflict3": "", "consumptionDate": None,  "designation": "LLC", "conflict1_num": "NR 0000001", "decision_text": "my descision", "conflict3_num": "", "conflict2_num": "A123456", "choice": 1}
    name_schema = NameSchema()

    # create a name
    name = Name(name="temp")
    session.add(name)
    session.commit()
    name_id = name.id

    # update it from the json data vi the schema loader
    name_schema.load(name_json, instance=name, partial=False)
    name.save_to_db()


    # get the name from the data base & assert it was updated with data changes
    name = None
    name = Name.query.filter_by(id=name_id).one_or_none()
    assert name.id is not None
    assert name.id == name_id
    assert name.name == test_name.upper() # name should be uppercase
    assert name.conflict1_num == "NR 0000001" # NR number conflicts should be unchanged
    assert name.conflict2_num == "A123456" # corp number conflicts should be unchanged
    assert name.conflict3_num in ("", None)
Example #3
0
def test_reopen_event_history(client, jwt, app):
    from namex.models import Request as RequestDAO, State, Name as NameDAO, User, Event
    from namex.services import EventRecorder

    # add a user for the comment
    user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc',
                'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc')
    user.save_to_db()

    headers = create_header(jwt, [User.EDITOR])

    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.REJECTED
    nr.requestId = 1460775
    nr._source = 'NRO'
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'TEST NAME ONE'
    nr.names = [name1]
    nr.save_to_db()

    EventRecorder.record(user, Event.PATCH, nr, {})

    nr.stateCd = State.INPROGRESS
    EventRecorder.record(user, Event.PUT, nr, {
        "additional": "additional",
        "furnished": "N"
    })

    # get the resource (this is the test)
    rv = client.get('/api/v1/events/NR%200000002', headers=headers)
    assert rv.status_code == 200

    assert b'"user_action": "Re-Open"' in rv.data
Example #4
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()
Example #5
0
def test_get_inprogress_event_history(client, jwt, app):
    from namex.models import Request as RequestDAO, State, Name as NameDAO, User, Event
    from namex.services import EventRecorder

    # add a user for the comment
    user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc',
                'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc')
    user.save_to_db()

    # create JWT & setup header with a Bearer Token using the JWT
    token = jwt.create_jwt(claims, token_header)
    headers = {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
    }

    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.INPROGRESS
    nr.requestId = 1460775
    nr._source = 'NRO'
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'TEST NAME ONE'
    nr.names = [name1]
    nr.save_to_db()

    EventRecorder.record(user, Event.PATCH, nr, {})

    # get the resource (this is the test)
    rv = client.get('/api/v1/events/NR%200000002', headers=headers)
    assert rv.status_code == 200

    assert b'"user_action": "Load NR"' in rv.data
Example #6
0
    def create_name(cls):
        try:
            name = Name()
            name_id = cls.get_name_sequence()
            name.id = name_id
            name.state = NameState.NOT_EXAMINED.value
        except Exception as err:
            raise MapRequestNamesError(err, 'Error setting submitted_name and / or sequence.')

        return name
Example #7
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
Example #8
0
def test_add_new_comment_to_nr(client, jwt, app):
    from namex.models import Request as RequestDAO, State, Name as NameDAO, Comment as CommentDAO, User, \
    Event as EventDAO
    from sqlalchemy import desc

    #add a user for the comment
    user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc',
                'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc')
    user.save_to_db()

    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.INPROGRESS
    nr.requestId = 1460775
    nr._source = 'NRO'
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'TEST NAME ONE'
    nr.names = [name1]
    nr.save_to_db()

    comment1 = CommentDAO()
    comment1.comment = 'This is the first Comment'
    comment1.nr_id = nr.id
    comment1.examinerId = nr.userId
    nr.comments = [comment1]
    nr.save_to_db()

    # create JWT & setup header with a Bearer Token using the JWT
    token = jwt.create_jwt(claims, token_header)
    headers = {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
    }

    # get the resource so we have a template for the request:
    rv = client.get('/api/v1/requests/NR%200000002', headers=headers)
    assert rv.status_code == 200
    # assert we're starting with just one name:
    data = json.loads(rv.data)
    assert len(data['comments']) == 1

    new_comment = {"comment": "The 13th comment entered by the user."}

    rv = client.post('/api/v1/requests/NR%200000002/comments',
                     data=json.dumps(new_comment),
                     headers=headers)

    assert b'"comment": "The 13th comment entered by the user."' in rv.data
    assert 200 == rv.status_code

    event_results = EventDAO.query.filter_by(nrId=nr.id).order_by(
        EventDAO.eventDate.desc()).first_or_404()
    assert event_results.action == 'post'
    assert event_results.eventJson[0:11] == '{"comment":'
Example #9
0
def test_name_search_populated_by_name():
    """Tests changing a name updates the nameSearch column."""
    from namex.models import Name, Request as RequestDAO, State

    name = Name()
    name.choice = 1
    name.name = 'TEST'
    name.state = 'NE'

    nr = RequestDAO()
    nr.nrNum = 'NR 0000001'
    nr.stateCd = State.DRAFT
    nr.names.append(name)
    nr.save_to_db()

    test = RequestDAO.find_by_id(nr.id)
    # sanity check
    names = test.names.all()
    assert len(names) == 1
    assert names[0].name == 'TEST'

    # check nameSearch
    assert nr.nameSearch == '|1TEST1|'

    # alter name
    name.name = 'CHANGED'
    name.save_to_db()

    # check nameSearch
    assert nr.nameSearch == '|1CHANGED1|'
Example #10
0
def create_base_nr():
    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.PENDING_PAYMENT
    nr.requestId = 1460775
    nr._source = ValidSources.NAMEREQUEST.value
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'TEST NAME ONE'
    nr.names = [name1]
    nr.additionalInfo = 'test'
    nr.requestTypeCd = 'CR'
    nr.request_action_cd = 'NEW'
    nr.save_to_db()
    return nr
Example #11
0
def test_has_consumed_name():
    """Assert has_consumed_name."""
    from namex.models import Name, Request as RequestDAO, State
    name = Name()
    name.choice = 1
    name.name = 'TEST'
    name.state = 'APPROVED'

    nr = RequestDAO()
    nr.nrNum = 'NR 0000001'
    nr.stateCd = State.CONSUMED
    nr.names.append(name)
    nr.save_to_db()

    assert nr.has_consumed_name is True
Example #12
0
def _map_submitted_name_consent_words(submitted_name: Name,
                                      consent_list: list):
    """
    Used internally by map_submitted_name.
    :param submitted_name: Name
    :param consent_list: list
    :return:
    """
    decision_text = submitted_name.decision_text
    for consent in consent_list:
        try:
            cnd_instructions = None
            if consent != '' or len(consent) > 0:
                # cnd_instructions = virtual_wc_svc.get_word_condition_instructions(consent)
                pass
        except Exception as err:
            log_error(
                'Error on get consent word. Consent Word[0]'.format(consent),
                err)
            raise MapRequestNamesError('Error mapping consent words.')

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

            submitted_name.decision_text = decision_text
        except Exception as err:
            raise MapRequestNamesError(
                err, 'Error adding consent words to decision.')

    return submitted_name
Example #13
0
def _map_submitted_name_macros(submitted_name: Name, macro_list: list):
    """
    Used internally by map_submitted_name.
    :param submitted_name: Name
    :param macro_list: list
    :return:
    """
    for macro in macro_list:
        try:
            macro_text = None
            if macro != '' or len(macro) > 0:
                macro_text = DecisionReason.find_by_name(macro)
        except Exception as err:
            log_error(
                'Error on get decision reason word. Macro Word[0]'.format(
                    macro), err)
            raise MapRequestNamesError('Error mapping macro words.')

        try:
            if submitted_name.decision_text is None:
                submitted_name.decision_text = macro + '- ' + macro_text.reason + '\n' + '\n'
            else:
                submitted_name.decision_text += macro + '- ' + macro_text.reason + '\n' + '\n'

        except Exception as err:
            raise MapRequestNamesError(
                err, 'Error adding macro words to decision.')

    return submitted_name
Example #14
0
def test_name_schema():
    """Start with a blank database."""
    name_json = {
        "name": "my good company",
        "state": "NE",
        "conflict1": "conflict1",
        "conflict2": "conflict2",
        "conflict3": "conflict3",
        "designation": "LLC",
        "conflict1_num": "NR 0000001",
        "decision_text": "my descision",
        "conflict3_num": "NR 0000003",
        "conflict2_num": "NR 0000002",
        "choice": 1
    }

    name_schema = NameSchema()

    name = Name(name="my good company",
                state="NE",
                conflict1="conflict1",
                conflict2="conflict2",
                conflict3="conflict3",
                consumptionDate=None,
                corpNum=None,
                designation="LLC",
                conflict1_num="NR 0000001",
                decision_text="my descision",
                conflict3_num="NR 0000003",
                conflict2_num="NR 0000002",
                choice=1)

    name_dump = name_schema.dump(name).data

    assert name_dump == name_json
Example #15
0
def test_name_schema_db_query_update(session):
    """Start with a blank database."""

    # setup
    test_name = "my good company"
    name_json = {"name": test_name, "state": "NE", "conflict1": "conflict1", "conflict2": "conflict2", "conflict3": "conflict3", "consumptionDate": None,  "designation": "LLC", "conflict1_num": "NR 0000001", "decision_text": "my descision", "conflict3_num": "NR 0000003", "conflict2_num": "NR 0000002", "choice": 1}
    name_schema = NameSchema()

    # create a name
    name = Name(name="temp")
    session.add(name)
    session.commit()
    name_id = name.id

    # update it from the json data vi the schema loader
    name_schema.load(name_json, instance=name, partial=False)
    session.add(name)
    session.commit()

    # get the name from the data base & assert it was updated
    name = None
    name = Name.query.filter_by(name=test_name).one_or_none()
    assert name.id is not None
    assert name.id == name_id
    assert name.name == test_name
    assert name_json == name_schema.dump(name).data
Example #16
0
def test_name_schema_db_update(session):
    """Start with a blank database."""

    # setup
    test_name = "my good company"
    name_json = {
        "name": "my good company",
        "state": "NE",
        "conflict1": "conflict1",
        "conflict2": "conflict2",
        "conflict3": "conflict3",
        "designation": "LLC",
        "conflict1_num": "NR 0000001",
        "decision_text": "my descision",
        "conflict3_num": "NR 0000003",
        "conflict2_num": "NR 0000002",
        "choice": 1
    }
    name_schema = NameSchema()
    # create a name and add to the DB
    name = Name(name="temp")
    session.add(name)
    session.commit()

    # update the name and resave
    name_schema.load(name_json, instance=name, partial=False)
    session.add(name)
    session.commit()

    assert name.id is not None
    assert name.name == test_name
    assert name_json == name_schema.dump(name).data
Example #17
0
def test_is_expired():
    """Assert is_expired."""
    from namex.models import Name, Request as RequestDAO, State

    name = Name()
    name.choice = 1
    name.name = 'TEST'
    name.state = 'APPROVED'

    nr = RequestDAO()
    nr.nrNum = 'NR 0000001'
    nr.stateCd = State.EXPIRED
    nr.names.append(name)
    nr.save_to_db()

    assert nr.is_expired is True
Example #18
0
def build_name(test_name, generate_id_seq=True):
    name = NameDAO()
    if generate_id_seq:
        seq = db.Sequence('names_id_seq')
        name_id = db.engine.execute(seq)
        name.id = test_name.get('id', name_id)

    name.choice = 1
    name.name = test_name.get('name', '')
    name.designation = test_name.get('designation', '')
    name.name_type_cd = test_name.get('name_type_cd', '')
    name.consent_words = test_name.get('consent_words', '')
    name.conflict1 = test_name.get('conflict1', '')
    name.conflict1_num = test_name.get('conflict1_num', '')
    name.corpNum = test_name.get('corpNum', None)

    return name
Example #19
0
def test_name_create(session):
    """Start with a blank database."""

    name = Name(name= "my good company", state= "NE", conflict1= None, conflict3= None, consumptionDate= None, conflict2= None, designation= None, conflict1_num= None, decision_text= None, conflict3_num= None, conflict2_num= None, choice= 1)

    session.add(name)
    session.commit()

    assert name.id is not None
Example #20
0
def test_add_new_blank_name_to_nr(client, jwt, app):

    # add NR to database
    from namex.models import Request as RequestDAO, State, Name as NameDAO
    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.INPROGRESS
    nr.requestId = 1460775
    nr._source = 'NRO'
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'ONE'
    nr.names = [name1]
    nr.save_to_db()

    # create JWT & setup header with a Bearer Token using the JWT
    token = jwt.create_jwt(claims, token_header)
    headers = {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
    }

    # get the resource so we have a template for the request:
    rv = client.get('/api/v1/requests/NR%200000002', headers=headers)
    assert rv.status_code == 200
    # assert we're starting with just one name:
    data = json.loads(rv.data)
    assert len(data['names']) == 1

    new_name = data['names'][0].copy()
    new_name['name'] = ''
    new_name['choice'] = 2
    data['names'].append(new_name)

    # Update with a brand new name (this is the test)
    rv = client.put('/api/v1/requests/NR%200000002',
                    data=json.dumps(data),
                    headers=headers)

    data = json.loads(rv.data)
    assert 200 == rv.status_code
    assert len(data['names']) == 1
Example #21
0
def test_add_clean_name_to_nr(client, jwt, app):
    # add NR to database
    from namex.models import Request as RequestDAO, State, Name as NameDAO, User, Event as EventDAO
    # add a user for the comment
    user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc',
                'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc')
    user.save_to_db()

    user_id = user.id

    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.INPROGRESS
    nr.requestId = 1460775
    nr.userId = user_id
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'B,S&J ENTERPRISES LTD.'
    name1.state = State.APPROVED
    nr.names = [name1]
    nr.save_to_db()

    # create JWT & setup header with a Bearer Token using the JWT
    token = jwt.create_jwt(claims, token_header)
    headers = {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
    }

    rv = client.put('/api/v1/requests/NR%200000002/names/1',
                    data=json.dumps(name1.as_dict()),
                    headers=headers)
    assert rv.status_code == 200

    event_results = EventDAO.query.filter_by(nrId=nr.id).order_by(
        EventDAO.eventDate.desc()).first_or_404()
    assert event_results.action == 'put'

    test_string = event_results.eventJson
    test_dict = json.loads(test_string)

    assert 'BSJ ENTERPRISES' == test_dict['clean_name']
Example #22
0
def _map_submitted_name_conflicts(submitted_name: Name, request_name: dict):
    """
    Used internally by map_submitted_name.
    :param submitted_name: Name
    :param request_name: dict
    :return:
    """
    try:
        # Only capturing one conflict
        if request_name.get('conflict1_num'):
            submitted_name.conflict1_num = request_name.get('conflict1_num')
        if request_name.get('conflict1'):
            submitted_name.conflict1 = request_name.get('conflict1')
        # Conflict text same as Namex
        submitted_name.decision_text = 'Consent is required from ' + request_name.get(
            'conflict1') + '\n' + '\n'
    except Exception as err:
        raise MapRequestNamesError(err, 'Error on reserved conflict info.')

    return submitted_name
Example #23
0
def test_datapump_nr_requires_consent_flag(app, mocker, consent_flag,
                                           state_cd):

    # create minimal NR to send to NRO
    nr = Request()
    nr.nrNum = 'NR 0000001'
    nr.stateCd = state_cd
    nr.consentFlag = consent_flag
    nr.lastUpdate = datetime(1970,
                             1,
                             1,
                             00,
                             00,
                             tzinfo=timezone('US/Pacific', ))

    # requires the username
    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    nr.activeUser = user

    # add name(s) to the NR - max 3
    for i in range(1, 4):
        name = Name()
        name.state = Name.APPROVED if i == 1 else Name.NOT_EXAMINED
        name.name = 'sample name {}'.format(i)
        name.choice = i
        name.decision_text = 'All good to go {}'.format(i)
        nr.names.append(name)

    # mock the oracle cursor
    oc = mocker.MagicMock()
    # make the real call
    nro_data_pump_update(nr, ora_cursor=oc, expires_days=60)

    oc.callfunc.assert_called_with(
        'NRO_DATAPUMP_PKG.name_examination_func',  # package.func_name
        str,
        [
            'NR 0000001',  # p_nr_number
            'A',  # p_status
            '19700302',  # p_expiry_date (length=8)
            'Y',  # p_consent_flag
            'bob',  # p_examiner_id (anything length <=7)
            'A****All good to go 1',  # p_choice1
            None,  # p_choice2
            None,  # p_choice3
            None,  # p_exam_comment
            '',  # p_add_info - not used in proc anymore
            None,  # p_confname1A
            None,  # p_confname1B
            None,  # p_confname1C
            None,  # p_confname2A
            None,  # p_confname2B
            None,  # p_confname2C
            None,  # p_confname3A
            None,  # p_confname3B
            None
        ])  # p_confname3C
Example #24
0
def test_datapump(app, mocker, start_date, expected_date):

    # create minimal NR to send to NRO
    nr = Request()
    nr.nrNum = 'NR 0000001'
    nr.stateCd = State.REJECTED
    nr.consentFlag = 'N'
    nr.lastUpdate = start_date

    # requires the username
    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    nr.activeUser = user

    # add name(s) to the NR - max 3
    for i in range(1, 4):
        name = Name()
        name.state = Name.REJECTED
        name.name = 'sample name {}'.format(i)
        name.choice = i
        name.decision_text = 'No Distinctive Term {}'.format(i)
        nr.names.append(name)

    # mock the oracle cursor
    oc = mocker.MagicMock()
    # make the real call
    nro_data_pump_update(nr, ora_cursor=oc, expires_days=56)

    oc.callfunc.assert_called_with(
        'NRO_DATAPUMP_PKG.name_examination_func',  # package.func_name
        str,
        [
            'NR 0000001',  # p_nr_number
            'R',  # p_status
            expected_date.strftime('%Y%m%d'),  # p_expiry_date (length=8)
            'N',  # p_consent_flag
            'bob',  # p_examiner_id (anything length <=7)
            'R****No Distinctive Term 1',  # p_choice1
            'R****No Distinctive Term 2',  # p_choice2
            'R****No Distinctive Term 3',  # p_choice3
            None,  # p_exam_comment
            '',  # p_add_info - not used in proc anymore
            None,  # p_confname1A
            None,  # p_confname1B
            None,  # p_confname1C
            None,  # p_confname2A
            None,  # p_confname2B
            None,  # p_confname2C
            None,  # p_confname3A
            None,  # p_confname3B
            None
        ])  # p_confname3C
Example #25
0
def test_remove_name_from_nr(client, jwt, app):

    # add NR to database
    from namex.models import Request as RequestDAO, State, Name as NameDAO
    nr = RequestDAO()
    nr.nrNum = 'NR 0000002'
    nr.stateCd = State.INPROGRESS
    nr.requestId = 1460775
    nr._source = 'NRO'
    name1 = NameDAO()
    name1.choice = 1
    name1.name = 'ONE'
    name2 = NameDAO()
    name2.choice = 2
    name2.name = 'TWO'
    nr.names = [name1, name2]
    nr.save_to_db()

    # create JWT & setup header with a Bearer Token using the JWT
    token = jwt.create_jwt(claims, token_header)
    headers = {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
    }

    # get the resource so we have a template for the request:
    rv = client.get('/api/v1/requests/NR%200000002', headers=headers)
    assert rv.status_code == 200
    # assert we're starting with just one name:
    data = json.loads(rv.data)
    assert len(data['names']) == 2

    for name in data['names']:
        if name['choice'] == 2:
            name['name'] = ''

    # Update with one blank name name (should remove the blank name)
    rv = client.put('/api/v1/requests/NR%200000002',
                    data=json.dumps(data),
                    headers=headers)

    data = json.loads(rv.data)
    assert 200 == rv.status_code
    assert len(data['names']) == 1
Example #26
0
def add_names(new_nr, nr_names):
    NAME_STATE = {
        'NE': Name.NOT_EXAMINED,
        'A': Name.APPROVED,
        'R': Name.REJECTED,
        'C': Name.CANCELED
    }
    last_choice = 0
    for n in nr_names:
        if last_choice != n[
                'choice_number']:  # TODO remove this when the view is fixed
            last_choice = n['choice_number']
            name = Name()
            name.state = Name.NOT_EXAMINED if n[
                'name_state_type_cd'] is None else NAME_STATE[
                    n['name_state_type_cd']]
            name.choice = n['choice_number']
            name.name = n['name']
            name.designation = n['designation']

            new_nr.names.append(name)
Example #27
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
Example #28
0
def create_name(name: str, state: str, choice: int) -> Name:
    """Create new name."""
    name = Name(name=name, state=state, choice=choice)
    name.save_to_db()
    return name
Example #29
0
def _map_submitted_name_attrs(submitted_name: Name, request_name: dict,
                              **kwargs):
    """
    Used internally by map_submitted_name.
    :param submitted_name: Name
    :param request_name: dict
    :key nr_id: int
    :key new_state_code: str
    :return:
    """
    nr_id = kwargs.get('nr_id')
    new_state_code = kwargs.get('new_state_code')

    try:
        submitted_name.nrId = nr_id
        submitted_name.choice = request_name.get('choice', 1)
        submitted_name.name_type_cd = request_name.get('name_type_cd', 'CO')
        submitted_name.name = convert_to_ascii(request_name.get('name', ''))
        submitted_name.designation = request_name.get('designation', '')
        # For existing businesses
        if isinstance(request_name.get('corpNum'), str):
            # To clear the corpNum use an empty string in the data payload
            submitted_name.corpNum = convert_to_ascii(
                request_name.get('corpNum'))

        if new_state_code == State.DRAFT:
            submitted_name.state = NameState.NOT_EXAMINED.value

        elif new_state_code == State.COND_RESERVE:
            submitted_name.state = NameState.COND_RESERVE.value

        elif new_state_code == State.RESERVED:
            submitted_name.state = NameState.RESERVED.value

        elif new_state_code == State.CONDITIONAL:
            submitted_name.state = NameState.CONDITION.value

        elif new_state_code == State.APPROVED:
            submitted_name.state = NameState.APPROVED.value

    except Exception as err:
        raise MapRequestNamesError(err,
                                   'Error setting common name attributes.')

    return submitted_name
Example #30
0
def add_names(nr, nr_names):
    NAME_STATE={
        'NE': Name.NOT_EXAMINED,
        'A': Name.APPROVED,
        'R': Name.REJECTED,
        'C': Name.CONDITION
    }

    # tracker to check whether all name choices are covered
    name_choice_numbers = [1,2,3]

    for n in nr_names:

        # find existing name record
        name_found = False
        for name in nr.names.all():
            if name.choice == n['choice_number']:
                name_found = True

                name.name = n['name']
                name.designation = n['designation']

                # if this NR hasn't recently been reset, set name and NR states as well
                if not nr.hasBeenReset:
                    name.state = Name.NOT_EXAMINED if n['name_state_type_cd'] is None \
                        else NAME_STATE[n['name_state_type_cd']]

                    if nr.stateCd in ['COMPLETED', State.REJECTED] and name.state == Name.APPROVED:
                        nr.stateCd = State.APPROVED
                    elif nr.stateCd in ['COMPLETED', State.REJECTED,
                                        State.APPROVED] and name.state == Name.CONDITION:
                        nr.stateCd = State.CONDITIONAL
                    elif nr.stateCd == 'COMPLETED' and name.state == Name.REJECTED:
                        nr.stateCd = State.REJECTED

                name_choice_numbers.remove(name.choice)

                break

        # if we didn't find the name in the existing Namex names, add it - it's been added in NRO
        if not name_found:
            name = Name()
            name.state = Name.NOT_EXAMINED if n['name_state_type_cd'] is None else NAME_STATE[n['name_state_type_cd']]
            name.choice = n['choice_number']
            name.name = n['name']
            name.designation = n['designation']

            if nr.stateCd in ['COMPLETED', State.REJECTED] and name.state == Name.APPROVED:
                nr.stateCd = State.APPROVED
            elif nr.stateCd in ['COMPLETED', State.REJECTED, State.APPROVED] and name.state == Name.CONDITION:
                nr.stateCd = State.CONDITIONAL
            elif nr.stateCd == 'COMPLETED' and name.state == Name.REJECTED:
                nr.stateCd = State.REJECTED

            nr.names.append(name)

            name_choice_numbers.remove(name.choice)

    # if there were any names not send back from NRO that are in Namex, remove them from Namex
    # since they were deleted in NRO
    if name_choice_numbers is not []:
        for name in nr.names.all():
            if name.choice in name_choice_numbers:
                nr.names.remove(name)