def cancel_registration():
    if request.headers['Content-Type'] != "application/json":
        logging.error('Content-Type is not JSON')
        return Response(status=415)

    suppress = False
    if 'suppress_queue' in request.args:
        logging.info(format_message('Queue suppressed'))
        suppress = True
    json_data = json.loads(request.data.decode('utf-8'))

    if 'dev_date' in request.args and app.config['ALLOW_DEV_ROUTES']:
        logging.warning(format_message('Overriding date'))
        json_data['dev_registration'] = {'date': request.args['dev_date']}

    logging.debug("Received: %s", json_data)
    reg = json_data['registration']
    logging.debug("Reg: %s", reg)
    rows, nos, canc_request_id = insert_cancellation(json_data, get_username())
    if rows == 0:
        return Response(status=404)
    else:
        data = {"cancellations": nos, "request_id": canc_request_id}
        if not suppress:
            publish_cancellation(producer, nos)
        return Response(json.dumps(data),
                        status=200,
                        mimetype='application/json')
def registration(date, reg_no):
    if "class_of_charge" in request.args:
        class_of_charge = request.args["class_of_charge"]
    else:
        class_of_charge = None
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        logging.audit(format_message("Retrieve entry details for %s, %s"),
                      reg_no, date)

        details = get_registration_details(cursor, reg_no, date,
                                           class_of_charge)
        if details is not None:
            addl_info = get_additional_info(cursor, details)

            if addl_info is not None:
                details['additional_information'] = addl_info
    finally:
        complete(cursor)
    if details is None:
        logging.warning(
            format_message("Returning 404 for /registrations/{}/{}".format(
                date, reg_no)))
        return Response(status=404)
    else:
        return Response(json.dumps(details),
                        status=200,
                        mimetype='application/json')
def reprints(reprint_type):
    request_id = ''
    if reprint_type == 'registration':
        registration_no = request.args['registration_no']
        registration_date = request.args['registration_date']
        url = app.config['LAND_CHARGES_URI'] + '/request_details?reprint_type=' + reprint_type
        url += '&registration_no=' + registration_no + '&registration_date=' + registration_date
        response = requests.get(url, headers=get_headers())
        data = json.loads(response.content.decode('utf-8'))
        if "request_id" not in data:
            return "invalid request_id for " + registration_no + ' ' + registration_date
        request_id = data['request_id']
    elif reprint_type == 'search':
        request_id = request.args['request_id']
    if not request_id:
        datetime.strptime(registration_date, '%Y-%m-%d')
        formatted_registration_date = datetime.strptime(registration_date, '%Y-%m-%d').strftime('%d/%m/%Y')
        err = "Could not find request for {} of {}.".format(registration_no, formatted_registration_date)
        logging.error(format_message(err))
        return Response(err, status=400)
    logging.audit(format_message("Request reprint for %s"), request_id)
    # for the time being call reprint on result-generate. this probably needs moving into casework-api
    url = app.config['RESULT_GENERATE_URI'] + '/reprints?request=' + str(request_id)
    response = requests.get(url, headers=get_headers())
    if response.headers['content-type'] == 'application/pdf':
        return send_file(BytesIO(response.content), as_attachment=False, attachment_filename='reprint.pdf',
                         mimetype='application/pdf')
    else:
        err = "An error occured {}.".format(response.text)
        logging.error(format_message(err))
        return Response(err, status=405)
def unlock_application(appn_id):
    logging.info(format_message("Unlock application"))
    logging.audit(format_message("Unlock application"))
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        clear_lock_ind(cursor, appn_id)
    finally:
        complete(cursor)
    return Response(status=200)
def lock_application(appn_id):
    logging.info(format_message("Lock application"))
    logging.audit(format_message("Lock application"))
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        locked = set_lock_ind(cursor, appn_id)
        if locked is None:
            # Selected application already locked or no longer on work list
            return Response(status=404)
        else:
            return Response(status=200)
    finally:
        complete(cursor)
def remove_application(appn_id):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        if 'reject' in request.args:
            logging.audit(format_message("Reject application"))
        else:
            logging.audit(format_message("Remove application"))
        rows = delete_application(cursor, appn_id)
    finally:
        complete(cursor)

    if rows == 0:
        return Response(status=404)
    return Response(status=204, mimetype='application/json')
def all_registrations():
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        logging.audit(format_message("Retrieve all registrations"))
        details = get_all_registrations(cursor)
    finally:
        complete(cursor)
    if details is None:
        logging.warning(format_message("Returning 404 for /registrations"))
        return Response(status=404)
    else:
        return Response(json.dumps(details),
                        status=200,
                        mimetype='application/json')
def registrations_by_date(date):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        logging.audit(format_message("Retrieve registrations dated %s"), date)
        details = get_registrations_by_date(cursor, date)
    finally:
        complete(cursor)
    if details is None:
        logging.warning(
            format_message("Returning 404 for date {}".format(date)))
        return Response(status=404)
    else:
        return Response(json.dumps(details),
                        status=200,
                        mimetype='application/json')
def get_searches():
    logging.audit(format_message("Search reprints"))
    search_data = request.data
    response = requests.post(app.config['LAND_CHARGES_URI'] + '/request_search_details', data=search_data,
                             headers=get_headers({'Content-Type': 'application/json'}))
    data = json.loads(response.content.decode('utf-8'))
    return Response(json.dumps(data), status=200, mimetype='application/json')
def get_searches_by_date(date):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        data = get_search_ids_by_date(cursor, date)
    finally:
        logging.audit(format_message("Retrieve searches for date: %s"), date)
        complete(cursor)

    if data is None:
        logging.warning(
            format_message("Returning 404 for date {}".format(date)))
        return Response(status=404)
    else:
        return Response(json.dumps(data),
                        status=200,
                        mimetype='application/json')
