Skip to content

Commit

Permalink
Release skip nro decom: #23050 NR expiry date is not being extended f…
Browse files Browse the repository at this point in the history
…or future effective filings (#1578)

* new release branch and merged ticket 23243 code change

* #23050 NR expiry date is not being extended for future effective filings

* Auth -Search Name Request - Cancelled Name Request should not be selected#19703

Signed-off-by: Chen <[email protected]>

* Auth -Search Name Request - Cancelled Name Request should not be selected#19703

Signed-off-by: Chen <[email protected]>

---------

Signed-off-by: Chen <[email protected]>
Co-authored-by: Chen <[email protected]>
  • Loading branch information
eve-git and stevenc987 authored Oct 1, 2024
1 parent 0cebb83 commit f84e25d
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 62 deletions.
3 changes: 1 addition & 2 deletions api/namex/VERSION.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
__version__ = '1.1.60'

__version__ = '1.1.62'
29 changes: 10 additions & 19 deletions api/namex/resources/mras.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from http import HTTPStatus

import requests, xmltodict
from flask import current_app, jsonify, make_response
from flask import current_app, jsonify, make_response, current_app
from flask_restx import Namespace, Resource, cors
from lxml import etree # Don't worry about this it exists... the module is dynamically loaded

Expand Down Expand Up @@ -56,15 +56,15 @@ class MrasProfile(Resource):
def get(self, province, corp_num):
try:
# Get the jurisdiction
print('Calling MRAS Jurisdictions API using [corp_num: {corp_num}]'.format(corp_num=corp_num))
current_app.logger.debug('Calling MRAS Jurisdictions API using [corp_num: {corp_num}]'.format(corp_num=corp_num))
mras_url = f'{current_app.config.get("MRAS_SVC_URL")}/api/v1/xpr/jurisdictions/{corp_num}'
headers = {
'x-api-key': current_app.config.get('MRAS_SVC_API_KEY'),
'Accept': 'application/xml'
}

print(mras_url)
print(repr(headers))
current_app.logger.debug(mras_url)
current_app.logger.debug(repr(headers))
response = requests.get(
mras_url,
headers=headers
Expand All @@ -86,43 +86,34 @@ def get(self, province, corp_num):
if province not in jurisdiction_ids:
return make_response(jsonify(message='Invalid request, province jurisdiction is incorrect'), HTTPStatus.BAD_REQUEST)
else:
print('Valid jurisdiction IDs')
print(repr(jurisdiction_ids))
current_app.logger.debug('Valid jurisdiction IDs')
current_app.logger.debug(repr(jurisdiction_ids))

# Get the profile
print('\nCalling MRAS Profile API using [corp_num: {corp_num}], [province: {province}]'.format(corp_num=corp_num, province=province))
current_app.logger.debug('\nCalling MRAS Profile API using [corp_num: {corp_num}], [province: {province}]'.format(corp_num=corp_num, province=province))
mras_url = f'{current_app.config.get("MRAS_SVC_URL")}/api/v1/xpr/GetProfile/{corp_num}/{province}'

headers = {
'x-api-key': current_app.config.get('MRAS_SVC_API_KEY'),
'Accept': 'application/xml'
}

print(mras_url)
print(repr(headers))
current_app.logger.debug(mras_url)
current_app.logger.debug(repr(headers))
response = requests.get(
mras_url,
headers=headers
)


# Return the auth response if an error occurs
if not response.status_code == HTTPStatus.OK:
return make_response(jsonify({'error': 'No profile found for the jurisdiction, registration number pair.'}), HTTPStatus.NOT_FOUND)
# mras_errors = load_xml_response_content(response, './/mras_error')
# mras_error = {
# 'error_code': mras_errors[0].find('error_code').text,
# 'internal_error_code': mras_errors[0].find('internal_error_code').text,
# 'internal_error_message': mras_errors[0].find('internal_error_message').text
# }

# raise MrasServiceException(mras_error=mras_error)

# Just return true or false, the profile either exists or it doesn't
# Note: the response content is in xml format so we need to parse it to json format.
dict_data = xmltodict.parse(response.content)
jsonify_data = jsonify(dict_data)
return make_response(jsonify_data), HTTPStatus.OK
return make_response(jsonify_data, HTTPStatus.OK)
except MrasServiceException as err:
return handle_exception(err, err.message, err.error_code)
except Exception as err:
Expand Down
99 changes: 58 additions & 41 deletions api/namex/resources/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from flask import request, jsonify, g, current_app, make_response
from flask_restx import Namespace, Resource, fields, cors
from flask_jwt_oidc import AuthError
from marshmallow import ValidationError

from namex.constants import DATE_TIME_FORMAT_SQL
from namex.models.request import RequestsAuthSearchSchema
Expand Down Expand Up @@ -36,6 +37,7 @@
from namex.analytics import SolrQueries, RestrictedWords, VALID_ANALYSIS as ANALYTICS_VALID_ANALYSIS
from namex.services.nro import NROServicesError
from namex.utils import queue_util
from .utils import DateUtils

import datetime

Expand Down Expand Up @@ -459,7 +461,7 @@ def _get_next_set_from_solr(solr_query, start, rows):
have_more_data = results['response']['numFound'] > (start + rows)
identifiers = [name['nr_num'] for name in results['names']]
return RequestDAO.query.filter(
RequestDAO.nrNum.in_(identifiers),
RequestDAO.nrNum.in_(identifiers), RequestDAO.stateCd != State.CANCELLED,
or_(RequestDAO.stateCd != State.EXPIRED,
text(f"(requests.state_cd = '{State.EXPIRED}' AND CAST(requests.expiration_date AS DATE) + "
"interval '60 day' >= CAST(now() AS DATE))"))
Expand Down Expand Up @@ -747,13 +749,26 @@ def put(nr, *args, **kwargs):
existing_nr.save_to_db()

if json_input.get('consent_dt', None):
json_input['consent_dt'] = str(datetime.datetime.strptime(
str(json_input['consent_dt'][5:]), '%d %b %Y %H:%M:%S %Z'))
consentDateStr = json_input['consent_dt']
json_input['consent_dt'] = DateUtils.parse_date_string(consentDateStr, '%d %b %Y %H:%M:%S %Z')

# convert Submitted Date to correct format
if json_input.get('submittedDate', None):
json_input['submittedDate'] = str(datetime.datetime.strptime(
str(json_input['submittedDate'][5:]), '%d %b %Y %H:%M:%S %Z'))
submittedDateStr = json_input['submittedDate']
json_input['submittedDate'] = DateUtils.parse_date_string(submittedDateStr, '%d %b %Y %H:%M:%S %Z')

# convert Expiration Date to correct format
if json_input.get('expirationDate', None):
try:
expirationDateStr = json_input['expirationDate']
expirationDate = DateUtils.parse_date(expirationDateStr)
# Convert the UTC datetime object to the end of day in pacific time without milliseconds
pacific_time = expirationDate.astimezone(timezone('US/Pacific'))
end_of_day_pacific = pacific_time.replace(hour=23, minute=59, second=0, microsecond=0)
json_input['expirationDate'] = end_of_day_pacific.strftime('%Y-%m-%d %H:%M:%S%z')
except Exception as e:
current_app.logger.debug(f"Error parsing expirationDate: {str(e)}")
pass

# convert NWPTA dates to correct format
if json_input.get('nwpta', None):
Expand All @@ -762,8 +777,8 @@ def put(nr, *args, **kwargs):
if region['partnerNameDate'] == '':
region['partnerNameDate'] = None
if region['partnerNameDate']:
region['partnerNameDate'] = str(datetime.datetime.strptime(
str(region['partnerNameDate']), '%d-%m-%Y'))
partnerNameDateStr = region['partnerNameDate']
region['partnerNameDate'] = DateUtils.parse_date_string(partnerNameDateStr, '%d-%m-%Y')
except ValueError:
pass
# pass on this error and catch it when trying to add to record, to be returned
Expand Down Expand Up @@ -817,7 +832,8 @@ def put(nr, *args, **kwargs):

try:
previousNr = json_input['previousNr']
nrd.previousRequestId = RequestDAO.find_by_nr(previousNr).requestId
if previousNr:
nrd.previousRequestId = RequestDAO.find_by_nr(previousNr).requestId
except AttributeError:
nrd.previousRequestId = None
except KeyError:
Expand Down Expand Up @@ -1080,39 +1096,40 @@ def put(nr, *args, **kwargs):
is_changed__nwpta_ab = False
is_changed__nwpta_sk = False

for nrd_nwpta in nrd.partnerNS.all():

orig_nwpta = nrd_nwpta.as_dict()

for in_nwpta in json_input['nwpta']:
if nrd_nwpta.partnerJurisdictionTypeCd == in_nwpta['partnerJurisdictionTypeCd']:

errors = nwpta_schema.validate(in_nwpta, partial=False)
if errors:
MessageServices.add_message(MessageServices.ERROR, 'nwpta_validation', errors)
# return make_response(jsonify(errors), 400

nwpta_schema.load(in_nwpta, instance=nrd_nwpta, partial=False)

# convert data to ascii, removing data that won't save to Oracle
nrd_nwpta.partnerName = convert_to_ascii(in_nwpta.get('partnerName'))
nrd_nwpta.partnerNameNumber = convert_to_ascii(in_nwpta.get('partnerNameNumber'))

# check if any of the Oracle db fields have changed, so we can send them back
tmp_is_changed = False
if nrd_nwpta.partnerNameTypeCd != orig_nwpta['partnerNameTypeCd']:
tmp_is_changed = True
if nrd_nwpta.partnerNameNumber != orig_nwpta['partnerNameNumber']:
tmp_is_changed = True
if nrd_nwpta.partnerNameDate != orig_nwpta['partnerNameDate']:
tmp_is_changed = True
if nrd_nwpta.partnerName != orig_nwpta['partnerName']:
tmp_is_changed = True
if tmp_is_changed:
if nrd_nwpta.partnerJurisdictionTypeCd == 'AB':
is_changed__nwpta_ab = True
if nrd_nwpta.partnerJurisdictionTypeCd == 'SK':
is_changed__nwpta_sk = True
if nrd.partnerNS.count() > 0:
for nrd_nwpta in nrd.partnerNS.all():

orig_nwpta = nrd_nwpta.as_dict()

for in_nwpta in json_input['nwpta']:
if nrd_nwpta.partnerJurisdictionTypeCd == in_nwpta['partnerJurisdictionTypeCd']:

errors = nwpta_schema.validate(in_nwpta, partial=False)
if errors:
MessageServices.add_message(MessageServices.ERROR, 'nwpta_validation', errors)
# return make_response(jsonify(errors), 400

nwpta_schema.load(in_nwpta, instance=nrd_nwpta, partial=False)

# convert data to ascii, removing data that won't save to Oracle
nrd_nwpta.partnerName = convert_to_ascii(in_nwpta.get('partnerName'))
nrd_nwpta.partnerNameNumber = convert_to_ascii(in_nwpta.get('partnerNameNumber'))

# check if any of the Oracle db fields have changed, so we can send them back
tmp_is_changed = False
if nrd_nwpta.partnerNameTypeCd != orig_nwpta['partnerNameTypeCd']:
tmp_is_changed = True
if nrd_nwpta.partnerNameNumber != orig_nwpta['partnerNameNumber']:
tmp_is_changed = True
if nrd_nwpta.partnerNameDate != orig_nwpta['partnerNameDate']:
tmp_is_changed = True
if nrd_nwpta.partnerName != orig_nwpta['partnerName']:
tmp_is_changed = True
if tmp_is_changed:
if nrd_nwpta.partnerJurisdictionTypeCd == 'AB':
is_changed__nwpta_ab = True
if nrd_nwpta.partnerJurisdictionTypeCd == 'SK':
is_changed__nwpta_sk = True

### END nwpta ###

Expand Down
13 changes: 13 additions & 0 deletions api/namex/resources/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from dateutil import parser


class DateUtils:

@staticmethod
def parse_date(date_str):
return parser.parse(date_str)

@staticmethod
def parse_date_string(date_str, output_date_format):
parsed_date = parser.parse(date_str)
return parsed_date.strftime(output_date_format)

0 comments on commit f84e25d

Please sign in to comment.