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
def furnish_request_message(request: Request, option: str): # pylint: disable=redefined-outer-name """Send notification info to the mail queue.""" current_app.logger.debug( 'Start of the furnishing of request for %s nrNum=%s', option, request.nrNum) payload = create_cloud_event_msg( msg_id=str(uuid.uuid4()), msg_type='bc.registry.names.request', source=f'/requests/{request.nrNum}', time=datetime.utcfromtimestamp( time.time()).replace(tzinfo=timezone.utc).isoformat(), identifier=request.nrNum, json_data_body={'request': { 'nrNum': request.nrNum, 'option': option }}) current_app.logger.debug('About to publish email for %s nrNum=%s', option, request.nrNum) publish_email_message(payload) if option == 'before-expiry': request.notifiedBeforeExpiry = True elif option == 'expired': request.notifiedExpiry = True request.stateCd = State.EXPIRED request.save_to_db()
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
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
def save_auto_approved_names(approved_number_records): from namex.models import Event as EventDAO, Request as RequestDAO, User as UserDAO, State num = 0 global num_records username = '******' usr = UserDAO(username, '', '', '', '') usr.id = 86 usr.save_to_db() while approved_number_records > num: nr_num_label = 'NR 00' num_records += 1 num += 1 nr_num = nr_num_label + str(num_records) nr = RequestDAO() nr.nrNum = nr_num nr.stateCd = State.APPROVED nr._source = 'NAMEREQUEST' event = EventDAO() event.action = EventAction.PUT.value event.userId = EventUserId.SERVICE_ACCOUNT.value event.stateCd = State.APPROVED event.eventDate = datetime.date.today() nr.events = [event] nr.save_to_db()
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()
def complete_reapply_payment(self, nr_model: RequestDAO, payment_id: int): """ Invoked when re-applying for an existing Name Request reservation. Extend the Name Request's expiration date by 56 days. If the request action is set to REH or REST, extend the expiration by an additional year (plus the default 56 days). :param nr_model: :param payment_id: :return: """ nr_svc = self.nr_service # Update the state of the payment payment = get_active_payment(nr_model, payment_id) sbc_payment_response = get_payment(payment.payment_token) # TODO: Throw errors if this fails! if sbc_payment_response.statusCode in [ PaymentStatusCode.COMPLETED.value, PaymentStatusCode.APPROVED.value ]: payment.payment_status_code = sbc_payment_response.statusCode payment.payment_completion_date = sbc_payment_response.createdOn payment.save_to_db() if nr_model.submitCount < 3: if nr_model.request_action_cd in [ RequestAction.REH.value, RequestAction.REN.value ]: # If request action is REH or REST extend by 1 year (+ 56 default) days, starting tomorrow nr_model = nr_svc.extend_expiry_date(nr_model, datetime.utcnow(), days=421) nr_model = nr_svc.update_request_submit_count(nr_model) else: # Extend expiry date by (default) 56 days, starting tomorrow nr_model = nr_svc.extend_expiry_date(nr_model, datetime.utcnow(), days=56) nr_model = nr_svc.update_request_submit_count(nr_model) nr_model.save_to_db() else: # TODO: Make a custom exception for this? raise PaymentServiceError( message= 'Submit count maximum of 3 retries has been reached!') # This (optionally) handles the updates for NRO and Solr, if necessary update_solr = False nr_model = self.update_records_in_network_services( nr_model, update_solr) # Update the actions, as things change once the payment is successful self.nr_service.current_state_actions = get_nr_state_actions( nr_model.stateCd, nr_model) # Record the event # EventRecorder.record(nr_svc.user, Event.PATCH + ' [re-apply]', nr_model, nr_svc.request_data) return nr_model
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|'
def test_get_queued_oldest_multirow(client, app): # add NR to database from namex.models import Request as RequestDAO, State, User nr_first = RequestDAO() nr_first.nrNum = 'NR 0000001' nr_first.stateCd = State.DRAFT nr_first.save_to_db() for i in range(2, 12): nr = RequestDAO() nr.nrNum = 'NR {0:07d}'.format(i) nr.stateCd = State.DRAFT nr.save_to_db() user = User(username='******', firstname='first', lastname='last', sub='idir/funcmunk', iss='keycloak') user.save_to_db() nr_oldest, new_req = RequestDAO.get_queued_oldest(user) # Tests #### assert nr_first.nrNum == nr_oldest.nrNum assert nr_oldest.json()
def create_nr(nr_num: str, request_state: str, names: list, names_state: list): now = datetime.utcnow() with freeze_time(now): name_request = Request() name_request.nrNum = nr_num name_request.stateCd = request_state name_request._source = 'NRO' name_request.expirationDate = add_years(now, 1) name_request.entity_type_cd = 'CR' # name_request.priorityCd = start_priority name_request.save_to_db() for index, name in enumerate(names): name_state = names_state[index] choice = index + 1 name_obj = Name() name_obj.nrId = name_request.id name_obj.name = name name_obj.state = name_state name_obj.choice = choice name_obj.name_type_cd = 'CO' name_obj.save_to_db() return name_request
def test_full_access_to_name_request(test_name, \ name_request_number, temp_request_number, user_email, user_phone, \ header_name_request_number, header_temp_request_number, header_user_email, header_user_phone, \ expected): """Assure that this contains the headers required to fully access an NR.""" from namex.utils.auth import full_access_to_name_request # setup nr = RequestDAO() nr.nrNum = name_request_number or temp_request_number nr.stateCd = State.DRAFT nr._source = ValidSources.NAMEREQUEST.value applicant = Applicant() applicant.phoneNumber = user_phone applicant.emailAddress = user_email nr.applicants.append(applicant) nr.save_to_db() builder = EnvironBuilder(method='POST', data={}, headers={ 'BCREG_NR': header_name_request_number, 'BCREG_NRL': header_temp_request_number, 'BCREG-User-Email': header_user_email, 'BCREG-User-Phone': header_user_phone }) env = builder.get_environ() req = Request(env) print(req) assert expected == full_access_to_name_request(req)
def test_get_next_oldest(client, jwt, app): # add NR to database from namex.models import Request as RequestDAO, State nr = RequestDAO() nr.nrNum = 'NR 0000001' nr.stateCd = State.DRAFT nr._source = 'NRO' nr.save_to_db() for i in range(2, 12): nr = RequestDAO() nr.nrNum = 'NR {0:07d}'.format(i) nr.stateCd = State.DRAFT nr._source = 'NRO' 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} # The message expected to be returned json_msg = jsonify(nameRequest='NR 0000001') # get the resource (this is the test) rv = client.get('/api/v1/requests/queues/@me/oldest', headers=headers) assert b'"nameRequest": "NR 0000001"' in rv.data
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":'
def complete_reservation_payment(self, nr_model: RequestDAO, payment_id: int): """ Invoked when completing an in-progress Name Request reservation. :param nr_model: :param payment_id: :return: """ nr_svc = self.nr_service # Update the state of the payment payment = get_active_payment(nr_model, payment_id) sbc_payment_response = get_payment(payment.payment_token) # TODO: Throw errors if this fails! if sbc_payment_response.statusCode in [ PaymentStatusCode.COMPLETED.value, PaymentStatusCode.APPROVED.value ]: payment.payment_status_code = sbc_payment_response.statusCode payment.payment_completion_date = sbc_payment_response.createdOn payment.save_to_db() # This handles updates if the NR state is DRAFT, COND_RESERVE or RESERVED # If the state is COND_RESERVE update state to CONDITIONAL # If the state is RESERVED update state to APPROVED # Then update the name request as required if nr_model.stateCd == State.DRAFT: # If the state is DRAFT, leave it as a DRAFT nr_model = self.update_nr(nr_model, State.DRAFT, self.handle_nr_approve) if nr_model.stateCd == State.COND_RESERVE: # If the state is COND_RESERVE update state to CONDITIONAL, and update the name request as required nr_model = self.update_nr(nr_model, State.CONDITIONAL, self.handle_nr_approve) elif nr_model.stateCd == State.RESERVED: # If the state is RESERVED update state to APPROVED, and update the name request as required nr_model = self.update_nr(nr_model, State.APPROVED, self.handle_nr_approve) # Save the name request nr_model.save_to_db() # Record the event EventRecorder.record(nr_svc.user, Event.PATCH + ' [payment completed] RESERVE', nr_model, nr_model.json()) # Update the actions, as things change once the payment is successful self.nr_service.current_state_actions = get_nr_state_actions( nr_model.stateCd, nr_model) return nr_model
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
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
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()
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
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
def complete_upgrade_payment(self, nr_model: RequestDAO, payment_id: int): """ Invoked when upgrading an existing Name Request reservation to PRIORITY status. :param nr_model: :param payment_id: :return: """ nr_svc = self.nr_service if nr_model.stateCd not in [State.DRAFT, State.PENDING_PAYMENT]: raise PaymentServiceError( message= 'Error upgrading Name Request, request is in an invalid state!' ) # Update the state of the payment payment = get_active_payment(nr_model, payment_id) sbc_payment_response = get_payment(payment.payment_token) # TODO: Throw errors if this fails! if sbc_payment_response.statusCode in [ PaymentStatusCode.COMPLETED.value, PaymentStatusCode.APPROVED.value ]: payment.payment_status_code = sbc_payment_response.statusCode payment.payment_completion_date = sbc_payment_response.createdOn payment.save_to_db() nr_model.priorityCd = 'Y' nr_model.priorityDate = datetime.utcnow() # Save the name request nr_model.save_to_db() # This (optionally) handles the updates for NRO and Solr, if necessary update_solr = False nr_model = self.update_records_in_network_services( nr_model, update_solr) # Update the actions, as things change once the payment is successful self.nr_service.current_state_actions = get_nr_state_actions( nr_model.stateCd, nr_model) # Record the event EventRecorder.record(nr_svc.user, Event.PATCH + ' [payment completed] UPGRADE', nr_model, nr_model.json()) return nr_model
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
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
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
def save_name(submitted_date, nr_num, priority=False): from namex.models import Request as RequestDAO, State num = 0 global num_records nr_num_label = 'NR ' nr_num = nr_num_label + str(nr_num) nr = RequestDAO() nr.nrNum = nr_num nr.stateCd = State.DRAFT nr.priorityCd = 'Y' if priority else 'N' nr._source = 'NAMEREQUEST' nr.submittedDate = submitted_date nr.save_to_db()
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()
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
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
def test_get_queued_oldest(client, app): # SETUP ##### # add NR to database from namex.models import Request as RequestDAO, State, User nr = RequestDAO() nr.nrNum='NR 0000001' nr.stateCd = State.DRAFT nr.save_to_db() user = User(username='******', firstname='first', lastname='last', sub='idir/funcmunk', iss='keycloak') user.save_to_db() nr_oldest, new_req = RequestDAO.get_queued_oldest(user) # Tests #### assert nr.nrNum == nr_oldest.nrNum
def save_names_queue(queue_number_records, priority=False): from namex.models import Request as RequestDAO, State num = 0 global num_records while queue_number_records > num: nr_num_label = 'NR ' num_records += 1 num += 1 nr_num = nr_num_label + str(num_records) nr = RequestDAO() nr.nrNum = nr_num nr.stateCd = State.DRAFT nr.priorityCd = 'Y' if priority else 'N' nr._source = 'NAMEREQUEST' nr.save_to_db()
def test_get_next_no_draft_avail(client, jwt, app): # add NR to database from namex.models import Request as RequestDAO, State nr = RequestDAO() nr.nrNum = 'NR 0000001' nr.stateCd = State.APPROVED 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} # get the resource (this is the test) rv = client.get('/api/v1/requests/queues/@me/oldest', headers=headers) # should return 404, not found assert 404 == rv.status_code