def load_counties():  # pragma: no cover
    if not app.config['ALLOW_DEV_ROUTES']:  # and is_dev_VM()):
        return Response(status=403)

    if request.headers['Content-Type'] != "application/json":
        logging.error(format_message('Content-Type is not JSON'))
        return Response(status=415)

    json_data = request.get_json(force=True)
    cursor = connect()
    try:
        for item in json_data:
            if 'cym' not in item:
                item['cym'] = None

            cursor.execute(
                'INSERT INTO COUNTY (name, welsh_name) VALUES (%(e)s, %(c)s)',
                {
                    'e': item['eng'],
                    'c': item['cym']
                })
        complete(cursor)
    except:
        rollback(cursor)
        raise

    return Response(status=200)
def get_request_id():
    if 'registration_no' in request.args:
        reg_no = request.args['registration_no']
    else:
        return Response(json.dumps({'error': 'no registration_no'}),
                        status=400)

    if 'registration_date' in request.args:
        reg_date = request.args['registration_date']
    else:
        return Response(json.dumps({'error': 'no registration_date'}),
                        status=400)

    if 'reprint_type' in request.args:
        reprint_type = request.args['reprint_type']
    else:
        return Response("no reprint_type specified", status=400)

    logging.audit(
        format_message("Retrieve request details for registration %s of %s"),
        reg_no, reg_date)
    request_id = 0
    if reprint_type == 'registration':
        request_id = get_k22_request_id(reg_no, reg_date)
    elif reprint_type == 'search':
        request_id = 0  # write method to get k17/18 request ids

    return Response(json.dumps(request_id),
                    status=200,
                    mimetype='application/json')
def create_search():
    if request.headers['Content-Type'] != "application/json":
        logging.error(format_message('Content-Type is not JSON'))
        return Response(status=415)

    data = request.get_json(force=True)
    logging.debug('this is search data: %s', json.dumps(data))
    errors = validate(data, SEARCH_SCHEMA)
    if errors is not None:
        return Response(json.dumps(errors), status=400)
    logging.debug(data['parameters']['search_type'])

    if data['parameters']['search_type'] not in ['full', 'banks']:
        message = "Invalid search type supplied: {}".format(
            data['parameters']['search_type'])
        logging.error(format_message(message))
        return Response(message, status=400)

    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        # Store the search request
        if 'X-LC-Username' in request.headers:
            data['user_id'] = request.headers['X-LC-Username']
        search_request_id, search_details_id, search_data = store_search_request(
            cursor, data)

        # Run the queries
        results = perform_search(cursor, search_data['parameters'],
                                 search_data['search_date'])
        for item in results:
            store_search_result(cursor, search_request_id, search_details_id,
                                item['name_id'], item['name_result'])

        logging.audit(format_message("Submit search request: %d, ID: %d"),
                      search_request_id, search_details_id)
        complete(cursor)
        logging.info(format_message("Search request and result committed"))
    except:
        rollback(cursor)
        raise
    results = [search_request_id]
    if len(results) == 0:
        return Response(status=404)
    else:
        return Response(json.dumps(results, ensure_ascii=False),
                        status=200,
                        mimetype='application/json')
def error_handler(err):
    logging.error(format_message('Unhandled exception: ' + str(err)))
    call_stack = traceback.format_exc()

    lines = call_stack.split("\n")
    for line in lines:
        logging.error(format_message(line))

    error = {"type": "F", "stack": lines[0:-2]}

    try:
        error["dict"] = json.loads(str(err))
    except ValueError as e:
        error["text"] = str(err)

    logging.debug(json.dumps(error, indent=4))
    raise_error(error)
    return Response(json.dumps(error), status=500)
def submit_lc_cancellation(data):
    cust_address = data['customer_address'].replace("\r\n", ", ").strip()
    application = {
        'update_registration': {
            'type': 'Cancellation'
        },
        'applicant': {
            'key_number': data['key_number'],
            'name': data['customer_name'],
            'address': cust_address,
            'address_type': data['address_type'],
            'reference': data['customer_ref']
        },
        'registration_no': session['regn_no'],
        'document_id': session['document_id'],
        'registration': {
            'date': session['reg_date']
        },
        'fee_details': {
            'type': data['payment'],
            'fee_factor': 1,
            'delivery': session['application_dict']['delivery_method']
        }
    }
    if "class_of_charge" in session:
        application["class_of_charge"] = session["class_of_charge"]
    # if plan attached selected then pass the part_cans_text into that field
    if 'cancellation_type' in session:
        application['update_registration'] = {
            'type': session['cancellation_type']
        }
        if 'plan_attached' in session:
            if session['plan_attached'] == 'true':
                application['update_registration']['plan_attached'] = session[
                    'part_cans_text']
        elif 'part_cans_text' in session:
            application['update_registration']['part_cancelled'] = session[
                'part_cans_text']
    url = app.config['CASEWORK_API_URL'] + '/applications/' + session[
        'worklist_id'] + '?action=cancel'
    headers = get_headers({'Content-Type': 'application/json'})
    response = requests.put(url, data=json.dumps(application), headers=headers)
    if response.status_code == 200:
        logging.info(format_message("Cancellation submitted to CASEWORK_API"))
        data = response.json()
        if 'cancellations' in data:
            reg_list = []
            for item in data['cancellations']:
                reg_list.append(item['number'])
            session['confirmation'] = {'reg_no': reg_list}
        else:
            session['confirmation'] = {'reg_no': []}

    return response
def synchronise():  # pragma: no cover
    if not app.config['ALLOW_DEV_ROUTES']:  # and is_dev_VM()):
        return Response(status=403)

    if request.headers['Content-Type'] != "application/json":
        logging.error(format_message('Content-Type is not JSON'))
        return Response(status=415)

    json_data = request.get_json(force=True)
    publish_new_bankruptcy(producer, json_data)
    return Response(status=200)
