Exemplo n.º 1
0
def test_add_names_with_changes(app, request, session, previous_names,
                                test_names):

    # imports for just this test
    from namex.services.nro.request_utils import add_names

    # SETUP
    # create an NR
    nr = Request()
    nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost')

    if previous_names:
        add_names(nr, previous_names)

    session.add(nr)
    session.commit()

    # Test
    add_names(nr, test_names)
    session.add(nr)
    session.commit()

    names = nr.names.all()

    assert len(test_names) == len(names)

    for name in names:
        name_found = False
        decision_data_intact = False
        for tn in test_names:
            if tn['name'] == name.name:
                name_found = True
                continue

        assert name_found
Exemplo n.º 2
0
def test_request_add_applicant_existing(app, request, session, applicant1,
                                        applicant2):

    # imports for just this test
    from namex.models import Applicant
    from namex.services.nro.request_utils import add_applicant

    # SETUP
    # create an NR and add an applicant
    nr = Request()
    nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    nr.applicants.append(Applicant(**applicant1))

    session.add(nr)
    session.commit()

    # Test
    # Call add_applicant and then assert the new NR applicant matches our data

    add_applicant(nr, applicant2)

    session.add(nr)
    session.commit()

    appl = nr.applicants.one_or_none()

    nra = dict_to_json_keys(applicant2)
    a = appl.as_dict()
    if a.get('partyId'): a.pop('partyId')

    # check entire dict
    assert nra == a
Exemplo n.º 3
0
def test_add_nr_header_with_priority(priority_cd, expected):

    from namex.services.nro.request_utils import add_nr_header

    nr = Request()
    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    nr_submitter = None

    nr_header = {
        'priority_cd': priority_cd,
        'state_type_cd': 'H',
        'nr_num': 'NR 0000001',
        'request_id': 1,
        'previous_request_id': None,
        'submit_count': 0,
        'request_type_cd': 'REQ',
        'expiration_date': None,
        'additional_info': None,
        'nature_business_info': 'N/A',
        'xpro_jurisdiction': None,
        'submitted_date': EPOCH_DATETIME,
        'last_update': EPOCH_DATETIME
    }

    add_nr_header(nr, nr_header, nr_submitter, user)

    assert nr.priorityCd == expected
Exemplo n.º 4
0
def test_add_nwpta(app, request, session, pns):

    # imports for just this test
    from namex.services.nro.request_utils import add_nwpta

    # SETUP
    # create an NR
    nr = Request()
    nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost')

    session.add(nr)
    session.commit()

    # Test
    add_nwpta(nr, pns)

    session.add(nr)
    session.commit()

    partners = nr.partnerNS.all()

    assert len(pns) == len(partners)

    for partner in partners:
        partner_found = False
        for p in pns:
            if p['partner_jurisdiction_type_cd'] == partner.partnerJurisdictionTypeCd:
                partner_found = True
                continue

        assert partner_found
Exemplo n.º 5
0
def test_add_nr_header_set_state(state_type_cd, nr_names, expected):
    from namex.services.nro.request_utils import add_names, add_nr_header

    # the correct state for a Request that is completed in NRO is determined by the Name states

    nr = Request()
    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    nr_submitter = None

    nr_header = {
        'priority_cd': 'N',
        'state_type_cd': state_type_cd,
        'nr_num': 'NR 0000001',
        'request_id': 1,
        'previous_request_id': None,
        'submit_count': 0,
        'request_type_cd': 'REQ',
        'expiration_date': None,
        'additional_info': None,
        'nature_business_info': 'N/A',
        'xpro_jurisdiction': None,
        'submitted_date': EPOCH_DATETIME,
        'last_update': EPOCH_DATETIME
    }

    add_nr_header(nr, nr_header, nr_submitter, user)
    add_names(nr, nr_names)

    assert nr.stateCd == expected
