def get_party_name(data):
        party = {
            "type": "Estate Owner",
            "names": []}
        name = {"type": data['estate_owner_ind']}

        if name['type'] == 'Private Individual':
            name['private'] = {
                'forenames': data['estate_owner']['private']['forenames'],
                'surname': data['estate_owner']['private']['surname']}
        elif name['type'] == "County Council" or name['type'] == "Parish Council" or name['type'] == "Other Council":
            name['local'] = {
                'name': data['estate_owner']['local']['name'],
                'area': data['estate_owner']['local']['area']}
        elif name['type'] == "Development Corporation" or name['type'] == "Other":
            name['other'] = data['estate_owner']['other']
        elif name['type'] == "Limited Company":
            name['company'] = data['estate_owner']['company']
        elif name['type'] == "Complex Name":
            name['complex'] = {
                'name': data['estate_owner']['complex']['name'],
                'number': data['estate_owner']['complex']['number']}
        else:
            raise CaseworkAPIError("Unexpected name type: {}".format(name['type']))

        party['names'].append(name)
        party['occupation'] = data['occupation']

        return party
def amend_application(cursor, appn_id, data):
    logging.debug(data)
    if data['update_registration']['type'] == 'Amendment':
        doc_id = data['application_data']['document_id']
        reg_data = data['registration']
        if 'wob_original' in data and 'pab_original' in data:
            reg_no = data['wob_original']['number']
            date = data['wob_original']['date']
            reg_data['pab_amendment'] = {'reg_no': data['pab_original']['number'],
                                         'date': data['pab_original']['date'],
                                         }
        elif 'wob_original' in data:
            reg_no = data['wob_original']['number']
            date = data['wob_original']['date']
        else:
            reg_no = data['pab_original']['number']
            date = data['pab_original']['date']
    else:  # rectification
        reg_no = data['regn_no']
        date = data['registration']['date']
        doc_id = data['document_id']
        del data['regn_no']
        del data['registration']
        del data['document_id']
        del data['fee_details']
        reg_data = data

    url = app.config['LAND_CHARGES_URI'] + '/registrations/' + date + '/' + reg_no
    headers = get_headers({'Content-Type': 'application/json'})
    response = requests.put(url, data=json.dumps(reg_data), headers=headers)
    if response.status_code != 200:
        logging.error(response.text)
        error = json.loads(response.text)
        logging.error(json.dumps(error, indent=2))
        raise CaseworkAPIError(json.dumps(error))

    regns = response.json()

    # Insert print job
    insert_result_row(cursor, regns['request_id'], 'registration')

    for regn in regns['new_registrations']:
        number = regn['number']
        date = regn['date']
        store_image_for_later(cursor, doc_id, number, date)

    # Delete work-item
    delete_application(cursor, appn_id)

    # return regn nos
    return regns