def get_searches():
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)

    try:
        if 'name' in request.args:
            name = request.args['name']
            result = read_searches(cursor, name)

        elif 'id' in request.args:
            result = get_search_by_request_id(cursor, request.args['id'])

        else:
            result = []

        data = []
        for results in result:
            for ids in results['result']:
                reg_data = get_registration(cursor, ids, None)
                data.append({
                    'reg_id': ids,
                    'reg_no': reg_data['registration_no'],
                    'reg_date': reg_data['registration_date'],
                    'class': reg_data['class_of_charge']
                })

    finally:
        if 'name' in request.args:
            logging.audit(
                format_message("Retrieve search results by name: %s"),
                request.args['name'])

        elif 'id' in request.args:
            logging.audit(format_message("Retrieve search results by ID: %s"),
                          request.args['id'])

        else:
            logging.audit(format_message("Retrieve search results"))

        complete(cursor)

    return Response(json.dumps(data), status=200, mimetype='application/json')
def update_request_fee(request_id, transaction_fee):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    cursor.execute(
        'UPDATE request SET transaction_fee = %(fee)s '
        'WHERE id = %(request_id)s', {
            'request_id': request_id,
            'fee': transaction_fee
        })
    logging.audit(format_message("Set transaction fee to %s for request %s"),
                  transaction_fee, request_id)
    complete(cursor)
    return Response(status=200)
def registration_by_id(reg_id):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        logging.audit(format_message("Retrieve entry details for %s"), reg_id)

        details = get_registration_details_by_register_id(cursor, reg_id)
        if details is not None:
            addl_info = get_additional_info(cursor, details)

            if addl_info is not None:
                details['additional_information'] = addl_info
    finally:
        complete(cursor)
    if details is None:
        logging.warning(
            format_message(
                "Returning 404 for /registrations/{}".format(reg_id)))
        return Response(status=404)
    else:
        return Response(json.dumps(details),
                        status=200,
                        mimetype='application/json')
def register_correction():

    logging.info(session['original_regns']['applicant'])

    applicant = {
        'name': session['original_regns']['applicant']['name'],
        'address': session['original_regns']['applicant']['address'],
        'key_number': session['original_regns']['applicant']['key_number'],
        'reference': session['original_regns']['applicant']['reference'],
        'address_type': session['original_regns']['applicant']['address_type'],
    }

    registration = {
        'parties': session['parties'],
        'class_of_charge': session['original_regns']['class_of_charge'],
        'applicant': applicant,
        'update_registration': {
            'type': 'Correction'
        }
    }

    application = {
        'registration': registration,
        'orig_regn': session['details_entered'],
        'update_registration': {
            'type': 'Correction'
        }
    }

    if request.form['generate_K22'] == 'yes':
        application['k22'] = True
    else:
        application['k22'] = False

    url = app.config[
        'CASEWORK_API_URL'] + '/applications/0' + '?action=correction'

    headers = get_headers({'Content-Type': 'application/json'})
    headers['X-Transaction-ID'] = session['transaction_id']
    logging.debug("bankruptcy details: " + json.dumps(application))
    response = http_put(url, data=json.dumps(application), headers=headers)
    if response.status_code == 200:
        logging.info(
            format_message("Registration (bank) submitted to CASEWORK_API"))
        data = response.json()
        reg_list = []

        for item in data['new_registrations']:
            reg_list.append(item['number'])
        session['confirmation'] = {'reg_no': reg_list}
    return response
def save_request_fee(id, fee):
    assert (fee is not None and fee != ''), "Fee is missing"

    # Add transaction fee to the associated request
    url = app.config['LAND_CHARGES_URI'] + '/request/' + id + "/" + fee
    response = requests.put(url, headers=get_headers())
    if response.status_code != 200:
        err = 'Failed to store fee against request ' + id + '. Error code:' \
              + str(response.status_code)

        logging.error(format_message(err))
        raise RuntimeError(err)

    return Response(status=response.status_code, mimetype='application/json')
def get_registration(reg_date, reg_name):
    if "class_of_charge" in request.args:
        class_of_charge = request.args["class_of_charge"]
    else:
        class_of_charge = None

    logging.audit(format_message("Retrieve registration details for %s / %s"), reg_date, reg_name)
    response = get_registration_details(reg_date, reg_name, class_of_charge)
    logging.debug(response['data'])

    if response['status'] != 200:
        return Response(json.dumps(response['data']), status=response['status'], mimetype='application/json')
    else:
        return Response(json.dumps(response['data']), status=200, mimetype='application/json')
def registration_history(date, reg_no):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        logging.audit(format_message("Retrieve entry history for %s, %s"),
                      reg_no, date)
        details = get_registration_history(cursor, reg_no, date)
    finally:
        complete(cursor)
    if details is None:
        logging.warning("Returning 404")
        return Response(status=404)
    else:
        return Response(json.dumps(details),
                        status=200,
                        mimetype='application/json')
Example #24
0
def error_handler(err):
    logging.debug('-----------------')
    logging.error(str(err))
    logging.error(format_message('Unhandled exception: ' + str(err)))
    call_stack = traceback.format_exc()

    lines = call_stack.split("\n")
    for line in lines[0:-2]:
        logging.error(format_message(line))

    error = {
        "type": "F",
        "stack": lines[0:-2]
    }

    try:
        error["dict"] = json.loads(str(err))
    except ValueError as e:
        error["text"] = str(err)

    logging.error(json.dumps(error, indent=2))

    raise_error(error)
    return Response(json.dumps(error), status=500)
def reclassify_form():
    data = request.get_json(force=True)
    appn_id = data['appn_id']
    form_type = data['form_type']
    logging.info("T:%s Reclassify as a %s Application ", str(appn_id), str(form_type))
    logging.audit(format_message("Reclassify %s as %s"), str(appn_id), str(form_type))
    work_type = get_work_type(form_type)
    logging.info("move to %s", work_type["list_title"])
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        unlock_application(appn_id)
        reclassify_appn(cursor, appn_id, form_type, work_type["work_type"])
    finally:
        complete(cursor)
    return Response(json.dumps(work_type), status=200, mimetype='application/json')