Exemplo n.º 6
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
Exemplo n.º 7
0
    def fetch_nro_request_and_copy_to_namex_request(self, user: User, nr_number: str, name_request: Request = None) \
            -> Request:
        """Utility function to gather up and copy a Request from NRO to a NameX Request Object
           The request is NOT persisted in this helper method
        """
        try:
            cursor = self.connection.cursor()

            if name_request:
                nr = name_request
                nr_num = nr.nrNum
            else:
                nr_num = nr_number
                nr = Request.find_by_nr(nr_num)
                if not nr:
                    nr = Request()

            nr_header = get_nr_header(cursor, nr_num)

            if not nr_header:
                current_app.logger.info(
                    'Attempting to fetch Request:{} from NRO, but does not exist'
                    .format(nr_num))
                return None
            current_app.logger.debug('fetched nr_header: {}'.format(nr_header))

            # get all the request segments from NRO
            nr_submitter = get_nr_submitter(cursor, nr_header['request_id'])
            nr_applicant = get_nr_requester(cursor, nr_header['request_id'])
            nr_ex_comments = get_exam_comments(cursor, nr_header['request_id'])
            nr_nwpta = get_nwpta(cursor, nr_header['request_id'])
            nr_names = get_names(cursor, nr_header['request_id'])

            current_app.logger.debug('completed all gets')

        except Exception as err:
            current_app.logger.debug(
                'unable to load nr_header: {}'.format(nr_num),
                err.with_traceback(None))
            return None

        add_nr_header(nr, nr_header, nr_submitter, user)
        current_app.logger.debug('completed header for {}'.format(nr.nrNum))
        if nr_applicant:
            add_applicant(nr, nr_applicant)
            current_app.logger.debug('completed applicants for {}'.format(
                nr.nrNum))
        if nr_ex_comments:
            add_comments(nr, nr_ex_comments)
            current_app.logger.debug('completed comments for {}'.format(
                nr.nrNum))
        if nr_nwpta:
            add_nwpta(nr, nr_nwpta)
            current_app.logger.debug('completed nwpta for {}'.format(nr.nrNum))
        if nr_names:
            add_names(nr, nr_names)
            current_app.logger.debug('completed names for {}'.format(nr.nrNum))

        return nr
Exemplo n.º 8
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
Exemplo n.º 9
0
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))
Exemplo n.º 10
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
Exemplo n.º 11
0
def test_fetch_nro_request_and_copy_to_namex_request_with_nr(app, session, nr_num, expected_nr_num):

    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    user.save_to_db()
    nr = Request()
    nr.nrNum = nr_num
    nr.userId = user.id
    nr.save_to_db()

    nr = nro.fetch_nro_request_and_copy_to_namex_request(user, nr_number=12, name_request=nr)

    assert expected_nr_num == None if (expected_nr_num is None) else nr.nrNum
Exemplo n.º 12
0
def create_nr(nr_num: str, state_cd: str, submitted: datetime,
              names: list) -> Request:
    """Create new NR."""
    nr = Request()
    nr.nrNum = nr_num
    nr.stateCd = state_cd
    nr.submittedDate = submitted
    nr._source = 'NRO'
    for name in names:
        nr.names.append(
            create_name(name['name'], name['state'], name['choice']))
    nr.save_to_db()
    return nr
Exemplo n.º 13
0
def helper_create_requests(row_data):

    user = User('automation', 'automation', 'automation', 'internal',
                'localhost')
    user.save_to_db()

    for row in row_data:
        if row['nr_num']:
            nr = Request()
            nr.nrNum = row['nr_num']
            nr.stateCd = row['state']
            nr.userId = user.id
            nr.save_to_db()
Exemplo n.º 14
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
Exemplo n.º 15
0
def test_move_control_of_existing_request_from_nro_missing_nr(app, session):

    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    user.save_to_db()
    nr = Request()
    nr.nrNum = 'NR 9999999'
    nr.stateCd = State.INPROGRESS
    nr.nroLastUpdate = EPOCH_DATETIME
    nr.userId = user.id
    nr.save_to_db()

    warnings = nro.move_control_of_request_from_nro(nr, user)

    assert warnings is not None
