Exemplo n.º 1
0
def test_map_request_data(client, jwt, app):
    """
    Setup:
    Test:
    Validate:
    :param client:
    :param jwt:
    :param app:
    :return:
    """
    nr_svc = NameRequestService()
    # Set data to the service
    input_data = {}
    nr_svc.request_data = input_data

    # Build the NR structure
    nr_model = build_nr(State.DRAFT)
    nr_model.save_to_db()

    # Apply the state change
    updated_nr_model = nr_svc.apply_state_change(
        nr_model, State.DRAFT, NameRequest.handle_name_request_update)

    # Test the result
    assert updated_nr_model is not None
def test_initial_to_reserved(client, jwt, app):
    """
    Setup:
    - Initialize NameRequestService
    - Create a new Request model instance
    Test:
    - Call apply_state_change on the NameRequestService instance
    - Make sure to pass in the Request model instance to apply_state_change
    - Make sure to pass in the appropriate apply_state_change handler eg. handle_name_request_<create|update> to apply_state_change
    Validate:
    - That the state change is successful
    :param client:
    :param jwt:
    :param app:
    :return:
    """
    nr_svc = NameRequestService()
    # Set data to the service
    input_data = {}
    nr_svc.request_data = input_data

    # Build the NR structure
    nr_model = build_nr(State.DRAFT)
    nr_model.save_to_db()

    # Apply the state change
    updated_nr_model = nr_svc.apply_state_change(
        nr_model, State.RESERVED, NameRequest.handle_name_request_update)

    # Test the result
    assert updated_nr_model is not None
Exemplo n.º 3
0
def test_update_request_names(client, jwt, app):
    """
    Setup:
    Test:
    Validate:
    :param client:
    :param jwt:
    :param app:
    :return:
    """
    do_test_cleanup()

    # Initialize the service
    nr_svc = NameRequestService()
    """
    Test updating three names 
    """
    # We will need a base NR
    nr = build_nr(State.DRAFT, {}, [test_names_no_id[0], test_names_no_id[1]])
    # We can't save the NR without an NR Num
    nr.nrNum = 'NR L000001'
    # Save to DB so PK sequences are updated
    nr.save_to_db()
    db.session.flush()

    # NR
    added_names = list(map(lambda n: n.as_dict(), nr.names.all()))
    added_name_0 = pick_name_from_list(added_names,
                                       test_names_no_id[0].get('name'))
    added_name_1 = pick_name_from_list(added_names,
                                       test_names_no_id[1].get('name'))

    # Set data to the service, all we need to test is names so just provide what's necessary
    nr_svc.request_data = {
        'names': [
            # Same as test name 1
            added_name_0,  # Map this over
            added_name_1,  # Map this over
            test_names_no_id[2]
        ]
    }

    # Build the names
    nr = nr_svc.map_request_names(nr)

    nr.save_to_db()

    nr = Request.find_by_nr(nr.nrNum)

    # Convert to dict
    nr = nr.json()

    assert nr is not None
    # Test the names
    assert_names_are_mapped_correctly(nr_svc.request_data.get('names'),
                                      nr.get('names'))

    # Clean up
    do_test_cleanup()
Exemplo n.º 4
0
    def nr_service(self):
        try:
            if not self._nr_service:
                self._nr_service = NameRequestService()
        except Exception as err:
            raise NameRequestException(
                err, message='Error initializing NameRequestService')

        return self._nr_service
Exemplo n.º 5
0
 def put_nr(nr: Request, svc: NameRequestService) -> Request:
     """
     Logic for updating the name request DATA goes inside this handler, which is invoked on successful state change.
     All request data is mapped.
     :param nr: The name request model
     :param svc A NameRequestService instance
     :return:
     """
     map_draft_attrs = nr.stateCd == State.DRAFT
     nr = svc.map_request_data(nr, map_draft_attrs)
     # Map applicants from request_data to the name request
     nr = svc.map_request_applicants(nr)
     # Map any submitted names from request_data to the name request
     nr = svc.map_request_names(nr)
     # Save
     nr = svc.save_request(nr)
     # Return the updated name request
     return nr