def submit_lc_rectification(form):
    rect_details = (session['rectification_details'])
    if 'instrument' in rect_details['update_registration']:
        orig_date = rect_details['update_registration']['instrument']['original']
        orig_date = datetime.strptime(orig_date, "%d/%m/%Y").strftime("%Y-%m-%d")
        cur_date = rect_details['update_registration']['instrument']['current']
        cur_date = datetime.strptime(cur_date, "%d/%m/%Y").strftime("%Y-%m-%d")
        rect_details['update_registration']['instrument']['original'] = orig_date
        rect_details['update_registration']['instrument']['current'] = cur_date
    cust_address = form['customer_address'].replace("\r\n", ", ").strip()
    application = {'update_registration': {'type': 'Rectification'},
                   'applicant': {
                       'key_number': form['key_number'],
                       'name': form['customer_name'],
                       'address': cust_address,
                       'address_type': form['address_type'],
                       'reference': form['customer_ref']},
                   'parties': [get_party_name(rect_details)],
                   'particulars': {'counties': rect_details['county'], 'district': rect_details['district'],
                                   'description': rect_details['short_description']},
                   'class_of_charge': convert_class_of_charge(rect_details['class']),
                   'regn_no': session['regn_no'],
                   'registration': {'date': session['reg_date']},
                   'document_id': session['document_id'],
                   'additional_information': rect_details['additional_info'],
                   'fee_details': {'type': form['payment'],
                                   'fee_factor': 1,
                                   'delivery': session['application_dict']['delivery_method']}
                   }
    if "update_registration" in rect_details:
        application["update_registration"] = rect_details["update_registration"]
    url = app.config['CASEWORK_API_URL'] + '/applications/' + session['worklist_id'] + '?action=rectify'
    headers = get_headers({'Content-Type': 'application/json'})
    response = http_put(url, data=json.dumps(application), headers=headers)
    if response.status_code == 200:
        logging.info(format_message("Rectification submitted to CASEWORK_API"))
        data = response.json()

        if 'new_registrations' in data:
            reg_list = []
            for item in data['new_registrations']:
                reg_list.append(item['number'])
            session['confirmation'] = {'reg_no': reg_list}
        else:
            session['confirmation'] = {'reg_no': []}

    return Response(status=200)
def retrieve_office_copy():
    class_of_charge = request.args['class']
    reg_no = request.args['reg_no']
    date = request.args['date']

    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        data = get_ins_office_copy(cursor, class_of_charge, reg_no, date)
    finally:
        logging.audit(format_message("Retrieve office copy for %s, %s (%s)"),
                      reg_no, date, class_of_charge)
        complete(cursor)

    if data is None:
        return Response(data, status=404, mimetype='application/json')
    else:
        return Response(data, status=200, mimetype='application/json')
def register_correction():

    logging.info(session["original_regns"]["applicant"])

    applicant = {
        "name": session["original_regns"]["applicant"]["name"],
        "address": session["original_regns"]["applicant"]["address"],
        "key_number": session["original_regns"]["applicant"]["key_number"],
        "reference": session["original_regns"]["applicant"]["reference"],
        "address_type": session["original_regns"]["applicant"]["address_type"],
    }

    registration = {
        "parties": session["parties"],
        "class_of_charge": session["original_regns"]["class_of_charge"],
        "applicant": applicant,
        "update_registration": {"type": "Correction"},
    }

    application = {
        "registration": registration,
        "orig_regn": session["details_entered"],
        "update_registration": {"type": "Correction"},
    }

    if request.form["generate_K22"] == "yes":
        application["k22"] = True
    else:
        application["k22"] = False

    url = app.config["CASEWORK_API_URL"] + "/applications/0" + "?action=correction"

    headers = get_headers({"Content-Type": "application/json"})
    headers["X-Transaction-ID"] = session["transaction_id"]
    logging.debug("bankruptcy details: " + json.dumps(application))
    response = http_put(url, data=json.dumps(application), headers=headers)
    if response.status_code == 200:
        logging.info(format_message("Registration (bank) submitted to CASEWORK_API"))
        data = response.json()
        reg_list = []

        for item in data["new_registrations"]:
            reg_list.append(item["number"])
        session["confirmation"] = {"reg_no": reg_list}
    return response
def get_search_type(request_id):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    # get all rows for this request id, if none contain results then search type is 'search_nr'
    try:
        sql = "Select result from search_results where request_id = %(request_id)s"
        cursor.execute(sql, {"request_id": request_id})
        rows = cursor.fetchall()
    finally:
        logging.audit(
            format_message("Retrieve search results for request: %s"),
            request_id)
        complete(cursor)
    search_type = {'search_type': 'search nr'}
    for row in rows:
        if row['result']:
            search_type = {'search_type': 'search'}
    return Response(json.dumps(search_type),
                    status=200,
                    mimetype='application/json')
def get_request_details(request_id):
    request_type = get_request_type(request_id)
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        if request_type.lower() == 'search':
            data = get_search_request_details(request_id)
        else:  # not a search - reg register details
            data = get_register_request_details(request_id)

            for index, row in enumerate(
                    data):  # Each AKA registration needs populating

                revealable = get_most_recent_revealable(
                    cursor, row["registration_no"], row["registration_date"])
                if revealable:
                    if index < len(revealable['registrations']):
                        details = get_registration_details(
                            cursor,
                            revealable['registrations'][index]['number'],
                            revealable['registrations'][index]['date'])
                else:  # if nothing came back from revealable
                    details = get_registration_details(
                        cursor, row["registration_no"],
                        row["registration_date"])
                if details is not None:
                    if 'particulars' in details:
                        if 'counties' in details['particulars']:
                            if len(details['particulars']['counties']) > 1:
                                county = get_county(cursor,
                                                    row['registration_no'],
                                                    row['registration_date'])
                                details['particulars']['counties'] = county
                    addl_info = get_additional_info(cursor, details)
                    if addl_info is not None:
                        details['additional_information'] = addl_info
                row['details'] = details
    finally:
        logging.audit(format_message("Retrieve request details for ID: %s"),
                      request_id)
        complete(cursor)
    return Response(json.dumps(data), status=200, mimetype='application/json')