Exemplo n.º 16
0
    def post(self, *args, **kwargs):
        json_input = request.get_json()
        if not json_input:
            return {"message": "No input data provided"}, 400

        nr_num = json_input['nameRequest']
        current_app.logger.debug('attempting to load: {}'.format(nr_num))
        if not validNRFormat(nr_num):
            return {"message": "Valid NR format required - 'NR 9999999'"}, 400

        if Request.find_by_nr(nr_num):
            return {
                "message":
                "{nr} already exists in namex, unable to create a duplicate".
                format(nr=nr_num)
            }, 409

        conn = db.get_engine(bind='nro')

        nr_header = get_nr_header(conn, nr_num)
        current_app.logger.debug('nr_header: {}'.format(nr_header))
        if not nr_header:
            return {
                "message":
                "{nr} not found, unable to complete extraction to new system".
                format(nr=nr_num)
            }, 404

        nr_submitter = get_nr_submitter(conn, nr_header['request_id'])
        nr_applicant = get_nr_requester(conn, nr_header['request_id'])
        nr_ex_comments = get_exam_comments(conn, nr_header['request_id'])
        nr_nwpat = get_nwpta(conn, nr_header['request_id'])
        nr_names = get_names(conn, nr_header['request_id'])

        user = User.find_by_username(current_app.config['NRO_SERVICE_ACCOUNT'])

        #Create NR
        new_nr = Request()
        add_nr_header(new_nr, nr_header, nr_submitter, user)
        add_applicant(new_nr, nr_applicant)
        add_comments(new_nr, nr_ex_comments)
        add_nwpta(new_nr, nr_nwpat)
        add_names(new_nr, nr_names)

        new_nr.save_to_db()

        return {
            "message": "{nr} has been successfully copied".format(nr=nr_num)
        }, 200
Exemplo n.º 17
0
def helper_create_requests(row_data):

    user = User('automation', 'automation', 'automation', 'internal',
                'localhost')
    user.save_to_db()

    for row in row_data:
        print('inserting nr:{}'.format(row['nr_num']))
        if row['nr_num']:
            nr = Request()
            nr.nrNum = row['nr_num']
            nr.stateCd = row['state']
            nr.lastUpdate = row['last_update']
            nr.userId = user.id
            nr.save_to_db()
Exemplo n.º 18
0
def test_move_control_of_request_from_nro(app, session, nr_num, expected_nr_num):

    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    user.save_to_db()
    nr = Request()
    nr.nrNum = nr_num
    nr.stateCd = State.INPROGRESS
    nr.nroLastUpdate = EPOCH_DATETIME
    nr.userId = user.id
    nr.save_to_db()

    warnings = nro.move_control_of_request_from_nro(nr, user)

    assert expected_nr_num == None if (expected_nr_num is None) else nr.nrNum
    assert warnings is None
Exemplo n.º 19
0
    def create_name_request(self):
        """
        # !Important! All new name requests should be initially set to the DRAFT state.
        # Use apply_state_change on the name_request to transition to any other state.
        :return:
        """
        try:
            name_request = Request()
            self.generate_nr_keys()

            name_request.stateCd = State.DRAFT
        except Exception as err:
            raise CreateNameRequestError(err)

        return name_request
Exemplo n.º 20
0
def test_add_names_after_reset(app, request, session, previous_names,
                               test_names, expected_states):

    # imports for just this test
    from namex.services.nro.request_utils import add_names

    # SETUP
    # create an NR
    nr = Request()
    nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost')

    if previous_names:
        add_names(nr, previous_names)

    nr.hasBeenReset = True

    session.add(nr)
    session.commit()

    # Test
    add_names(nr, test_names)
    session.add(nr)
    session.commit()

    names = nr.names.all()

    assert len(test_names) == len(names)

    for name in names:
        name_found = False
        decision_data_intact = False
        for tn in test_names:
            if tn['name'] == name.name:
                name_found = True
                if name.state == expected_states[tn['choice_number'] - 1]:
                    decision_data_intact = True
                continue

        assert name_found
        assert decision_data_intact