def cancel_application(cursor, appn_id, data):
    # Cancel registration
    url = app.config['LAND_CHARGES_URI'] + '/cancellations'
    headers = get_headers({'Content-Type': 'application/json'})

    response = requests.post(url, data=json.dumps(data), headers=headers)
    if response.status_code != 200:
        logging.error(response.text)
        raise CaseworkAPIError(json.dumps(response.text))

    regns = response.json()
    # Insert print job
    insert_result_row(cursor, regns['request_id'], 'registration')
    # Archive document
    document_id = data['document_id']
    # pages = get_document(cursor, document_id)
    for regn in regns['cancellations']:
        number = regn['number']
        date = regn['date']
        store_image_for_later(cursor, document_id, number, date)
    # Delete work-item
    delete_application(cursor, appn_id)
    return regns
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')
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 complete_application(cursor, appn_id, data):
    # Submit registration
    url = app.config['LAND_CHARGES_URI'] + '/registrations'
    headers = get_headers({'Content-Type': 'application/json'})
    if 'lc_register_details' in data:
        response = requests.post(url, data=json.dumps(create_lc_registration(data)), headers=headers)
    else:  # banks registration
        response = requests.post(url, data=json.dumps(data['registration']), headers=headers)

    if response.status_code == 400:
        logging.error(response.text)
        raise ValidationError(response.text)

    elif response.status_code != 200:
        logging.error(response.text)
        error = json.loads(response.text)
        logging.error(json.dumps(error, indent=2))
        raise CaseworkAPIError(json.dumps(error))

    regns = response.json()

    # Insert print job
    errors = []
    try:
        insert_result_row(cursor, regns['request_id'], 'registration')
    except Exception as e:
        error = "Failed to insert print row. Message: {}".format(str(e))
        errors.append(error)
        logging.error(error)

    # Archive document
    document_id = data['application_data']['document_id']
    if data['form'] == 'K6':
        reg_type = 'priority_notices'
    else:
        reg_type = 'new_registrations'

    try:
        for regn in regns[reg_type]:
            number = regn['number']
            date = regn['date']
            store_image_for_later(cursor, document_id, number, date)
    except Exception as e:
        error = "Failed to insert image for later. Message: {}".format(str(e))
        errors.append(error)
        logging.error(error)

    # Delete work-item
    try:
        delete_application(cursor, appn_id)
    except Exception as e:
        error = "Failed to delete application row. Message: {}".format(str(e))
        errors.append(error)
        logging.error(error)

    # return regn nos

    for error in errors:
        raise_error(error)

    return regns
def create_lc_registration(data):
    coc_lut = {
        'C(I)': 'C1',
        'C(II)': 'C2',
        'C(III)': 'C3',
        'C(IV)': 'C4',
        'D(I)': 'D1',
        'D(II)': 'D2',
        'D(III)': 'D3',
    }

    c = data['lc_register_details']['class']
    if c in coc_lut:
        c = coc_lut[c]
    else:
        c = re.sub("[\(\)]", "", c)

    registration = {
        "parties": [],
        "class_of_charge": c,
        "applicant": {
            "name": data['customer_name'],
            "address": data['customer_address'],
            "address_type": data['address_type'],
            "key_number": data["key_number"],
            "reference": data['application_ref']
        }
    }

    party = {
        "type": "Estate Owner",
        "names": []
    }

    name_data = data['lc_register_details']["estate_owner"]
    name = {
        "type": name_data['estate_owner_ind']
    }

    if name['type'] == 'Private Individual':
        name['private'] = {
            'forenames': name_data['private']['forenames'],
            'surname': name_data['private']['surname']
        }
    elif name['type'] == "County Council" or name['type'] == \
            "Parish Council" or name['type'] == "Rural Council" or name['type'] == "Other Council":
        name['local'] = {
            'name': name_data['local']['name'],
            'area': name_data['local']['area']
        }
    elif name['type'] == "Development Corporation" or name['type'] == "Other" or name['type'] == 'Coded Name':
        name['other'] = name_data['other']
    elif name['type'] == "Limited Company":
        name['company'] = name_data['company']
    elif name['type'] == "Complex Name":
        name['complex'] = {
            'name': name_data['complex']['name'],
            'number': name_data['complex']['number']
        }
    else:
        raise CaseworkAPIError("Unexpected name type: {}".format(name['type']))

    party['names'].append(name)
    party['occupation'] = data['lc_register_details']['occupation']
    registration['parties'].append(party)

    if 'additional_info' in data['lc_register_details']:
        registration['additional_information'] = data['lc_register_details']['additional_info']

    registration['particulars'] = {
        "counties": data['lc_register_details']['county'],
        "district": data['lc_register_details']['district'],
        "description": data['lc_register_details']['short_description']
    }

    if data['lc_register_details']['priority_notice'] != '':
        registration['particulars']['priority_notice'] = data['lc_register_details']['priority_notice']

    if 'priority_notice_ind' in data:
        # get the priority notice expiry date
        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(date_response.text))

        date_info = date_response.json()
        registration['priority_notice'] = {'expires': date_info['priority_notice_expires']}

    return registration