def get_applications():
    list_type = 'all'
    state = 'all'
    if 'type' in request.args:
        list_type = request.args['type']

    if 'state' in request.args:
        state = request.args['state'].upper()

    if list_type not in valid_types:
        return Response("Error: '" + list_type + "' is not one of the accepted work list types", status=400)

    logging.info(format_message('Get worklist %s'), list_type)
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        applications = get_application_list(cursor, list_type, state)
    finally:
        complete(cursor)

    data = json.dumps(applications, ensure_ascii=False)
    return Response(data, status=200, mimetype='application/json')
def submit_lc_cancellation(data):
    cust_address = data['customer_address'].replace("\r\n", ", ").strip()
    application = {'update_registration': {'type': 'Cancellation'},
                   'applicant': {
                       'key_number': data['key_number'],
                       'name': data['customer_name'],
                       'address': cust_address,
                       'address_type': data['address_type'],
                       'reference': data['customer_ref']},
                   'registration_no': session['regn_no'],
                   'document_id': session['document_id'],
                   'registration': {'date': session['reg_date']},
                   'fee_details': {'type': data['payment'],
                                   'fee_factor': 1,
                                   'delivery': session['application_dict']['delivery_method']}}
    if "class_of_charge" in session:
        application["class_of_charge"] = session["class_of_charge"]
    # if plan attached selected then pass the part_cans_text into that field
    if 'cancellation_type' in session:
        application['update_registration'] = {'type': session['cancellation_type']}
        if 'plan_attached' in session:
            if session['plan_attached'] == 'true':
                application['update_registration']['plan_attached'] = session['part_cans_text']
        elif 'part_cans_text' in session:
            application['update_registration']['part_cancelled'] = session['part_cans_text']
    url = app.config['CASEWORK_API_URL'] + '/applications/' + session['worklist_id'] + '?action=cancel'
    headers = get_headers({'Content-Type': 'application/json'})
    response = requests.put(url, data=json.dumps(application), headers=headers)
    if response.status_code == 200:
        logging.info(format_message("Cancellation submitted to CASEWORK_API"))
        data = response.json()
        if 'cancellations' in data:
            reg_list = []
            for item in data['cancellations']:
                reg_list.append(item['number'])
            session['confirmation'] = {'reg_no': reg_list}
        else:
            session['confirmation'] = {'reg_no': []}

    return response
Example #33
0
def submit_lc_registration(cust_fee_data):
    application = session['application_dict']
    application['class_of_charge'] = convert_application_type(session['application_type'])
    application['application_ref'] = cust_fee_data['application_reference']
    application['key_number'] = cust_fee_data['key_number']
    application['customer_name'] = cust_fee_data['customer_name']
    application['customer_address'] = cust_fee_data['customer_address']
    application['address_type'] = cust_fee_data['address_type']
    today = datetime.now().strftime('%Y-%m-%d')
    application['date'] = today
    application['residence_withheld'] = False
    #application['date_of_birth'] = "1980-01-01"  # DONE?: what are we doing about the DOB??
    application['document_id'] = session['document_id']
    application['fee_details'] = {'type': cust_fee_data['payment'],
                                  'fee_factor': 1,
                                  'delivery': session['application_dict']['delivery_method']}

    if session['application_dict']['form'] == 'K6':
        application['priority_notice_ind'] = True
        result_string = 'priority_notices'
    else:
        result_string = 'new_registrations'

    session['register_details']['estate_owner']['estate_owner_ind'] = session['register_details']['estate_owner_ind']
    #     convert_estate_owner_ind(session['register_details']['estate_owner_ind'])
    application['lc_register_details'] = session['register_details']

    url = app.config['CASEWORK_API_URL'] + '/applications/' + session['worklist_id'] + '?action=complete'
    headers = get_headers({'Content-Type': 'application/json'})
    response = http_put(url, data=json.dumps(application), headers=headers)
    if response.status_code == 200:
        logging.info(format_message("Registration submitted to CASEWORK_API"))
        data = response.json()
        reg_list = []

        for item in data[result_string]:
            reg_list.append(item['number'])
        session['confirmation'] = {'reg_no': reg_list}

    return response
def court_ref_existence_check(ref):
    logging.debug("Court existence checking")
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        logging.audit(format_message("Retrieve details by court: %s"), ref)
        cursor.execute(
            "SELECT registration_no, date FROM register r, register_details rd "
            + "WHERE UPPER(rd.legal_body_ref)=%(body_ref)s " +
            "AND rd.id=r.details_id "
            "AND (r.expired_on is NULL OR r.expired_on > current_date) "
            "AND rd.cancelled_by is NULL " +
            "AND (UPPER(rd.amendment_type)!='CANCELLATION' or rd.amendment_type is NULL) ",
            {"body_ref": ref.upper()})
        rows = cursor.fetchall()
        results = []
        if len(rows) > 0:
            status_code = 200
            for row in rows:
                details = get_registration_details(cursor,
                                                   row['registration_no'],
                                                   row['date'])
                debtor_name = details['parties'][0]['names'][0]['private']
                name_string = " ".join(
                    debtor_name['forenames']) + " " + debtor_name['surname']
                results.append({
                    'reg_no': details['registration']['number'],
                    'date': details['registration']['date'],
                    'class_of_charge': details['class_of_charge'],
                    'name': name_string
                })
        else:
            status_code = 404
    finally:
        complete(cursor)

    return Response(json.dumps(results),
                    status=status_code,
                    mimetype='application/json')
Example #35
0
def associate_image():
    data = request.get_json(force=True)
    logging.debug(json.dumps(data))
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    logging.audit(format_message("Link image to registration %s of %s"), data['reg_no'], data['date'])
    try:
        cursor.execute("UPDATE registered_documents SET doc_id = %(doc_id)s " +
                       "WHERE number=%(reg)s and date=%(date)s",
                       {
                           "doc_id": data['document_id'], "reg": int(data['reg_no']), "date": data['date']
                       })
        rows = cursor.rowcount
        if rows == 0:
            status_code = 404
        else:
            delete_application(cursor, data['appn_id'])
            status_code = 200
        complete(cursor)
    except:
        rollback(cursor)
        raise

    return Response(status=status_code, mimetype='application/json')
