views.py 13.6 KB
Newer Older
1 2 3 4
#!/usr/bin/env python3
"""
    Routes
"""
5
import copy
Pierre Dittgen's avatar
Pierre Dittgen committed
6
import itertools
7
import json
Christophe Benz's avatar
Christophe Benz committed
8
import logging
9
import subprocess
Christophe Benz's avatar
Christophe Benz committed
10
import tempfile
11
import time
12
from datetime import datetime
13
from io import BytesIO
14
from operator import itemgetter
15 16
from pathlib import Path
from urllib.parse import quote_plus
17

18
from backports.datetime_fromisoformat import MonkeyPatch
Pierre Dittgen's avatar
Pierre Dittgen committed
19
from commonmark import commonmark
20
from flask import make_response, redirect, render_template, request, url_for
21

22
import tabulator
23
from validata_core import csv_helpers, messages
Pierre Dittgen's avatar
Pierre Dittgen committed
24
from validata_core.loaders import custom_loaders
25
from validata_ui import app
Pierre Dittgen's avatar
Pierre Dittgen committed
26
from validata_ui.ui_util import flash_error, flash_warning
27
from validata_ui.validata_util import ValidataSource
28
from validata_ui.validate_helper import ValidatorHelper
29

30 31
MonkeyPatch.patch_fromisoformat()

Christophe Benz's avatar
Christophe Benz committed
32 33
log = logging.getLogger(__name__)

34 35

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

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

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

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


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

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

Pierre Dittgen's avatar
Pierre Dittgen committed
72 73 74 75
        # 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
76

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

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

Pierre Dittgen's avatar
Pierre Dittgen committed
83 84 85 86
        # 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
87

Pierre Dittgen's avatar
Pierre Dittgen committed
88 89 90
        # 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
91

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

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

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


Pierre Dittgen's avatar
Pierre Dittgen committed
101
def create_validata_ui_report(validata_core_report, schema):
102 103 104 105 106 107
    """ 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"
108
        - error messages are improved
109
    """
Pierre Dittgen's avatar
Pierre Dittgen committed
110
    report = copy.deepcopy(validata_core_report)
111 112 113 114 115 116 117 118 119

    # 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']
120 121 122
    # 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
123 124 125 126
    # Handy col_count info
    headers = report['table'].get('headers', [])
    report['table']['col_count'] = len(headers)

Pierre Dittgen's avatar
Pierre Dittgen committed
127
    # Computes column info
128
    schema_fields = schema.get('fields', [])
Pierre Dittgen's avatar
Pierre Dittgen committed
129 130 131 132
    fields_dict = {f['name']: (f.get('title', 'titre non défini'), f.get('description', '')) for f in schema_fields}
    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]
133

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

138 139 140 141 142 143 144
    # 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:
145
        if err['tag'] == 'structure':
146 147 148 149
            report['table']['errors']['structure'].append(err)
        else:
            report['table']['errors']['body'].append(err)

Pierre Dittgen's avatar
Pierre Dittgen committed
150
    # Checks if there are structure errors different to invalid-column-delimiter
Pierre Dittgen's avatar
Pierre Dittgen committed
151 152 153
    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)
154

Pierre Dittgen's avatar
Pierre Dittgen committed
155 156 157 158 159 160 161 162 163
    # 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 = []
        field_names = [f['name'] for f in schema_fields]
164
        has_case_errors = False
Pierre Dittgen's avatar
Pierre Dittgen committed
165 166
        for t in itertools.zip_longest(headers, field_names, fillvalue=''):
            status = 'ok' if t[0] == t[1] else 'ko'
167 168
            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
169
            column_comparison_table.append((*t, status))
170 171 172 173 174
        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
175 176
    report['table']['column_comparison_needed'] = column_comparison_needed

Pierre Dittgen's avatar
Pierre Dittgen committed
177 178 179 180
    # Group body errors by row id
    rows = []
    current_row_id = 0
    for err in report['table']['errors']['body']:
181 182
        if not 'row-number' in err:
            print('ERR', err)
Pierre Dittgen's avatar
Pierre Dittgen committed
183 184 185 186 187 188 189 190 191 192 193 194 195
        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
196
    report['table']['errors']['body_by_rows'] = rows
Pierre Dittgen's avatar
Pierre Dittgen committed
197

198 199 200 201 202 203 204 205 206
    # 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
207 208 209
    return report


210
def validate(schema_code, source: ValidataSource):
211 212
    """ Validate source and display report """

Pierre Dittgen's avatar
Pierre Dittgen committed
213
    try:
Pierre Dittgen's avatar
Pierre Dittgen committed
214
        validata_core_report = ValidatorHelper.validate(
215 216 217 218
            schema_code=schema_code,
            force_strings=True,
            **source.get_tabulator_params(),
        )
Pierre Dittgen's avatar
Pierre Dittgen committed
219 220 221
    except tabulator.exceptions.FormatError:
        flash_error('Erreur : format de fichier non supporté')
        return redirect(url_for('scdl_validator', val_code=schema_code))
222 223

    source_data = extract_source_data(source)
224

Pierre Dittgen's avatar
Pierre Dittgen committed
225
    # handle report date
226
    report_datetime = datetime.fromisoformat(validata_core_report['date']).astimezone()
227

Pierre Dittgen's avatar
Pierre Dittgen committed
228 229
    # Enhance validata_core_report
    validata_report = create_validata_ui_report(validata_core_report, ValidatorHelper.schema(schema_code).descriptor)
