コード例 #1
0
def add_nr_header(new_nr, nr_header, nr_submitter, user):

    NR_STATE = {
        'HISTORICAL': 'HISTORICAL',
        'H': 'HOLD',
        'COMPLETED': 'COMPLETED',
        'D': 'DRAFT',
        'C': 'CANCELLED',
        'E': 'CONDITIONAL'
    }

    if nr_submitter:
        submitter = User.find_by_username(nr_submitter['submitter'])

    new_nr.userId = user.id
    new_nr.stateCd = State.DRAFT if nr_header[
        'state_type_cd'] is None else NR_STATE[nr_header['state_type_cd']]
    new_nr.nrNum = nr_header['nr_num']
    new_nr.requestId = nr_header['request_id']
    new_nr.previousRequestId = nr_header['previous_request_id']
    new_nr.submitCount = nr_header['submit_count']
    new_nr.requestTypeCd = nr_header['request_type_cd']
    new_nr.expirationDate = nr_header['expiration_date']
    new_nr.additionalInfo = nr_header['additional_info']
    new_nr.natureBusinessInfo = nr_header['nature_business_info']
    new_nr.xproJurisdiction = nr_header['xpro_jurisdiction']
    new_nr.submittedDate = nr_submitter['submitted_date']
    new_nr.submitter_userid = None if (submitter is None) else submitter.id
    new_nr.nroLastUpdate = nr_header['last_update']
    if nr_header['priority_cd'] is 'PQ':
        new_nr.priorityCd = 'Y'
    else:
        new_nr.priorityCd = 'N'
コード例 #2
0
ファイル: name_request.py プロジェクト: LJTrent/namex
            def initialize(_self):
                _self.validate_config(current_app)
                request_json = request.get_json()

                if nr_action:
                    _self.nr_action = nr_action

                if nr_action is NameRequestPatchActions.CHECKOUT.value:
                    # Make sure the NR isn't already checked out
                    checked_out_by_different_user = nr_model.checkedOutBy is not None and nr_model.checkedOutBy != request_json.get('checkedOutBy', None)
                    if checked_out_by_different_user:
                        raise NameRequestIsInProgressError()

                    # set the user id of the request to name_request_service_account
                    service_account_user = User.find_by_username('name_request_service_account')
                    nr_model.userId = service_account_user.id

                    # The request payload will be empty when making this call, add them to the request
                    _self.request_data = {
                        # Doesn't have to be a UUID but this is easy and works for a pretty unique token
                        'checkedOutBy': str(uuid4()),
                        'checkedOutDt': datetime.now()
                    }
                    # Set the request data to the service
                    _self.nr_service.request_data = self.request_data
                elif nr_action is NameRequestPatchActions.CHECKIN.value:
                    # The request payload will be empty when making this call, add them to the request
                    _self.request_data = {
                        'checkedOutBy': None,
                        'checkedOutDt': None
                    }
                    # Set the request data to the service
                    _self.nr_service.request_data = self.request_data
                else:
                    super().initialize()
コード例 #3
0
def add_nr_header(nr, nr_header, nr_submitter, user):

    NR_STATE = {
        'HISTORICAL': 'HISTORICAL',
        'H': 'HOLD',
        'COMPLETED': 'COMPLETED',
        'D': 'DRAFT',
        'C': 'CANCELLED',
        'E': 'EXPIRED'
    }

    if nr_submitter:
        submitter = User.find_by_username(nr_submitter['submitter'])
    else:
        submitter = None

    previous_priorityCd = nr.priorityCd

    nr.userId = user.id
    nr.stateCd = State.DRAFT if nr_header[
        'state_type_cd'] is None else NR_STATE[nr_header['state_type_cd']]
    nr.nrNum = nr_header['nr_num']
    nr.requestId = nr_header['request_id']
    nr.previousRequestId = nr_header['previous_request_id']
    nr.submitCount = nr_header['submit_count']
    nr.requestTypeCd = nr_header['request_type_cd']
    nr.expirationDate = nr_header['expiration_date']
    nr.additionalInfo = nr_header['additional_info']
    nr.natureBusinessInfo = nr_header['nature_business_info']
    nr.xproJurisdiction = nr_header['xpro_jurisdiction']
    nr.homeJurisNum = nr_header['home_juris_num']
    # TODO This should NOT be None, but due to some legacy issues, it's set to None
    nr.submittedDate = None if not nr_submitter else nr_submitter[
        'submitted_date']
    nr.submitter_userid = None if not submitter else submitter.id
    nr.nroLastUpdate = nr_header['last_update']
    nr.lastUpdate = nr.nroLastUpdate  # this needs to be set to the same Point In Time as NRO until NameX owns it
    nr._source = 'NRO'

    if nr_header['priority_cd'] in ('PQ', 'PJ', 'RJ'):
        nr.priorityCd = 'Y'
        if previous_priorityCd == 'N':
            nr.priorityDate = datetime.datetime.utcnow()
        else:
            nr.priorityDate = nr.submittedDate
    else:
        nr.priorityCd = 'N'

    # if this was a change of name with related corp num, populate the corpNum field
    # - the string in Additional Info field is form: **Change of Name** **XXXXXXXXXXXXXX**
    try:
        if '**Change of Name**' in nr.additionalInfo:
            regex = r"\*\*Change of Name\*\* \*\*([a-zA-Z0-9]*)\*\*"
            m = re.search(regex, nr.additionalInfo)
            if m:
                nr.corpNum = m.group(1)
    except:
        pass