Exemplo n.º 6
0
    def nr_service(self):
        try:
            if not self._nr_service:
                self._nr_service = NameRequestService()
                self._nr_service.virtual_wc_service = VirtualWordConditionService()
        except Exception as err:
            raise NameRequestException(err, message='Error initializing NameRequestService')

        return self._nr_service
def test_map_request_data(client, jwt, app):
    """
    Setup:
    Test:
    Validate:
    :param client:
    :param jwt:
    :param app:
    :return:
    """
    nr_svc = NameRequestService()
    # Set data to the service
    input_data = {}
    nr_svc.request_data = input_data

    # Build the NR structure
    nr_model = build_nr(State.DRAFT)
    nr_model.save_to_db()
Exemplo n.º 8
0
    def patch_nr(nr: Request, svc: NameRequestService, nr_action, request_data: dict) -> Request:
        """
        Logic for updating the name request DATA goes inside this handler, which is invoked on successful state change.
        Re-map the names and the applicants (just the applicant / contact if applicable).
        :param nr: The name request model
        :param svc A NameRequestService instance
        :param nr_action: The Name Request action
        :param request_data: A request data object
        :return:
        """
        lock_actions = [NameRequestPatchActions.CHECKIN.value, NameRequestPatchActions.CHECKOUT.value]

        if nr_action in lock_actions and nr.stateCd in [State.DRAFT, State.INPROGRESS]:
            # Map the checkout data
            nr.checkedOutBy = request_data.get('checkedOutBy', None)
            nr.checkedOutDt = request_data.get('checkedOutDt', None)

            nr = svc.save_request(nr)
            # Return the updated name request
            return nr

        if nr.stateCd in request_editable_states:
            # Map data from request_data to the name request
            map_draft_attrs = nr.stateCd == State.DRAFT
            nr = svc.map_request_data(nr, map_draft_attrs)

            # Map any submitted names from request_data to the name request
            nr = svc.map_request_names(nr)

        if nr.stateCd in contact_editable_states:
            # Map applicants from request_data to the name request
            nr = svc.map_request_applicants(nr)

        # Save
        nr = svc.save_request(nr)
        # Return the updated name request
        return nr
Exemplo n.º 9
0
 def post_nr(nr: Request, svc: NameRequestService) -> Request:
     """
     All logic for creating the name request goes inside this handler, which is invoked on successful state change.
     By default just call the inherited post_nr method.
     :param nr: The name request model
     :param svc A NameRequestService instance
     """
     # Map the request data and save so we have a name request ID to use for collection ops
     nr = svc.map_request_data(nr, True)  # Set map_draft_attrs to True
     nr = svc.save_request(nr)
     # Map applicants from the request data to the name request
     nr = svc.map_request_applicants(nr)
     # Map any submitted names from the request data to the name request
     nr = svc.map_request_names(nr)
     # Update the submit count to 1
     nr = svc.update_request_submit_count(nr)
     # Save
     nr = svc.save_request(nr)
     # Return the updated name request
     return nr
Exemplo n.º 10
0
"""Tests for AbstractNameRequestMixin."""
import datetime

import pytest
from dateutil.tz import gettz

from namex.services.name_request import NameRequestService
from namex.models import State, Request as RequestDAO
from namex.constants import RequestAction

nr_svc = NameRequestService()
pacific_tz = gettz('US/Pacific')
utc_tz = gettz('UTC')

@pytest.mark.parametrize('input_datetime_utc,expected_date_utc,time_offset', [
    (datetime.datetime(2021, 1, 28, 8, 0, 0, tzinfo=utc_tz), datetime.datetime(2021, 3, 26, 6, 59, 0, tzinfo=utc_tz), '-0700'),
    (datetime.datetime(2021, 1, 28, 7, 59, 59, tzinfo=utc_tz), datetime.datetime(2021, 3, 25, 6, 59, 0, tzinfo=utc_tz), '-0700'),

    (datetime.datetime(2021, 2, 28, 8, 0, 0, tzinfo=utc_tz), datetime.datetime(2021, 4, 26, 6, 59, 0, tzinfo=utc_tz), '-0700'),
    (datetime.datetime(2021, 2, 28, 7, 59, 59, tzinfo=utc_tz), datetime.datetime(2021, 4, 25, 6, 59, 0, tzinfo=utc_tz), '-0700'),

    (datetime.datetime(2021, 3, 28, 7, 0, 0, tzinfo=utc_tz), datetime.datetime(2021, 5, 24, 6, 59, 0, tzinfo=utc_tz), '-0700'),
    (datetime.datetime(2021, 3, 28, 6, 59, 59, tzinfo=utc_tz), datetime.datetime(2021, 5, 23, 6, 59, 0, tzinfo=utc_tz), '-0700'),

    (datetime.datetime(2021, 4, 28, 7, 0, 0, tzinfo=utc_tz), datetime.datetime(2021, 6, 24, 6, 59, 0, tzinfo=utc_tz), '-0700'),
    (datetime.datetime(2021, 4, 28, 6, 59, 59, tzinfo=utc_tz), datetime.datetime(2021, 6, 23, 6, 59, 0, tzinfo=utc_tz), '-0700'),

    (datetime.datetime(2021, 5, 28, 7, 0, 0, tzinfo=utc_tz), datetime.datetime(2021, 7, 24, 6, 59, 0, tzinfo=utc_tz), '-0700'),
    (datetime.datetime(2021, 5, 28, 6, 59, 59, tzinfo=utc_tz), datetime.datetime(2021, 7, 23, 6, 59, 0, tzinfo=utc_tz), '-0700'),

    (datetime.datetime(2021, 6, 28, 7, 0, 0, tzinfo=utc_tz), datetime.datetime(2021, 8, 24, 6, 59, 0, tzinfo=utc_tz), '-0700'),
Exemplo n.º 11
0
def nro_data_pump_update(nr, ora_cursor, expires_days=56):
    nr_service = NameRequestService()
    expiry_date = nr_service.create_expiry_date(start=nr.lastUpdate,
                                                expires_in_days=expires_days)

    current_app.logger.debug(f'Setting expiry date to: { expiry_date }')
    # init dict for examiner comment data, populated below in loop through names
    examiner_comment = {
        'choice': 0,
        'comment': None,
    }

    # initialize array of derived values to use in the stored proc
    nro_names = [{
        'state': None,
        'decision': None,
        'conflict1': None,
        'conflict2': None,
        'conflict3': None
    }, {
        'state': None,
        'decision': None,
        'conflict1': None,
        'conflict2': None,
        'conflict3': None
    }, {
        'state': None,
        'decision': None,
        'conflict1': None,
        'conflict2': None,
        'conflict3': None
    }]
    current_app.logger.debug('processing names for :{}'.format(nr.nrNum))
    for name in nr.names.all():
        choice = name.choice - 1
        if name.state in [Name.APPROVED, Name.CONDITION]:
            nro_names[choice]['state'] = 'A'
        elif name.state == Name.REJECTED:
            nro_names[choice]['state'] = 'R'
        else:
            nro_names[choice]['state'] = 'NE'

        # some defensive coding here to handle approve/reject/condition where no decision text is available
        # TODO determine if there a business rule requiring APPROVE|REJECTED|CONDITION to have a decision?
        if name.state in [Name.APPROVED, Name.CONDITION, Name.REJECTED]:
            nro_names[choice]['decision'] = '{}****{}'.format(
                nro_names[choice]['state'], '  ' if
                (name.decision_text
                 in [None, '']) else name.decision_text[:1000].encode(
                     "ascii", "ignore").decode('ascii'))

        if name.conflict1:
            nro_names[choice]['conflict1'] = '{}****{}'.format(
                _clear_NR_num_from_conflict(name.conflict1_num[:10]),
                name.conflict1[:150])
        if name.conflict2:
            nro_names[choice]['conflict2'] = '{}****{}'.format(
                _clear_NR_num_from_conflict(name.conflict2_num[:10]),
                name.conflict2[:150])
        if name.conflict3:
            nro_names[choice]['conflict3'] = '{}****{}'.format(
                _clear_NR_num_from_conflict(name.conflict3_num[:10]),
                name.conflict3[:150])

        if name.comment:
            # use the last name comment as the examiner comment, whether that was a rejection or approval
            if name.choice > examiner_comment['choice']:
                examiner_comment['choice'] = name.choice
                examiner_comment['comment'] = name.comment.comment.encode(
                    "ascii", "ignore").decode('ascii')

    status = 'A' if (nr.stateCd in [State.APPROVED, State.CONDITIONAL
                                    ]) else 'R'
    consent = 'Y' if (nr.consentFlag == 'Y'
                      or nr.stateCd == State.CONDITIONAL) else 'N'
    current_app.logger.debug('sending {} to NRO'.format(nr.nrNum))
    current_app.logger.debug(
        'nr:{}; stateCd:{}; status: {}; expiry_dt:{}; consent:{}; examiner:{}'.
        format(nr.nrNum, nr.stateCd, status, expiry_date.strftime('%Y%m%d'),
               consent, nro_examiner_name(nr.activeUser.username)))

    # Call the name_examination function to save complete decision data for a single NR
    ret = ora_cursor.callfunc(
        "NRO_DATAPUMP_PKG.name_examination_func",
        str,
        [
            nr.nrNum,  # p_nr_number
            status,  # p_status
            expiry_date.strftime('%Y%m%d'),  # p_expiry_date
            consent,  # p_consent_flag
            nro_examiner_name(nr.activeUser.username),  # p_examiner_id
            nro_names[0]['decision'],  # p_choice1
            nro_names[1]['decision'],  # p_choice2
            nro_names[2]['decision'],  # p_choice3
            examiner_comment['comment'],  # p_exam_comment
            '',  # p_add_info - not used in func anymore
            nro_names[0]['conflict1'],  # p_confname1A
            nro_names[0]['conflict2'],  # p_confname1B
            nro_names[0]['conflict3'],  # p_confname1C
            nro_names[1]['conflict1'],  # p_confname2A
            nro_names[1]['conflict2'],  # p_confname2B
            nro_names[1]['conflict3'],  # p_confname2C
            nro_names[2]['conflict1'],  # p_confname3A
            nro_names[2]['conflict2'],  # p_confname3B
            nro_names[2]['conflict3'],  # p_confname3C
        ])
    if ret is not None:
        current_app.logger.error(
            'name_examination_func failed, return message: {}'.format(ret))

    current_app.logger.debug('finished sending {} to NRO'.format(nr.nrNum))
    # mark that we've set the record in NRO - which assumes we have legally furnished this to the client.
    # and record the expiry date we sent to NRO
    nr.furnished = 'Y'
    nr.expirationDate = expiry_date
Exemplo n.º 12
0
    # leaving this debug statement here as there were some translation and image caching issues
    # that are easier to see from the raw SQL in the log
    #
    current_app.logger.debug(
        str(
            q.statement.compile(dialect=postgresql.dialect(),
                                compile_kwargs={"literal_binds": True})))

    for r in q.all():
        row_count += 1

        current_app.logger.debug('processing: {}'.format(r.nrNum))

        try:
            nr_service = NameRequestService()
            expiry_days = int(nr_service.get_expiry_days(r))
            nro_data_pump_update(r, ora_cursor, expiry_days)
            db.session.add(r)
            EventRecorder.record(user,
                                 Event.NRO_UPDATE,
                                 r,
                                 r.json(),
                                 save_to_session=True)

            ora_con.commit()
            db.session.commit()
            JobTracker.job_detail(db, job_id, r.nrNum)

        except Exception as err:
            current_app.logger.error(err)
Exemplo n.º 13
0
def test_create_expiry_date(test_name, start_date, days, tz, expected_date):
    nr_service = NameRequestService()
    ced = nr_service.create_expiry_date(start_date, expires_in_days=days)

    assert ced.replace(tzinfo=None) == expected_date
    assert ced.tzinfo.zone == tz