Pierre Dittgen's avatar
Pierre Dittgen committed
230

Pierre Dittgen's avatar
Pierre Dittgen committed
231
    # Display report to the user
Pierre Dittgen's avatar
Pierre Dittgen committed
232
    val_info = ValidatorHelper.schema_info(schema_code)
233
    return render_template('validation_report.html', title='Rapport de validation',
234
                           val_info=ValidatorHelper.schema_info(schema_code), report=validata_report,
235
                           validation_date=report_datetime.strftime('le %d/%m/%Y à %Hh%M'),
236
                           source=source, source_type=source.type, source_data=source_data,
237
                           print_mode=request.args.get('print', 'false') == 'true',
238
                           report_str=json.dumps(validata_report, sort_keys=True, indent=2),
Pierre Dittgen's avatar
Pierre Dittgen committed
239
                           breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'},
Pierre Dittgen's avatar
Pierre Dittgen committed
240 241
                                        {'url': url_for('scdl_validator', val_code=schema_code),
                                         'title': val_info['title']}])
242 243


244 245 246 247 248 249 250 251
def bytes_data(f):
    """ Gets bytes data from Werkzeug FileStorage instance """
    iob = BytesIO()
    f.save(iob)
    iob.seek(0)
    return iob.getvalue()


252 253 254 255 256 257
# Routes


@app.route('/')
def home():
    """ Home page """
Pierre Dittgen's avatar
Pierre Dittgen committed
258
    validators = ValidatorHelper.schema_info_list()
Pierre Dittgen's avatar
Pierre Dittgen committed
259
    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')
260 261 262 263 264 265 266 267 268
    return render_template('home.html', title='Accueil', validators=validators)


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


269 270 271
@app.route('/pdf/<val_code>')
def pdf_report(val_code):
    """PDF report generation"""
272
    err_prefix = 'Erreur de génération du rapport PDF'
273 274

    if not ValidatorHelper.schema_exist(val_code):
275 276
        flash_error(err_prefix + ': schéma inconnu')
        return redirect(url_for('scdl_validator', val_code=val_code))
277 278 279

    url_param = request.args.get('url')
    if not url_param:
280 281
        flash_error(err_prefix + ': URL non fournie')
        return redirect(url_for('scdl_validator', val_code=val_code))
282 283 284 285

    validation_url = '{}?input=url&print=true&url={}'.format(url_for('scdl_validator', val_code=val_code, _external=True),
                                                             quote_plus(url_param))

Christophe Benz's avatar
Christophe Benz committed
286 287
    with tempfile.NamedTemporaryFile(prefix='validata_{}_report_'.format(val_code), suffix='.pdf') as tmpfile:
        tmp_pdf_report = Path(tmpfile.name)
288 289 290 291 292

    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:
293 294
        flash_error(err_prefix)
        log.error("Command %r returned an error: %r", cmd, result.stdout.decode('utf-8'))
295 296
        if tmp_pdf_report.exists():
            tmp_pdf_report.unlink()
297
        return redirect(url_for('scdl_validator', val_code=val_code))
298

Pierre Dittgen's avatar
Pierre Dittgen committed
299 300
    pdf_filename = 'Rapport de validation {} {}.pdf'.format(val_code,
                                                            datetime.now().strftime('%d-%m-%Y %Hh%M'))
Christophe Benz's avatar
Christophe Benz committed
301
    response = make_response(tmp_pdf_report.read_bytes())
Pierre Dittgen's avatar
Pierre Dittgen committed
302
    response.headers.set('Content-disposition', 'attachment', filename=pdf_filename)
303 304 305 306 307 308 309 310
    response.headers.set('Content-type', 'application/pdf')
    response.headers.set('Content-length', tmp_pdf_report.stat().st_size)

    tmp_pdf_report.unlink()

    return response


311 312 313 314 315 316 317 318 319 320
@app.route('/validators/<val_code>', methods=['GET', 'POST'])
def scdl_validator(val_code):
    """ Validator page """

    if not ValidatorHelper.schema_exist(val_code):
        flash_error('Validateur [{}] inconnu'.format(val_code))
        return redirect(url_for('home'))

    if request.method == 'GET':

Pierre Dittgen's avatar
Pierre Dittgen committed
321
        val_info = ValidatorHelper.schema_info(val_code)
322 323 324 325
        input_param = request.args.get('input')

        # First form display
        if input_param is None or input_param not in ('url', 'example'):
326
            return render_template('validation_form.html', title=val_info['title'],
327 328 329 330 331
                                   val_info=val_info,
                                   breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'}, ])

        # Process URL
        else:
332 333
            url_param = request.args.get('url')
            if url_param is None or url_param == '':
334 335
                flash_error("Vous n'avez pas indiqué d'url à valider")
                return redirect(url_for('scdl_validator', val_code=val_code))
336
            return validate(val_code, ValidataSource('url', url_param, url_param))
337 338 339 340

    else:  # POST
        input_param = request.form.get('input')
        if input_param is None:
Pierre Dittgen's avatar
Pierre Dittgen committed
341
            flash_error('Aucun fichier à valider')
342 343 344 345 346 347 348 349
            return redirect(url_for('scdl_validator', val_code=val_code))

        # 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")
                return redirect(url_for('scdl_validator', val_code=val_code))
350

351
            return validate(val_code, ValidataSource('file', f.filename, bytes_data(f)))
352 353

        return 'Bizarre, vous avez dit bizarre ?'