コード例 #4
0
    def create_or_update(cls, word_classification):
        entity = cls.find_one_by_class(
            word_classification['word'],
            word_classification['classification']) or None

        # user = get_or_create_user_by_jwt(g.jwt_oidc_token_info)
        user = User.find_by_username(word_classification['examiner'])

        if not entity:
            return cls.create(word_classification, user.id)
        else:
            return cls.update(entity, word_classification, user.id)
コード例 #5
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
コード例 #6
0
# #### Send the NameX Request info to NRO
# #########################################

# this allows me to use the NameX ORM Model, and use the db scoped session attached to the models.
app = create_app(Config)
delay, max_rows, expires_days = get_ops_params()

start_time = datetime.utcnow()
row_count = 0

try:
    job_id = JobTracker.start_job(db, start_time)

    # get the service account user to save BRO Requests
    user = User.find_by_username(current_app.config['NRO_SERVICE_ACCOUNT'])

    ora_con = cx_Oracle.connect(Config.ORA_USER,
                                Config.ORA_PASSWORD,
                                "{0}:{1}/{2}".format(Config.ORA_HOST, Config.ORA_PORT, Config.ORA_NAME))
    ora_con.begin()
    ora_cursor = ora_con.cursor()

    # A more generic way of setting time
    # but it doens't print / log well from the Postgres Dialect
    # so just leaving it here for future reference
    # q = q.filter(Request.lastUpdate < datetime.utcnow()-timedelta(seconds=delay)). \
    #

    q = db.session.query(Request).\
                filter(Request.stateCd.in_([State.APPROVED, State.REJECTED, State.CONDITIONAL])).\
コード例 #7
0
ファイル: name_requests.py プロジェクト: rarmitag/namex
    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
コード例 #8
0
async def process_payment(pay_msg: dict, flask_app: Flask):
    """Render the payment status."""
    if not flask_app or not pay_msg:
        raise QueueException('Flask App or token not available.')

    with flask_app.app_context():
        logger.debug('entering process payment: %s', pay_msg)

        # capture_message(f'Queue Issue: Unable to find payment.id={payment_id} to place on email queue')
        # return

        if pay_msg.get(
                'paymentToken',
            {}).get('statusCode') == PaymentState.TRANSACTION_FAILED.value:
            # TODO: The customer has cancelled out of paying, so we could note this better
            # technically the payment for this service is still pending
            logger.debug('Failed transaction on queue:%s', pay_msg)
            return

        complete_payment_status = [
            PaymentState.COMPLETED.value, PaymentState.APPROVED.value
        ]
        if pay_msg.get('paymentToken',
                       {}).get('statusCode') in complete_payment_status:  # pylint: disable=R1702
            logger.debug('COMPLETED transaction on queue: %s', pay_msg)

            if payment_token := pay_msg.get('paymentToken', {}).get('id'):
                if payment := Payment.find_by_payment_token(payment_token):

                    if update_payment := await update_payment_record(payment):
                        payment = update_payment
                        # record event
                        nr = RequestDAO.find_by_id(payment.nrId)
                        # TODO: create a namex_pay user for this
                        user = User.find_by_username(
                            'name_request_service_account')
                        EventRecorder.record(
                            user, Event.NAMEX_PAY +
                            f' [payment completed] { payment.payment_action }',
                            nr, nr.json())
                        # try to update NRO otherwise send a sentry msg for OPS
                        if payment.payment_action in \
                                [payment.PaymentActions.UPGRADE.value, payment.PaymentActions.REAPPLY.value]:
                            change_flags = {
                                'is_changed__request': True,
                                'is_changed__previous_request': False,
                                'is_changed__applicant': False,
                                'is_changed__address': False,
                                'is_changed__name1': False,
                                'is_changed__name2': False,
                                'is_changed__name3': False,
                                'is_changed__nwpta_ab': False,
                                'is_changed__nwpta_sk': False,
                                'is_changed__request_state': False,
                                'is_changed_consent': False
                            }
                            warnings = nro.change_nr(nr, change_flags)
                            if warnings:
                                logger.error(
                                    'Queue Error: Unable to update NRO :%s',
                                    warnings)
                                capture_message(
                                    f'Queue Error: Unable to update NRO for {nr} {payment.payment_action} :{warnings}',
                                    level='error')

                    await furnish_receipt_message(qsm, payment)

                else: