views.py 17.3 KB
Newer Older
1 2 3
"""
    Routes
"""
4
import copy
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
5
import io
Pierre Dittgen's avatar
Pierre Dittgen committed
6
import itertools
7
import json
8
import logging
9
import subprocess
10
import tempfile
11
from datetime import datetime
12
from operator import itemgetter
13 14
from pathlib import Path
from urllib.parse import quote_plus
15

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
16
import requests
17
from backports.datetime_fromisoformat import MonkeyPatch
18
from commonmark import commonmark
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
19
from flask import make_response, redirect, render_template, request, url_for
Pierre Dittgen's avatar
Pierre Dittgen committed
20 21
from validata_core import compute_badge, csv_helpers, messages
from validata_core.loaders import custom_loaders
22

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
23 24
import tabulator

Pierre Dittgen's avatar
Pierre Dittgen committed
25
from . import app, config, ui_config, schema_info_map
26 27
from .ui_util import flash_error, flash_warning
from .validata_util import ValidataSource
28

29 30
MonkeyPatch.patch_fromisoformat()

31 32
log = logging.getLogger(__name__)

33 34

def extract_source_data(source: ValidataSource, preview_rows_nb=5):
35
    """ Computes table preview """
36 37 38

    def stringify(val):
        """ Transform value into string """
Pierre Dittgen's avatar
Pierre Dittgen committed
39
        return '' if val is None else str(val)
40

41 42
    header = None
    rows = []
Pierre Dittgen's avatar
Pierre Dittgen committed
43
    nb_rows = 0
44

45
    options = {}
46
    if source.format == "csv":
47
        options['delimiter'] = csv_helpers.detect_dialect(source.source, format=source.format, scheme=source.scheme,
48
                                                          custom_loaders=custom_loaders).delimiter
49
    with tabulator.Stream(source.source, format=source.format, scheme=source.scheme, custom_loaders=custom_loaders,
50
                          **options) as stream:
51 52
        for row in stream:
            if header is None:
53
                header = ['' if v is None else v for v in row]
54
            else:
55
                rows.append(list(map(stringify, row)))
Pierre Dittgen's avatar
Pierre Dittgen committed
56
                nb_rows += 1
57
    preview_rows_nb = min(preview_rows_nb, nb_rows)
58 59
    return {'header': header,
            'rows_nb': nb_rows,
60 61 62
            'data_rows': rows,
            'preview_rows_nb': preview_rows_nb,
            'preview_rows': rows[:preview_rows_nb]}
63 64


Pierre Dittgen's avatar
Pierre Dittgen committed
65 66
def improve_errors(errors):
    """Add context to errors, converts markdown content to HTML"""
67

Pierre Dittgen's avatar
Pierre Dittgen committed
68 69
    def improve_err(err):
        """Adds context info based on row-nb presence and converts content to HTML"""
70

Pierre Dittgen's avatar
Pierre Dittgen committed
71 72 73 74
        # Context
        update_keys = {
            'context': 'body' if 'row-number' in err and not err['row-number'] is None else 'table',
        }
Pierre Dittgen's avatar
Pierre Dittgen committed
75

Pierre Dittgen's avatar
Pierre Dittgen committed
76
        # markdown to HTML (with default values for 'title' and 'content')
Pierre Dittgen's avatar
Pierre Dittgen committed
77

Pierre Dittgen's avatar
Pierre Dittgen committed
78 79 80
        # Set default title if no title
        if not 'title' in err:
            update_keys['title'] = '[{}]'.format(err['code'])
Pierre Dittgen's avatar
Pierre Dittgen committed
81

Pierre Dittgen's avatar
Pierre Dittgen committed
82 83 84 85
        # Convert message to markdown only if no content
        # => for pre-checks errors
        if 'message' in err and not 'content' in err:
            update_keys['message'] = commonmark(err['message'])
Pierre Dittgen's avatar
Pierre Dittgen committed
86

Pierre Dittgen's avatar
Pierre Dittgen committed
87 88 89
        # Else, default message
        elif not 'message' in err or err['message'] is None:
            update_keys['message'] = '[{}]'.format(err['code'])
Pierre Dittgen's avatar
Pierre Dittgen committed
90

Pierre Dittgen's avatar
Pierre Dittgen committed
91 92 93
        # Message content
        md_content = '*content soon available*' if not 'content' in err else err['content']
        update_keys['content'] = commonmark(md_content)
94

Pierre Dittgen's avatar
Pierre Dittgen committed
95
        return {**err, **update_keys}
96

Pierre Dittgen's avatar
Pierre Dittgen committed
97
    return list(map(improve_err, errors))
98 99


Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
100
def create_validata_ui_report(validata_core_report, schema_dict):
101 102 103 104 105 106
    """ Creates an error report easier to handle and display in templates:
        - only one table
        - errors are contextualized
        - error-counts is ok
        - errors are grouped by lines
        - errors are separated into "structure" and "body"
107
        - error messages are improved
108
    """
Pierre Dittgen's avatar
Pierre Dittgen committed
109
    report = copy.deepcopy(validata_core_report)
110 111 112 113 114 115 116 117 118

    # One table is enough
    del report['table-count']
    report['table'] = report['tables'][0]
    del report['tables']
    del report['table']['error-count']
    del report['table']['time']
    del report['table']['valid']
    del report['valid']
119 120 121
    # use _ instead of - to ease information picking in jinja2 template
    report['table']['row_count'] = report['table']['row-count']

Pierre Dittgen's avatar
Pierre Dittgen committed
122 123 124 125
    # Handy col_count info
    headers = report['table'].get('headers', [])
    report['table']['col_count'] = len(headers)

Pierre Dittgen's avatar
Pierre Dittgen committed
126
    # Computes column info
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
127 128
    fields_dict = {f['name']: (f.get('title', 'titre non défini'), f.get('description', ''))
                   for f in schema_dict.get('fields', [])}
Pierre Dittgen's avatar
Pierre Dittgen committed
129 130 131
    report['table']['headers_title'] = [fields_dict[h][0] if h in fields_dict else 'colonne inconnue' for h in headers]
    report['table']['headers_description'] = [fields_dict[h][1]
                                              if h in fields_dict else 'Cette colonne n\'est pas définie dans le schema' for h in headers]
132

133
    # Provide better (french) messages
Pierre Dittgen's avatar
Pierre Dittgen committed
134 135
    errors = improve_errors(report['table']['errors'])
    del report['table']['errors']
136

137 138 139 140 141 142 143
    # Count errors
    report['error_count'] = len(errors)
    del report['error-count']

    # Then group them in 2 groups : structure and body
    report['table']['errors'] = {'structure': [], 'body': []}
    for err in errors:
144
        if err['tag'] == 'structure':
145 146 147 148
            report['table']['errors']['structure'].append(err)
        else:
            report['table']['errors']['body'].append(err)

Pierre Dittgen's avatar
Pierre Dittgen committed
149
    # Checks if there are structure errors different to invalid-column-delimiter
Pierre Dittgen's avatar
Pierre Dittgen committed
150 151 152
    structure_errors = report['table']['errors']['structure']
    report['table']['do_display_body_errors'] = len(structure_errors) == 0 or \
        all(err['code'] == 'invalid-column-delimiter' for err in structure_errors)
153

Pierre Dittgen's avatar
Pierre Dittgen committed
154 155 156 157 158 159 160 161
    # Checks if a column comparison is needed
    header_errors = ('missing-headers', 'extra-headers', 'wrong-headers-order')
    structure_errors = [{**err, 'in_column_comp': err['code'] in header_errors} for err in structure_errors]
    report['table']['errors']['structure'] = structure_errors
    column_comparison_needed = any(err['in_column_comp'] == True for err in structure_errors)
    column_comparison_table = []
    if column_comparison_needed:
        column_comparison_table = []
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
162
        field_names = [f['name'] for f in schema_dict.get('fields', [])]
163
        has_case_errors = False
Pierre Dittgen's avatar
Pierre Dittgen committed
164 165
        for t in itertools.zip_longest(headers, field_names, fillvalue=''):
            status = 'ok' if t[0] == t[1] else 'ko'
166 167
            if not has_case_errors and status == 'ko' and t[0].lower() == t[1].lower():
                has_case_errors = True
Pierre Dittgen's avatar
Pierre Dittgen committed
168
            column_comparison_table.append((*t, status))
169 170 171 172 173
        info = {}
        info['table'] = column_comparison_table
        info['has_missing'] = len(headers) < len(field_names)
        info['has_case_errors'] = has_case_errors
        report['table']['column_comparison_info'] = info
Pierre Dittgen's avatar
Pierre Dittgen committed
174 175
    report['table']['column_comparison_needed'] = column_comparison_needed

Pierre Dittgen's avatar
Pierre Dittgen committed
176 177 178 179
    # Group body errors by row id
    rows = []
    current_row_id = 0
    for err in report['table']['errors']['body']:
180 181
        if not 'row-number' in err:
            print('ERR', err)
Pierre Dittgen's avatar
Pierre Dittgen committed
182 183 184 185 186 187 188 189 190 191 192 193 194
        row_id = err['row-number']
        del err['row-number']
        del err['context']
        if row_id != current_row_id:
            current_row_id = row_id
            rows.append({'row_id': current_row_id, 'errors': {}})

        column_id = err.get('column-number')
        if column_id is not None:
            del err['column-number']
            rows[-1]['errors'][column_id] = err
        else:
            rows[-1]['errors']['row'] = err
Pierre Dittgen's avatar
Pierre Dittgen committed
195
    report['table']['errors']['body_by_rows'] = rows
Pierre Dittgen's avatar
Pierre Dittgen committed
196

197 198 199 200 201 202 203 204 205
    # Sort by error names in statistics
    stats = report['table']['error-stats']
    code_title_map = messages.ERROR_MESSAGE_DEFAULT_TITLE
    for key in ('structure-errors', 'value-errors'):
        # convert dict into tuples with french title instead of error code
        # and sorts by title
        stats[key]['count-by-code'] = sorted([(code_title_map.get(k, k), v) for k, v in stats[key]['count-by-code'].items()],
                                             key=itemgetter(0))

Pierre Dittgen's avatar
Pierre Dittgen committed
206 207 208
    return report


Pierre Dittgen's avatar
Pierre Dittgen committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
def compute_badge_message_and_color(badge):
    """Computes message and color from badge information"""
    structure = badge['structure']
    body = badge.get('body')

    # Bad structure, stop here
    if structure == 'KO':
        return (
            'structure invalide', 'red')

    # No body error
    if body == 'OK':
        return ('structure invalide', 'orange') if structure == 'WARN' else ('valide', 'green')

    # else compute quality ratio percent
Christophe Benz's avatar
Christophe Benz committed
224
    p = (1 - badge['error-ratio']) * 100.0
Pierre Dittgen's avatar
Pierre Dittgen committed
225 226 227 228 229 230 231 232
    msg = 'cellules valides : {:.1f}%'.format(p)
    return (msg, 'red') if body == 'KO' else (msg, 'orange')


def get_badge_url_and_message(badge):
    """Gets badge url from badge information"""

    msg, color = compute_badge_message_and_color(badge)
233 234
    return ('{}static/v1.svg?label=Validata&message={}&color={}'.format(
        config.SHIELDS_IO_BASE_URL, quote_plus(msg), color), msg)
Pierre Dittgen's avatar
Pierre Dittgen committed
235 236


Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
237
def validate(schema_url, source: ValidataSource):
238 239
    """ Validate source and display report """

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
240 241 242 243 244 245
    if config.API_VALIDATE_ENDPOINT is None:
        flash_error("No Validate endpoint defined :-(")
        return redirect(url_for("custom_validator"))
    api_url = config.API_VALIDATE_ENDPOINT
    headers = {"Accept": "application/json"}

246
    try:
247

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
248 249 250 251 252 253 254 255 256 257 258 259
        if source.is_url():
            params = {
                "schema": schema_url,
                "url": source.get_url(),
            }
            req = requests.get(api_url, params=params, headers=headers)

        else:
            files = {'file': (source.name, io.BytesIO(source.source))}
            data = {'schema': schema_url}
            req = requests.post(api_url, data=data, files=files, headers=headers)

Pierre Dittgen's avatar
Pierre Dittgen committed
260 261 262 263 264 265 266
        # 400
        if req.status_code == 400:
            json_response = req.json()
            flash_error("Une erreur est survenue durant la validation: {}"
                        .format(json_response.get('message')))
            return redirect(url_for("home"))

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
267
        if not req.ok:
Pierre Dittgen's avatar
Pierre Dittgen committed
268
            flash_error("Un erreur s'est produite côté serveur :-(")
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
269
            return redirect(url_for("home"))
270

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
271 272 273
        json_response = req.json()
        validata_core_report = json_response['report']
        schema_dict = json_response['schema']
274

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
275 276 277 278
    except requests.ConnectionError as err:
        logging.exception(err)
        flash_error(str(err))
        return redirect(url_for('home'))
279

Pierre Dittgen's avatar
Pierre Dittgen committed
280
    # Computes badge from report and badge configuration
281
    badge = compute_badge(validata_core_report, config.BADGE_CONFIG)
Pierre Dittgen's avatar
Pierre Dittgen committed
282 283
    badge_url, badge_msg = get_badge_url_and_message(badge)

284 285 286 287 288 289
    source_errors = [err for err in validata_core_report['tables'][0]['errors'] if err['code'] == 'source-error']
    if source_errors:
        err = source_errors[0]
        msg = "l'encodage du fichier est invalide. Veuillez le corriger" if 'charmap' in err[
            'message'] else err['message']
        flash_error('Erreur de source : {}'.format(msg))
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
290
        return redirect(url_for('custom_validator'))
291

292
    source_data = extract_source_data(source)
293

Pierre Dittgen's avatar
Pierre Dittgen committed
294
    # handle report date
295
    report_datetime = datetime.fromisoformat(validata_core_report['date']).astimezone()
296

Pierre Dittgen's avatar
Pierre Dittgen committed
297
    # Enhance validata_core_report
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
298
    validata_report = create_validata_ui_report(validata_core_report, schema_dict)
Pierre Dittgen's avatar
Pierre Dittgen committed
299

Pierre Dittgen's avatar
Pierre Dittgen committed
300
    # Display report to the user
Pierre Dittgen's avatar
Pierre Dittgen committed
301 302
    validator_form_url = url_for("custom_validator")+'?schema='+quote_plus(schema_url)
    val_info, validator_title = compute_validator_info(schema_url)
303
    return render_template('validation_report.html', title='Rapport de validation',
Pierre Dittgen's avatar
Pierre Dittgen committed
304
                           val_info=val_info, report=validata_report,
Pierre Dittgen's avatar
Pierre Dittgen committed
305
                           schema_url=schema_url,
306
                           validation_date=report_datetime.strftime('le %d/%m/%Y à %Hh%M'),
307
                           source=source, source_type=source.type, source_data=source_data,
308
                           print_mode=request.args.get('print', 'false') == 'true',
Pierre Dittgen's avatar
Pierre Dittgen committed
309
                           badge_url=badge_url, badge_msg=badge_msg,
310
                           report_str=json.dumps(validata_report, sort_keys=True, indent=2),
Pierre Dittgen's avatar
Pierre Dittgen committed
311
                           breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'},
Pierre Dittgen's avatar
Pierre Dittgen committed
312
                                        {'url': validator_form_url, 'title': validator_title},
Pierre Dittgen's avatar
Pierre Dittgen committed
313
                                        ])
314 315


316 317
def bytes_data(f):
    """ Gets bytes data from Werkzeug FileStorage instance """
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
318
    iob = io.BytesIO()
319 320 321 322 323
    f.save(iob)
    iob.seek(0)
    return iob.getvalue()


324 325 326 327 328 329
# Routes


@app.route('/')
def home():
    """ Home page """
Christophe Benz's avatar
Christophe Benz committed
330
    flash_warning('Ce service est fourni en mode beta - certains problèmes peuvent subsister - nous mettons tout en œuvre pour améliorer son fonctionnement en continu.')
Pierre Dittgen's avatar
Pierre Dittgen committed
331
    return render_template('home.html', title='Accueil', config=ui_config)
332 333 334 335 336 337 338 339


@app.route('/validators')
def validators():
    """ No validators page """
    return redirect(url_for('home'))


Pierre Dittgen's avatar
Pierre Dittgen committed
340 341
@app.route('/pdf')
def pdf_report():
342
    """PDF report generation"""
343
    err_prefix = 'Erreur de génération du rapport PDF'
344 345 346

    url_param = request.args.get('url')
    if not url_param:
347
        flash_error(err_prefix + ': URL non fournie')
Pierre Dittgen's avatar
Pierre Dittgen committed
348
        return redirect(url_for('home'))
349

Pierre Dittgen's avatar
Pierre Dittgen committed
350 351 352 353 354 355 356
    schema_param = request.args.get('schema')
    if not schema_param:
        flash_error(err_prefix + ': URL de schema non fournie')
        return redirect(url_for('home'))

    validation_url = '{}?input=url&print=true&url={}&schema={}'.format(url_for('custom_validator', _external=True),
                                                                       quote_plus(url_param), quote_plus(schema_param))
357

Pierre Dittgen's avatar
Pierre Dittgen committed
358
    with tempfile.NamedTemporaryFile(prefix='validata_{}_report_'.format(datetime.now().timestamp()), suffix='.pdf') as tmpfile:
359
        tmp_pdf_report = Path(tmpfile.name)
360 361 362 363 364

    cmd = ['chromium', '--headless', '--disable-gpu',
           '--print-to-pdf={}'.format(str(tmp_pdf_report)), validation_url]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    if result.returncode != 0:
365 366
        flash_error(err_prefix)
        log.error("Command %r returned an error: %r", cmd, result.stdout.decode('utf-8'))
367 368
        if tmp_pdf_report.exists():
            tmp_pdf_report.unlink()
Pierre Dittgen's avatar
Pierre Dittgen committed
369
        return redirect(url_for('home'))
370

Pierre Dittgen's avatar
Pierre Dittgen committed
371
    pdf_filename = 'Rapport de validation {}.pdf'.format(datetime.now().strftime('%d-%m-%Y %Hh%M'))
372
    response = make_response(tmp_pdf_report.read_bytes())
Pierre Dittgen's avatar
Pierre Dittgen committed
373
    response.headers.set('Content-disposition', 'attachment', filename=pdf_filename)
374 375 376 377 378 379 380 381
    response.headers.set('Content-type', 'application/pdf')
    response.headers.set('Content-length', tmp_pdf_report.stat().st_size)

    tmp_pdf_report.unlink()

    return response


Pierre Dittgen's avatar
Pierre Dittgen committed
382 383 384 385 386 387 388 389 390 391
def compute_validator_info(schema_url):
    """Factor code for validator form page"""
    val_info = None
    title = "Schéma personnalisé"
    if schema_url in schema_info_map:
        val_info = schema_info_map.get(schema_url)
        title = "Schéma « {} »".format(val_info['title'])
    return val_info, title


Pierre Dittgen's avatar
Pierre Dittgen committed
392
@app.route('/validators/form', methods=['GET', 'POST'])
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
393 394 395 396 397 398 399
def custom_validator():
    """ Validator page """

    if config.API_VALIDATE_ENDPOINT is None:
        flash_error("URL de connexion à l'API non indiquée :-(")
        return redirect(url_for('home'))

Pierre Dittgen's avatar
Pierre Dittgen committed
400 401 402 403
    def validation_form_url(schema_url):
        """Computes validation form url with schema URL parameter"""
        return "{}?schema={}".format(url_for('custom_validator'), quote_plus(schema_url))

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
404 405 406 407 408 409
    if request.method == 'GET':

        input_param = request.args.get('input')
        url_param = request.args.get("url")
        schema_param = request.args.get("schema")

Pierre Dittgen's avatar
Pierre Dittgen committed
410 411 412 413
        if schema_param is None or schema_param == '':
            flash_error("Vous n'avez pas indiqué d'url de schéma")
            return redirect(url_for('home'))

Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
414 415
        # First form display
        if input_param is None:
Pierre Dittgen's avatar
Pierre Dittgen committed
416 417 418 419

            val_info, title = compute_validator_info(schema_param)
            return render_template('validation_form.html', title=title,
                                   val_info=val_info, schema_url=schema_param,
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
420 421 422 423 424 425
                                   breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'}, ])

        # Process URL
        else:
            if url_param is None or url_param == '':
                flash_error("Vous n'avez pas indiqué d'url à valider")
Pierre Dittgen's avatar
Pierre Dittgen committed
426
                return redirect(validation_form_url(schema_param))
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
427 428 429 430 431
            try:
                return validate(schema_param, ValidataSource('url', url_param, url_param))
            except tabulator.exceptions.FormatError as e:
                flash_error('Erreur : Format de ressource non supporté')
                log.info(e)
Pierre Dittgen's avatar
Pierre Dittgen committed
432
                return redirect(validation_form_url(schema_param))
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
433 434 435
            except tabulator.exceptions.HTTPError as e:
                flash_error('Erreur : impossible d\'accéder au fichier source en ligne')
                log.info(e)
Pierre Dittgen's avatar
Pierre Dittgen committed
436
                return redirect(validation_form_url(schema_param))
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
437 438 439 440 441

    else:  # POST
        schema_param = request.form.get('schema')
        if schema_param is None:
            flash_error('Aucun schéma défini')
Pierre Dittgen's avatar
Pierre Dittgen committed
442 443 444 445 446 447
            return redirect(url_for('home'))

        input_param = request.form.get('input')
        if input_param is None:
            flash_error("Vous n'avez pas indiqué de fichier à valider")
            return redirect(validation_form_url(schema_param))
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
448 449 450 451 452 453

        # File validation
        if input_param == 'file':
            f = request.files.get('file')
            if f is None:
                flash_warning("Vous n'avez pas indiqué de fichier à valider")
Pierre Dittgen's avatar
Pierre Dittgen committed
454
                return redirect(validation_form_url(schema_param))
Pierre Dittgen's avatar
wip  
Pierre Dittgen committed
455 456 457 458 459

            b_content = bytes_data(f)
            return validate(schema_param, ValidataSource('file', f.filename, b_content))

        return 'Bizarre, vous avez dit bizarre ?'