Exemplo n.º 21
0
def test_update_nr_header_with_mutating_priority(freeze_datetime_utcnow,
                                                 test_name,
                                                 initial_priority_cd,
                                                 second_priority_code,
                                                 expected_cd, expected_dt):

    from namex.services.nro.request_utils import add_nr_header

    nr = Request()
    user = User('idir/bob', 'bob', 'last', 'idir', 'localhost')
    nr_submitter = {
        'submitted_date': EPOCH_DATETIME,
        'submitter': 'doesnt matter'
    }

    nr_header = {
        'priority_cd': initial_priority_cd,
        'state_type_cd': 'H',
        'nr_num': 'NR 0000001',
        'request_id': 1,
        'previous_request_id': None,
        'submit_count': 0,
        'request_type_cd': 'REQ',
        'expiration_date': None,
        'additional_info': None,
        'nature_business_info': 'N/A',
        'xpro_jurisdiction': None,
        'submitted_date': EPOCH_DATETIME,
        'last_update': EPOCH_DATETIME
    }

    print(nr.json())

    add_nr_header(nr, nr_header, nr_submitter, user)

    nr_header['priority_cd'] = second_priority_code
    add_nr_header(nr, nr_header, nr_submitter, user)

    assert expected_cd == nr.priorityCd
    assert expected_dt == nr.priorityDate
Exemplo n.º 22
0
def test_add_comments(app, request, session, test_comments, test_size,
                      should_have_existing_comments):

    # imports for just this test
    from namex.services.nro.request_utils import add_comments

    # SETUP
    # create an NR
    nr = Request()
    nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost')

    if should_have_existing_comments:
        add_comments(nr, test_comments)

    session.add(nr)
    session.commit()

    # Test
    add_comments(nr, test_comments)

    session.add(nr)
    session.commit()

    comments = nr.comments.all()

    assert test_size == len(comments)

    for com in comments:
        comment_found = False
        for tc in test_comments:
            if tc['examiner_comment'] == com.comment:
                comment_found = True
                continue

        assert comment_found
        assert EPOCH_DATETIME == com.timestamp.replace(tzinfo=None)
Exemplo n.º 23
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'
Exemplo n.º 24
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
Exemplo n.º 25
0
async def test_furnish_receipt_message(app, session, stan_server, event_loop,
                                       client_id, entity_stan, future):
    """Assert that events are placed on the email queue and the payment is marked furnished."""
    from queue_common.messages import create_cloud_event_msg
    from queue_common.service import ServiceWorker
    from queue_common.service_utils import subscribe_to_queue
    from namex_pay.worker import APP_CONFIG, furnish_receipt_message, qsm
    from namex.models import Request, State, Payment

    print('test vars')
    print(app, session, stan_server, event_loop, client_id, entity_stan,
          future)
    # setup
    PAYMENT_TOKEN = 'dog'
    NR_NUMBER = 'NR B000001'
    name_request = Request()
    name_request.nrNum = NR_NUMBER
    name_request.stateCd = State.DRAFT
    name_request._source = 'NRO'
    name_request.save_to_db()

    payment = Payment()
    payment.nrId = name_request.id
    payment._payment_token = PAYMENT_TOKEN
    payment._payment_status_code = 'COMPLETED'
    payment.furnished = False
    payment.save_to_db()

    # file handler callback
    msgs = []
    s = ServiceWorker()
    s.sc = entity_stan
    qsm.service = s

    async def cb_handler(msg):
        nonlocal msgs
        nonlocal future
        msgs.append(msg)
        print('call back recvd')
        if len(msgs) == 1:
            future.set_result(True)

    file_handler_subject = APP_CONFIG.EMAIL_PUBLISH_OPTIONS['subject']
    print(f'file_handler_subject:{file_handler_subject}')

    await subscribe_to_queue(entity_stan, file_handler_subject,
                             f'entity_queue.{file_handler_subject}',
                             f'entity_durable_name.{file_handler_subject}',
                             cb_handler)

    print(payment.as_dict())
    # sanity check
    assert name_request.id
    assert payment.nrId == name_request.id

    # test
    await furnish_receipt_message(qsm, payment)

    try:
        await asyncio.wait_for(future, 1, loop=event_loop)
    except Exception as err:
        print(err)

    # results
    processed_payment = Payment.find_by_payment_token(PAYMENT_TOKEN)

    # verify
    assert processed_payment.furnished
    assert len(msgs) == 1
    cloud_event = json.loads(msgs[0].data.decode('utf-8'))
    assert cloud_event['identifier'] == NR_NUMBER