def insert_result(request_id, result_type):
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        insert_result_row(cursor, request_id, result_type)
        complete(cursor)
    except:
        rollback(cursor)
        raise
    return Response(status=200)
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')