Example #36
0
def get_multi_reg_check(reg_date, reg_no):
    logging.audit(format_message("Check multiple registration for %s %s"), reg_no, reg_date)
    url = app.config['LAND_CHARGES_URI'] + '/multi_reg_check/' + reg_date + "/" + reg_no
    data = requests.get(url, headers=get_headers())
    return Response(data, status=200, mimetype='application/json')
Example #37
0
def get_keyholder(key_number):
    logging.audit(format_message("Get keyholder details"))
    uri = app.config['LEGACY_ADAPTER_URI'] + '/keyholders/' + key_number
    response = requests.get(uri, headers=get_headers())
    return Response(response.text, status=response.status_code, mimetype='application/json')
Example #38
0
def update_application(appn_id):
    # TODO: validate
    action = 'store'
    if 'action' in request.args:
        action = request.args['action']

    logging.debug(request.headers)

    data = request.get_json(force=True)
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    # store fee info for later use. Quick fix because of data structure in rectifications
    if 'fee_details' in data:
        fee_ind = True
        fee_details = data['fee_details']
    else:
        fee_ind = False
        fee_details = {}

    try:
        if action == 'store':
            logging.info(format_message("Store application"))
            logging.audit(format_message("Store application"))
            # logging.debug(data)
            # update_application_details(cursor, appn_id, data)
            store_application(cursor, appn_id, data)
            appn = get_application_by_id(cursor, appn_id)
        elif action == 'complete':
            logging.info(format_message("Complete registration"))
            logging.audit(format_message("Complete application"))
            appn = complete_application(cursor, appn_id, data)
        elif action == 'amend' or action == 'rectify':
            logging.info(format_message("Complete update"))
            logging.audit(format_message("Complete update application"))
            appn = amend_application(cursor, appn_id, data)
        elif action == 'cancel':
            logging.info(format_message("Complete cancellation"))
            logging.audit(format_message("Complete cancellation application"))
            appn = cancel_application(cursor, appn_id, data)
        elif action == 'renewal':
            logging.info(format_message("Complete renewal"))
            logging.audit(format_message("Complete renewal application"))
            appn = renew_application(cursor, appn_id, data)
        elif action == 'correction':
            logging.info(format_message("Complete correction"))
            logging.audit(format_message("Complete correction"))
            appn = correct_application(cursor, data)
        else:
            return Response("Invalid action", status=400)
        # sort out the fee
        # everything but searches
        if fee_ind is True:
            logging.debug("fee selected" + json.dumps(fee_details))
            if fee_details['type'] == 'wf' or  fee_details['type'] == 'nf':
                save_request_fee(str(appn['request_id']), str(0))
            else:
                # build the fee details to pass to legacy_adapter
                build_fee_data(data, appn, fee_details, action)
        complete(cursor)
        status = 200
    except ValidationError as e:
        rollback(cursor)
        error_str = str(e)
        error_dict = json.loads(error_str[1:-1])  # Exception seems to add quotes, annoyingly
        appn = {"ValidationError": error_dict}
        status = 400
    except:
        rollback(cursor)
        raise
    return Response(json.dumps(appn), status=status)
Example #39
0
def post_search():
    data = request.get_json(force=True)

    logging.debug(json.dumps(data))
    logging.audit("Submit search")

    today = datetime.now().strftime('%Y-%m-%d')
    date_uri = app.config['LEGACY_ADAPTER_URI'] + '/dates/' + today
    date_response = requests.get(date_uri, headers=get_headers())

    if date_response.status_code != 200:
        raise CaseworkAPIError(json.dumps({
            "message": "Unexpected response from legacy_adapter/dates: " + str(date_response.status_code),
            "response": date_response.text
        }))

    # call legacy_adapter to retrieve the next search number
    url = app.config['LEGACY_ADAPTER_URI'] + '/search_number'
    response = requests.get(url, headers=get_headers())
    if response.status_code == 200:
        cert_no = response.text
    else:
        err = 'Failed to call search_number. Error code: {}'.format(str(response.status_code))
        logging.error(format_message(err))
        raise CaseworkAPIError(json.dumps({
            "message": err,
            "response": response.text
        }))

    date_info = date_response.json()
    data['expiry_date'] = date_info['search_expires']
    data['search_date'] = date_info['prev_working']
    data['cert_no'] = cert_no

    uri = app.config['LAND_CHARGES_URI'] + '/searches'
    response = requests.post(uri, data=json.dumps(data), headers=get_headers({'Content-Type': 'application/json'}))
    if response.status_code != 200:
        raise CaseworkAPIError(json.dumps(response.text))

    logging.info('POST {} -- {}'.format(uri, response.text))

    # store result
    response_data = response.json()
    logging.debug(json.dumps(response_data))
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        # process fee info
        if data['fee_details']['type'] == 'wf' or data['fee_details']['type'] == 'nf':
            save_request_fee(str(response_data[0]), str(0))
        else:
            # build the fee details to pass to legacy_adapter
            build_fee_data(data, response_data, data['fee_details'], 'search')
        store_image_for_later(cursor, data['document_id'], None, None, response_data[0])
        complete(cursor)
    except:
        rollback(cursor)
        raise

    cursor = connect()
    for req_id in response_data:
        uri = app.config['LAND_CHARGES_URI'] + '/search_type/' + str(req_id)
        response = requests.get(uri, headers=get_headers())
        resp_data = response.json()
        res_type = resp_data['search_type']
        insert_result_row(cursor, req_id, res_type)
    complete(cursor)
    return Response(response.text, status=response.status_code, mimetype='application/json')
