Exemplo n.º 1
0
    async def post(self, request):
        session = await get_session(request)
        data = await request.post()

        user_role = await saml.get_role_id(request)

        await saml.ensure_logged_in(request)
        microservice_name = request.match_info['microservice_name']

        if 'clear' in microservice_name:
            microservice_name = microservice_name.replace('clear', '')
            await clear_stored_search_criteria(request, microservice_name)

        if microservices_permissions(user_role, microservice_name) == False:
            request['client_ip'] = request.get('client_ip', "No IP Provided")
            return await forbidden(request)

        microservice_title = microservice_name.replace("table",
                                                       " Table").title()
        page_number = get_page(request)

        try:

            field_classes = await get_fields(microservice_name, request)
            table_headers = get_table_headers(
                field_classes)  # formatted for table use
            fields_to_load = get_fields_to_load(field_classes)

            search_criteria, previous_criteria = load_search_criteria(
                data, fields_to_load)
            field_classes = load_cookie_into_fields(field_classes,
                                                    search_criteria)

            if search_criteria:
                await store_search_criteria(request, previous_criteria,
                                            fields_to_load)

            if search_criteria == '' and from_index == 'true':
                raise HTTPFound(
                    request.app.router['MicroservicesTable:get'].url_for())
            elif search_criteria == '' and from_index == 'false':
                return aiohttp_jinja2.render_template(
                    'search.html',
                    request, {'no_search_criteria': 'True'},
                    status=405)

            search_range, records_per_page = page_bounds(page_number)
            search_criteria.update(search_range)

            get_microservice_info = get_microservice_records(
                microservice_name, user_filter=search_criteria)
            get_microservice_info_json = get_microservice_info.json()

            if len(get_microservice_info_json) > 0:
                microservice_sum = get_microservice_info_json[0].get(
                    'total_records', 0)
                max_page = math.ceil(microservice_sum / records_per_page)
            else:
                microservice_sum = 0
                max_page = 1

        except ClientResponseError as ex:
            return client_response_error(ex, request)

        if get_microservice_info.status_code == 200:
            # for 0 response st no_records true

            table_records = get_table_records(
                field_classes, get_microservice_info_json
            )  # database name field ([gsuite_status,...

            result_message_str = result_message(search_range, microservice_sum,
                                                microservice_title)

            views, current_view_index = get_views(user_role, microservice_name)
            header_html = get_html(user_role, views)
            current_view = views[current_view_index]
            if (current_view.database_name == "search"):
                current_view.hide_table = False
                current_view.hide_search_criteria = True

            return {
                'views': views,
                'header_html': header_html,
                'current_view': current_view,
                'called_from_index': False,
                'Fields': field_classes,
                'result_message': result_message_str,
                'page_title': f'{microservice_title} view for: {user_role}',
                'page_number': page_number,
                'last_page_number': max_page,
                'no_records': microservice_sum == 0,
                'table_headers': table_headers,
                'table_records': table_records,
            }
        else:
            return warn_invalid_login(request)
    async def post(self, request):
        session = await get_session(request)
        data = await request.post()

        user_role = await saml.get_role_id(request)

        await saml.ensure_logged_in(request)

        if microservices_permissions(user_role, 'customsql') == False:
            request['client_ip'] = request.get('client_ip', 'No IP Provided')
            return await forbidden(request)

        clear = request.match_info['clear']
        if clear == 'clear':
            temp = session.get('custom_sql_previous_filters', {})
            final = {}
            for key in temp:
                final[key] = ''

            session['custom_sql_previous_filters'] = final

        database_names, fields = await get_database_fields(request)
        page_number = get_page(request)

        checked_boxes = session.get('custom_sql_previous_checked_fields', [])

        client_input = {}
        all_input = {}
        field_classes = []
        for db_name in fields.keys():
            current_fieldset = fields.get(db_name)  # [Field, Field, Field...]
            for field in current_fieldset:
                field_classes.append(field)

            client_input[db_name] = []
            for each_field in current_fieldset:
                unique_name_no_period = each_field.unique_name.replace('.', '')
                if unique_name_no_period in all_input:
                    each_field.previous_value = all_input.get(
                        unique_name_no_period)

                checkbox_present, filter_data = each_field.find_and_extract(
                    data)
                all_input[unique_name_no_period] = filter_data
                if (unique_name_no_period
                        in checked_boxes) or checkbox_present:

                    client_input[db_name].append(
                        {unique_name_no_period + '_text_box': filter_data})
                    checked_boxes.append(unique_name_no_period)
                    each_field.show_as_table_header = True
                    each_field.search_box_visible = True
                else:
                    each_field.show_as_table_header = False
                    each_field.search_box_visible = False

        # Load into classes
        for field in field_classes:
            unique_name_no_period = field.unique_name.replace('.', '')
            if unique_name_no_period in all_input:
                if all_input.get(unique_name_no_period) != '':
                    field.previous_value = all_input.get(unique_name_no_period)

            if unique_name_no_period in data:
                field.previous_value = data.get(unique_name_no_period)

        all_input.update(data)
        session['custom_sql_previous_filters'] = all_input
        session['custom_sql_previous_checked_fields'] = checked_boxes

        all_records = get_customsql_records(all_input)

        all_records_json = all_records.json()

        search_criteria = {}
        search_range, records_per_page = page_bounds(page_number)
        search_criteria.update(search_range)
        get_microservice_info_json = all_records_json

        if len(get_microservice_info_json) > 0:
            microservice_sum = get_microservice_info_json[0].get(
                'total_records', 0)
            max_page = math.ceil(microservice_sum / records_per_page)
        else:
            microservice_sum = 0
            max_page = 1

        table_records = get_table_records(
            field_classes,
            get_microservice_info_json,
            custom_sql=True,
        )

        result_message_str = result_message(search_range, microservice_sum,
                                            'Custom SQL')

        table_headers = get_table_headers(field_classes)

        views, current_view_index = get_views(user_role, 'customsql')
        header_html = get_html(user_role, views)
        current_view = views[current_view_index]

        return {
            'views': views,
            'header_html': header_html,
            'current_view': current_view,
            'fields': fields,
            'database_names': database_names,
            'called_from_index': 'customsql',
            'Fields': field_classes,
            'result_message': result_message_str,
            'page_title': f'Custom SQL view for: {user_role}',
            'page_number': page_number,
            'last_page_number': max_page,
            'table_headers': table_headers,
            'table_records': table_records,
        }
    async def get(self, request):

        microservice_name = request.match_info['microservice_name']
        session = await get_session(request)
        await saml.ensure_logged_in(request)

        user_role = await saml.get_role_id(request)

        if not has_download_permission(user_role, microservice_name):
            return aiohttp_jinja2.render_template('error403.html', request,
                                                  {'include_nav': True})

        try:
            search_range, records_per_page = page_bounds(1)

            get_microservice_info = get_microservice_records(
                microservice_name, user_filter=search_range)
            get_microservice_info_json = get_microservice_info.json()

            if len(get_microservice_info_json) > 0:
                microservice_sum = get_microservice_info_json[0].get(
                    'total_records', 0)

                # If there are more than 0 people in Microservice
                # then get_employee_info is set to everyone (max is total number of employees)
                search_range = {'rangeHigh': microservice_sum, 'rangeLow': 0}
                get_microservice_info = get_microservice_records(
                    microservice_name, search_range)
                get_microservice_info_json = get_microservice_info.json()

                field_classes = await get_fields(microservice_name, request)

                html_microservice_records = get_table_records(
                    field_classes,
                    get_microservice_info_json,
                    remove_html=True,
                )
                html_headers = get_table_headers(
                    field_classes,
                    remove_html=True,
                )

        except ClientResponseError as ex:
            client_response_error(ex, request)

        if get_microservice_info.status_code == 200:

            with StringIO(newline='') as csvfile:
                writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
                writer.writerow(x.get('value') for x in html_headers)

                for row in html_microservice_records:
                    writer.writerow(x.get('value') for x in row.get('tds'))

                # Create unique file name
                today = datetime.today().strftime('%Y-%m-%d')
                file_name = f'{microservice_name}{today}.csv'

                return web.Response(headers=MultiDict({
                    'Content-Disposition':
                    f'attachment; filename="{file_name}"'
                }),
                                    body=csvfile.getvalue())
        else:
            logger.warn('Database is down', client_ip=request['client_ip'])
            flash(request, NO_EMPLOYEE_DATA)
            raise HTTPFound(request.app.router['MainPage:get'].url_for())