Ejemplo n.º 1
0
class QueryToolController(base.BaseController):

    ctrl = 'ckanext.querytool.controllers.querytool:QueryToolController'

    def groups(self):
        '''
        Lists all available groups
        :return: base template
        '''

        context = _get_context()

        try:
            check_access('querytool_list', context)
        except NotAuthorized:
            abort(403, _('Not authorized to see this page'))

        return render('querytool/admin/base_groups.html',
                      extra_vars={'msg': 'Groups'})

    def list_by_group(self, group):
        '''

        :return: query list by group template
        '''

        context = _get_context()

        try:
            check_access('querytool_list', context)

            querytools = _get_action('querytool_list_by_group',
                                     {'group': group})
        except NotAuthorized:
            abort(403, _('Not authorized to see this page'))

        return render('querytool/admin/base_list.html',
                      extra_vars={
                          'data': querytools})

    def list_other(self):
        '''

        :return: list querytools that don't belong to
         any of the existing groups
        '''
        context = _get_context()
        groups = helpers.get_groups()

        try:
            check_access('querytool_list', context)
            querytools = _get_action('querytool_list_other',
                                     {'groups': groups})
        except NotAuthorized:
            abort(403, _('Not authorized to see this page'))

        return render('querytool/admin/base_list.html',
                      extra_vars={
                          'data': querytools})

    def delete(self, querytool):
        '''
            Delete query tool

        :return: querytools list template page

        '''

        context = _get_context()

        name = querytool[1:]

        try:
            check_access('querytool_delete', context, {'name': name})
        except NotAuthorized:
            abort(403, _('Not authorized to see this page'))

        data_dict = {
            'name': name
        }
        _querytool = _get_action('querytool_get', data_dict)

        try:
            junk = _get_action('querytool_delete', {'name': name})
        except NotFound:
            abort(404, _('Report not found'))

        h.flash_success(_('Report and visualizations were '
                          'removed successfully.'))

        toolkit.redirect_to('/group/' + _querytool['group'] + '/reports')

    def querytool_edit(self, querytool=None, data=None,
                       errors=None, error_summary=None):
        '''
            Create/edit query tool

        :return: query create/edit template page

        '''
        if querytool:
            querytool = querytool[1:]

        data_dict = {
            'name': querytool
        }

        context = _get_context()
        try:
            check_access('querytool_update', context, data_dict)
        except NotAuthorized:
            abort(403, _('Not authorized to see this page'))

        _querytool = _get_action('querytool_get', data_dict)

        if _querytool is None and len(querytool) > 0:
            abort(404, _('Report not found.'))

        if _querytool is None:
            _querytool = {}

        # Check if the data for this querytool still exists
        if 'dataset_name' in _querytool.keys():
            try:
                _get_action('package_show',
                            {'id': _querytool['dataset_name']})
            except NotFound:
                abort(404, _('The data used for creating this '
                             'report has been removed '
                             'by the administrator.'))

        if toolkit.request.method == 'POST' and not data:

            data = dict(toolkit.request.POST)

            group = ast.literal_eval(data['group'])
            data.pop('group')
            data['group'] = group['name']

            filters = []
            y_axis_columns = []
            related_querytools = []
            for k, v in data.items():

                if k.startswith('data_filter_name_'):
                    filter = {}
                    id = k.split('_')[-1]
                    filter['order'] = int(id)
                    filter['name'] = data['data_filter_name_{}'.format(id)]
                    filter['value'] = data['data_filter_value_{}'.format(id)]
                    # Replace & with %26 to fix the error for graphs
                    # not being generated for values with & in them
                    filter['value'] = filter['value'].replace('&','%26')
                    filter['alias'] = data['data_filter_alias_{}'.format(id)]
                    filter['visibility'] = \
                        data['data_filter_visibility_{}'.format(id)]

                    filters.append(filter)
                elif k.startswith('y_axis_name_'):
                    id = k.split('_')[-1]
                    alias = data.get('y_axis_alias_%s' % id, '')
                    y_axis_columns.append({'name': v, 'alias': alias})

                elif k.startswith('related_querytool_'):
                    related_querytool = {}
                    id = k.split('_')[-1]
                    related_querytool['order'] = int(id)
                    related_querytool['name'] = \
                        data['related_querytool_{}'.format(id)]
                    related_querytools.append(related_querytool)

            if any(filters):
                _querytool['filters'] = json.dumps(filters)
                sql_string = helpers.create_query_str(data['chart_resource'],
                                                      filters)
            else:
                _querytool['filters'] = ''
                sql_string = ''

            if 'private' not in data.keys():
                _querytool['private'] = True

            if any(related_querytools):
                _querytool['related_querytools'] = json.\
                    dumps(related_querytools)
            else:
                _querytool['related_querytools'] = ''

            _querytool.update(data)
            _querytool['querytool'] = querytool
            _querytool['sql_string'] = sql_string
            _querytool['y_axis_columns'] = (
                json.dumps(y_axis_columns) if y_axis_columns else '')
            _querytool['owner_org'] = data['owner_org']
            _querytool['icon'] = data['icon']
            _querytool['selection_label'] = data.get('selection_label')
            _querytool['report_caption'] = data.get('report_caption')

            try:
                junk = _get_action('querytool_update', _querytool)
                h.flash_success(_('Data Successfully updated.'))
            except ValidationError, e:
                errors = e.error_dict
                error_summary = e.error_summary
                return self.querytool_edit('/' + querytool, _querytool,
                                           errors, error_summary)
            if 'save_data' in data.keys():
                # redirect to querytools group
                toolkit.redirect_to('/'+h.lang()+'/group/'+_querytool['group']+'/reports')

            else:
                # redirect to manage visualisations
                url = h.url_for('querytool_edit_visualizations',
                                querytool='/' + _querytool['name'])
                h.redirect_to(url)

        if not data:
            data = _querytool

        if 'filters' in data and len(data['filters']) > 0:
            data['filters'] = json.loads(data['filters'])
            data['filters'].sort(key=itemgetter('order'))

        if 'related_querytools' in data \
                and len(data['related_querytools']) > 0:
            data['related_querytools'] = json.loads(data['related_querytools'])
            data['related_querytools'].sort(key=itemgetter('order'))

        if 'chart_resource' in data:
            resource_fields = helpers.\
                get_resource_columns(data['chart_resource'])
            c.active_filters = ','.join(resource_fields)
            c.resource_id = data['chart_resource']

        errors = errors or {}
        error_summary = error_summary or {}

        if _querytool.get('y_axis_columns'):
            _querytool['y_axis_columns'] = helpers.parse_y_axis_columns(
                _querytool.get('y_axis_columns'))
            _querytool['y_axis_names'] = map(
                lambda column: column['name'],
                _querytool['y_axis_columns'])

        vars = {'data': data, 'errors': errors,
                'error_summary': error_summary,
                'querytool': _querytool}

        return render('querytool/admin/base_edit_data.html',
                      extra_vars=vars)
Ejemplo n.º 2
0
        # Add slug to filters
        main_filters = []
        for filter in json.loads(data['main_filters']):
            filter['slug'] = helpers.slugify(filter.get('alias', ''))
            main_filters.append(filter)
        data['main_filters'] = json.dumps(main_filters)

        # This is required in order to exclude
        # main filters in chart item filter options
        main_filters_names = []
        for filter in main_filters:
            main_filters_names.append(filter['name'])
        data['main_filters_names'] = ','.join(main_filters_names)

        data['y_axis_columns'] = helpers.parse_y_axis_columns(
            data.get('y_axis_columns'))

        data['y_axis_options'] = map(
            lambda column: {'value': column['name'], 'text': column['alias']},
            data['y_axis_columns'])

        # We need y_axis_columns names in comma separated
        # format because ajax snippets only support String parameters
        # This parameter is used for removing
        # Y axis values from the rest of the
        #  filtering options and the X axis values in viz items
        data['y_axis_values'] = ','.join(map(
            lambda column: column['name'],
            data['y_axis_columns']))

        vars = {'data': data, 'errors': errors,