Example #40
0
def build_fee_data(data, appn, fee_details, action):
    if action == 'complete':
        fee = {'transaction_code': 'RN',
               'key_number': data['key_number'],
               'reference': data['application_ref'],
               'class_of_charge': data['lc_register_details']['class']}
        reg_type = 'new_registrations'
    elif action == 'rectify':
        fee = {'transaction_code': 'RN',
               'key_number': data['applicant']['key_number'],
               'reference': data['applicant']['reference'],
               'class_of_charge': data['class_of_charge']}
        reg_type = 'new_registrations'
    elif action == 'renewal':
        fee = {'transaction_code': 'RN',
               'key_number': data['applicant']['key_number'],
               'reference': data['applicant']['reference'],
               'class_of_charge': data['class_of_charge']}
        reg_type = 'new_registrations'
    elif action == 'cancel':
        fee = {'transaction_code': 'CN',
               'key_number': data['applicant']['key_number'],
               'reference': data['applicant']['reference']}
        reg_type = 'cancellations'
        date = data['registration']['date']
        number = data['registration_no']
        url = app.config['LAND_CHARGES_URI'] + '/registrations/' + date + '/' + number
        response = requests.get(url, headers=get_headers())
        if response.status_code == 200:
            result = (json.loads(response.text))
            fee['class_of_charge'] = result['class_of_charge']
        else:
            err = "Failed to get registration {} of {}. Code: {}".format(
                number, date, response.status_code
            )
            logging.error(format_message(err))
            raise CaseworkAPIError(json.dumps({
                "message": err,
                "response": response.text
            }))

    elif action == 'search':
        if fee_details['delivery'] == 'Postal':
            transaction_code = 'PS'
        else:
            transaction_code = 'XS'

        fee = {'transaction_code': transaction_code,
               'key_number': data['customer']['key_number'],
               'reference': data['customer']['reference'],
               'class_of_charge': ' ',
               'method_of_payment': fee_details['type']}

        fee_data = {'fee_info': fee,
                    'reg_no': ' ',
                    'appn_no': data['cert_no'],
                    'fee_factor': fee_details['fee_factor']}

        # call legacy_adapter to process fee for search and return
        logging.debug("fee information" + json.dumps(fee_data))
        url = app.config['LEGACY_ADAPTER_URI'] + '/fee_process'
        response = requests.post(url, data=json.dumps(fee_data), headers=get_headers())
        if response.status_code == 200:
            fee = response.text
            save_request_fee(str(appn[0]), fee)
            return response.status_code
        else:
            err = "Failed to call fee_process for {}. Code: {}".format(
                data["cert_no"], response.status_code
            )

            logging.error(format_message(err))
            raise CaseworkAPIError(json.dumps({
                "message": err,
                "response": response.text
            }))

    else:
        err = "The fee action is incorrect: {}".format(action)
        logging.error(format_message(err))
        raise CaseworkAPIError(json.dumps({
            "message": err
        }))

        # call legacy_adapter for each registration number
    if 'priority_notices' in appn:
        reg_type = 'priority_notices'

    fee['method_of_payment'] = fee_details['type']

    fee_data = {'fee_info': fee}

    print(appn[reg_type])
    if action == 'cancel':
        fee_data['reg_no'] = number
        fee_data['appn_no'] = str(appn[reg_type][0]['number'])
    else:
        fee_data['reg_no'] = str(appn[reg_type][0]['number'])
        fee_data['appn_no'] = str(appn[reg_type][0]['number'])
    fee_data['fee_factor'] = fee_details['fee_factor']
    logging.debug("fee information " + json.dumps(fee_data))
    url = app.config['LEGACY_ADAPTER_URI'] + '/fee_process'
    response = requests.post(url, data=json.dumps(fee_data), headers=get_headers())
    if response.status_code != 200:
        err = "Failed to call fee_process for {}. Code: {}".format(
            fee_data['appn_no'], response.status_code
        )

        logging.error(format_message(err))
        raise CaseworkAPIError(json.dumps({
            "message": err
        }))
    else:
        fee = response.text
        save_request_fee(str(appn['request_id']), fee)

    return
