<commit_before>from application import app
from flask import Response, request
import logging
import requests
import json
import traceback
import kombu
import re
import json
import datetime
from datetime import timedelta


def check_bankreg_health():
    return requests.get(app.config['BANKRUPTCY_DATABASE_API'] + '/health')

application_dependencies = [
    {
        "name": "bankruptcy-registration",
        "check": check_bankreg_health
    }
]


@app.errorhandler(Exception)
def error_handler(err):
    logging.error('Unhandled exception: ' + str(err))
    call_stack = traceback.format_exc()

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

    error = {
        "type": "F",
        "message": str(err),
        "stack": call_stack
    }
    raise_error(error)
    return Response(json.dumps(error), status=500)


@app.before_request
def before_request():
    logging.info("BEGIN %s %s [%s] (%s)",
                 request.method, request.url, request.remote_addr, request.__hash__())


@app.after_request
def after_request(response):
    logging.info('END %s %s [%s] (%s) -- %s',
                 request.method, request.url, request.remote_addr, request.__hash__(),
                 response.status)
    return response


def automatic_process(registration):
    return True


@app.route('/', methods=["GET"])
def index():
    return Response(status=200)


@app.route('/health', methods=['GET'])
def health():
    result = {
        'status': 'OK',
        'dependencies': {}
    }

    status = 200
    for dependency in application_dependencies:
        response = dependency["check"]()
        result['dependencies'][dependency['name']] = str(response.status_code) + ' ' + response.reason
        data = json.loads(response.content.decode('utf-8'))
        for key in data['dependencies']:
            result['dependencies'][key] = data['dependencies'][key]

    return Response(json.dumps(result), status=status, mimetype='application/json')


def format_message(message):
    if 'X-Transaction-ID' in request.headers:
        return "T:{} {}".format(request.headers['X-Transaction-ID'], message)
    return message


def create_registration(data):
    registration = {
        "parties": [],
        "class_of_charge": re.sub("[\(\)]", "", data['application_type']),
        "applicant": {
            "name": data['customer_name'],
            "address": data['customer_address'],
            "key_number": data['key_number'],
            "reference": data['application_ref'],
            "address_type": "NA"
        },
        'original_request': data['original_request']
    }

    party = {
        "type": "Debtor",
        "names": [],
        "addresses": [],
        "occupation": data['occupation'],
        "trading_name": data['trading_name'],
        "residence_withheld": data['residence_withheld'],
        "case_reference": "[WHAT GOES HERE] FIXME!",
        "date_of_birth": data['date_of_birth']
    }

    for name in data['debtor_names']:
        party['names'].append({
            'type': 'Private Individual',
            'private': name
        })

    if 'residence' in data:<commit_msg>Set case reference<commit_after>from application import app
from flask import Response, request
import logging
import requests
import json
import traceback
import kombu
import re
import json
import datetime
from datetime import timedelta


def check_bankreg_health():
    return requests.get(app.config['BANKRUPTCY_DATABASE_API'] + '/health')

application_dependencies = [
    {
        "name": "bankruptcy-registration",
        "check": check_bankreg_health
    }
]


@app.errorhandler(Exception)
def error_handler(err):
    logging.error('Unhandled exception: ' + str(err))
    call_stack = traceback.format_exc()

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

    error = {
        "type": "F",
        "message": str(err),
        "stack": call_stack
    }
    raise_error(error)
    return Response(json.dumps(error), status=500)


@app.before_request
def before_request():
    logging.info("BEGIN %s %s [%s] (%s)",
                 request.method, request.url, request.remote_addr, request.__hash__())


@app.after_request
def after_request(response):
    logging.info('END %s %s [%s] (%s) -- %s',
                 request.method, request.url, request.remote_addr, request.__hash__(),
                 response.status)
    return response


def automatic_process(registration):
    return True


@app.route('/', methods=["GET"])
def index():
    return Response(status=200)


@app.route('/health', methods=['GET'])
def health():
    result = {
        'status': 'OK',
        'dependencies': {}
    }

    status = 200
    for dependency in application_dependencies:
        response = dependency["check"]()
        result['dependencies'][dependency['name']] = str(response.status_code) + ' ' + response.reason
        data = json.loads(response.content.decode('utf-8'))
        for key in data['dependencies']:
            result['dependencies'][key] = data['dependencies'][key]

    return Response(json.dumps(result), status=status, mimetype='application/json')


def format_message(message):
    if 'X-Transaction-ID' in request.headers:
        return "T:{} {}".format(request.headers['X-Transaction-ID'], message)
    return message


def create_registration(data):
    registration = {
        "parties": [],
        "class_of_charge": re.sub("[\(\)]", "", data['application_type']),
        "applicant": {
            "name": data['customer_name'],
            "address": data['customer_address'],
            "key_number": data['key_number'],
            "reference": data['application_ref'],
            "address_type": "NA"
        },
        'original_request': data['original_request']
    }

    party = {
        "type": "Debtor",
        "names": [],
        "addresses": [],
        "occupation": data['occupation'],
        "trading_name": data['trading_name'],
        "residence_withheld": data['residence_withheld'],
        "case_reference": "Adjudicator ref {}".format(data['application_ref']),
        "date_of_birth": data['date_of_birth']
    }

    for name in data['debtor_names']:
        party['names'].append({
            'type': 'Private Individual',
            'private': name
        })

    if 'residence' in data:
{'fraction_non_alphanumeric': 0.1495444549167452, 'fraction_numerical': 0.0031416902293433867, 'mean_word_length': 2.976889444097439, 'pattern_counts': {'":': 42, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2058163', 'n_tokens_mistral': 1920, 'n_tokens_neox': 1840, 'n_words': 396}