def process_search_criteria(data, search_type):
    logging.debug("process search data")
    counties = []
    parameters = {
        "counties": counties,
        "search_type": "banks" if search_type == "search_bank" else "full",
        "search_items": [],
    }
    counter = 1

    while True:

        name_type = "nameType_{}".format(counter)
        if name_type not in data:
            break

        name_extracted = False

        if data[name_type] == "privateIndividual" and data["surname_{}".format(counter)] != "":

            forename = "forename_{}".format(counter)
            surname = "surname_{}".format(counter)
            search_item = {
                "name_type": "Private Individual",
                "name": {"forenames": data[forename], "surname": data[surname]},
            }
            name_extracted = True

        elif data[name_type] == "limitedCompany" and data["company_{}".format(counter)] != "":

            company = "company_{}".format(counter)
            search_item = {"name_type": "Limited Company", "name": {"company_name": data[company]}}
            name_extracted = True

        elif (
            data[name_type] == "countyCouncil"
            and data["loc_auth_{}".format(counter)] != ""
            and data["loc_auth_area_{}".format(counter)] != ""
        ):

            loc_auth = "loc_auth_{}".format(counter)
            loc_auth_area = "loc_auth_area_{}".format(counter)
            search_item = {
                "name_type": "County Council",
                "name": {"local_authority_name": data[loc_auth], "local_authority_area": data[loc_auth_area]},
            }
            name_extracted = True

        elif (
            data[name_type] == "ruralCouncil"
            and data["loc_auth_{}".format(counter)] != ""
            and data["loc_auth_area_{}".format(counter)] != ""
        ):

            loc_auth = "loc_auth_{}".format(counter)
            loc_auth_area = "loc_auth_area_{}".format(counter)
            search_item = {
                "name_type": "Rural Council",
                "name": {"local_authority_name": data[loc_auth], "local_authority_area": data[loc_auth_area]},
            }
            name_extracted = True

        elif (
            data[name_type] == "parishCouncil"
            and data["loc_auth_{}".format(counter)] != ""
            and data["loc_auth_area_{}".format(counter)] != ""
        ):

            loc_auth = "loc_auth_{}".format(counter)
            loc_auth_area = "loc_auth_area_{}".format(counter)
            search_item = {
                "name_type": "Parish Council",
                "name": {"local_authority_name": data[loc_auth], "local_authority_area": data[loc_auth_area]},
            }
            name_extracted = True

        elif (
            data[name_type] == "otherCouncil"
            and data["loc_auth_{}".format(counter)] != ""
            and data["loc_auth_area_{}".format(counter)] != ""
        ):

            loc_auth = "loc_auth_{}".format(counter)
            loc_auth_area = "loc_auth_area_{}".format(counter)
            search_item = {
                "name_type": "Other Council",
                "name": {"local_authority_name": data[loc_auth], "local_authority_area": data[loc_auth_area]},
            }
            name_extracted = True

        elif data[name_type] == "codedName" and data["other_name_{}".format(counter)] != "":
            other_name = "other_name_{}".format(counter)
            search_item = {"name_type": "Coded Name", "name": {"other_name": data[other_name]}}
            name_extracted = True

        elif (
            data[name_type] == "complexName"
            and data["complex_name_{}".format(counter)] != ""
            and data["complex_number_{}".format(counter)] != ""
        ):

            complex_name = "complex_name_{}".format(counter)
            complex_number = "complex_number_{}".format(counter)
            search_item = {
                "name_type": "Complex Name",
                "name": {
                    "complex_name": data[complex_name],
                    "complex_number": int(data[complex_number]),
                    "complex_variations": [],
                },
            }
            url = app.config["CASEWORK_API_URL"] + "/complex_names/search"
            headers = get_headers({"Content-Type": "application/json"})
            comp_name = {"name": data[complex_name], "number": int(data[complex_number])}
            response = http_post(url, data=json.dumps(comp_name), headers=headers)
            logging.info(format_message("POST {} -- {}".format(url, response)))
            result = response.json()

            for item in result:
                search_item["name"]["complex_variations"].append({"name": item["name"], "number": int(item["number"])})
            name_extracted = True

        elif data[name_type] == "developmentCorporation" and data["other_name_{}".format(counter)] != "":
            # name_type is other
            other_name = "other_name_{}".format(counter)
            search_item = {"name_type": "Development Corporation", "name": {"other_name": data[other_name]}}
            name_extracted = True

        elif data[name_type] == "other" and data["other_name_{}".format(counter)] != "":
            # name_type is other
            other_name = "other_name_{}".format(counter)
            search_item = {"name_type": "Other", "name": {"other_name": data[other_name]}}
            name_extracted = True

        if search_type == "search_full" and name_extracted:
            logging.debug("Getting year stuff")
            search_item["year_to"] = int(data["year_to_{}".format(counter)])
            search_item["year_from"] = int(data["year_from_{}".format(counter)])

        if name_extracted:
            parameters["search_items"].append(search_item)

        counter += 1

    result = {}
    if search_type == "search_full":
        if "all_counties" in data and data["all_counties"] == "yes":
            result["county"] = ["ALL"]
        else:
            add_counties(result, data)
    else:
        result["county"] = []

    parameters["counties"] = result["county"]
    session["application_dict"]["search_criteria"] = parameters
    return
def register_bankruptcy(key_number):

    url = app.config["CASEWORK_API_URL"] + "/keyholders/" + key_number
    response = http_get(url, headers={"X-Transaction-ID": session["transaction_id"]})
    text = json.loads(response.text)
    if response.status_code == 200:
        cust_address = ", ".join(text["address"]["address_lines"]) + ", " + text["address"]["postcode"]
        address_type = "RM"
        if ("dx_number" in text) and ("dx_exchange" in text):
            if text["dx_number"]:  # switch to dx address if available
                if text["dx_exchange"]:
                    dx_no = str(text["dx_number"]).upper()
                    if not dx_no.startswith("DX"):
                        dx_no = "DX " + dx_no
                    cust_address = dx_no + ", " + text["dx_exchange"]
                    address_type = "DX"
        cust_name = text["name"]
        applicant = {
            "name": cust_name,
            "address": cust_address.upper(),
            "key_number": key_number,
            "reference": " ",
            "address_type": address_type,
        }
    else:
        return response

    if session["application_type"] == "bank_amend":
        class_of_charge = session["original_regns"]["class_of_charge"]
    elif session["application_dict"]["form"] == "PA(B)":
        class_of_charge = "PAB"
    elif session["application_dict"]["form"] == "WO(B)":
        class_of_charge = "WOB"
    else:
        class_of_charge = session["application_dict"]["form"]

    registration = {"parties": session["parties"], "class_of_charge": class_of_charge, "applicant": applicant}

    application = {
        "registration": registration,
        "application_data": session["application_dict"]["application_data"],
        "form": session["application_dict"]["form"],
    }

    if session["application_type"] == "bank_amend":
        # TODO: update registration added twice to get around bad structure for rectifications which needs changing!
        application["update_registration"] = {"type": "Amendment"}
        application["registration"]["update_registration"] = {"type": "Amendment"}
        if "wob_entered" in session:
            application["wob_original"] = session["wob_entered"]
        if "pab_entered" in session:
            application["pab_original"] = session["pab_entered"]
        url = app.config["CASEWORK_API_URL"] + "/applications/" + session["worklist_id"] + "?action=amend"
    else:
        url = app.config["CASEWORK_API_URL"] + "/applications/" + session["worklist_id"] + "?action=complete"

    headers = get_headers({"Content-Type": "application/json"})
    logging.debug("bankruptcy details: " + json.dumps(application))
    response = http_put(url, data=json.dumps(application), headers=headers)
    if response.status_code == 200:
        logging.info(format_message("Registration (bank) submitted to CASEWORK_API"))
        data = response.json()
        reg_list = []

        for item in data["new_registrations"]:
            reg_list.append(item["number"])
        session["confirmation"] = {"reg_no": reg_list}

    return response