def get_syrx_data(config):
    """
    Gets the data for the syrx number in config and returns a kendo-formatted object of the data
    :param config: EquipmentReport
    :return:
    """
    report_series_dict = {}
    benchmark_series_dict = {}

    if len(config.syrx_nums) > 1:
        target_unit = "mmbtu"
    else:
        target_unit = None

    for syrx_num in config.syrx_nums:
        # get the equipment point
        ep = g.uow.equipment.get_equipment_point_by_syrx_num(syrx_num)

        if not target_unit:
            target_unit = ep['units'].lower()

        conversion_factor = SharedReporting.get_component_point_conversion(ep['units'].lower(), 'mmbtu')

        syrx_series = get_consumption_data_for_year(syrx_num, config.report_year, config.start_month, config.end_month,
                                                    conversion_factor)
        # add to the existing series
        add_to_new_series_data(report_series_dict, syrx_series[0]['data'])

        syrx_series_benchmark = get_consumption_data_for_year(syrx_num, config.comparison_year, config.start_month,
                                                              config.end_month, conversion_factor)

        # add to the existing series
        add_to_new_series_data(benchmark_series_dict, syrx_series_benchmark[0]['data'])

    report_difference_list, benchmark_difference_list = calculate_difference_equipment_report(report_series_dict,
                                                                                              benchmark_series_dict)

    consumption_series_list = convert_dict_to_list(report_series_dict)
    consumption_series_list[0]['name'] = 'Reported Consumption'
    benchmark_series_list = convert_dict_to_list(benchmark_series_dict)
    consumption_series_list += benchmark_series_list
    consumption_series_list[1]['name'] = 'Benchmark Consumption'

    difference_series_list = convert_dict_to_list(report_difference_list)
    difference_series_list[0]['name'] = 'Reported Consumption'
    difference_series_list += convert_dict_to_list(benchmark_difference_list)
    difference_series_list[1]['name'] = 'Benchmark Consumption'

    chart_info = ComponentDifferenceDataContainer()
    chart_info.component_description = ""
    chart_info.title = "Intensity"
    chart_info.consumption_data = consumption_series_list
    chart_info.difference_data = difference_series_list
    chart_info.x_axis_label = "Temperature (F)"
    chart_info.y_axis_label = "Energy Consumption (" + SharedReporting.get_y_unit_label(target_unit.lower()) + ")"
    return chart_info
def get_comparison_chart_data(config):
    """
    Gets a list of the series used for the comparison report charts
    :param config: ComponentReportingComparisonConfiguration
    :return: TotalEnergyDataContainer that holds all information for the chart
    """
    series_list = []
    for entity in config.component_ids:
        # get label from the entity
        label = get_label_for_entity(entity)

        # get actual component_id from the list
        syrx_nums = get_syrx_nums_from_entity(entity)

        # combine the comparison year with the historical mode years
        all_years = list(set([config.comparison_year] + config.historical_years))
        for year in all_years:
            new_series_data = {}
            for syrx_num in syrx_nums:
                # get the equipment point by syrx num
                ep = g.uow.equipment.get_equipment_point_by_syrx_num(syrx_num)

                # get the series data for each point
                syrx_series = g.uow.compiled_point_records.get_data_for_syrx_nums([syrx_num], year, 1, 12)

                if len(syrx_series) > 0:
                    # convert the data to the new values
                    conversion_factor = SharedReporting.get_component_point_conversion(ep['units'].lower(), config.unit)

                    convert_data_to_btu_unit(syrx_series[0]['data'], conversion_factor)

                    # add to the new_series_data
                    add_to_new_series_data(new_series_data, syrx_series[0]['data'])

            if len(new_series_data) > 0:
                new_series_data_list = []
                # change the data from a dictionary to list
                for key in sorted(new_series_data.keys()):
                    new_series_data_list.append([key, new_series_data[key]])

                # overwrite the point name with the component name
                new_series = [{"name": None,
                               "data": new_series_data_list}]
                new_series[0]["name"] = label + " - " + str(year)

                series_list += new_series

    chart_info = TotalEnergyDataContainer()
    chart_info.title = "Intensity"
    chart_info.data = series_list
    chart_info.x_axis_label = "Temperature (F)"
    chart_info.y_axis_label = "Energy Consumption (" + SharedReporting.get_y_unit_label(config.unit) + ")"

    return chart_info
def generate_consumption_report(config, y_units, y_unit_map, total_energy_chart_info, submitted_by_user, submitted_to, g):
    """
    Gathers data and generates a pdf from it
    :param config:
    :param y_units:
    :param y_unit_map:
    :param total_energy_chart_info:
    :param submitted_by_user:
    :param submitted_to:
    :param g:
    :return:
    """
    # collect information for intensity chart
    intensity_chart_info = get_intensity_chart_data(config.entity_ids, config.account_type, config.report_year,
                                                    config.comparison_type, config.demand_type, g)

    year_group_grouping = {}
    # loop through every SIC code in the configuration and get their consumption chart data
    for code in config.entity_ids:
        # get the sic code and it's group descendants
        sic_code = g.uow.sic.get_by_code(code)
        group_descendants = g.uow.sic.get_group_descendants(code)

        # get all accounts for the SIC code
        accounts = []
        for gr in group_descendants:
            accounts += SharedReporting.get_accounts_for_group(gr, config.account_type, config.report_year,
                                                               config.comparison_type, config.demand_type, g)

        # get data associated with each account
        data = SharedReporting.get_total_energy_chart_data_pdf(accounts, config.report_year, config.benchmark_year, config.demand_type,
                                               y_units, y_unit_map, g)
        total_energy_chart_info.data.append({'entity': sic_code['name'], 'data': data['chart_data']})

        for year in data['year_data']:
            # check if the year has not been added to the group before
            if not year in year_group_grouping:
                # the year hasn't been added to the grouping, so just create a new entry in the dictionary
                year_group_grouping[year] = [{'entity': sic_code['name'] + ' (' + str(year) + ')',
                                              'data': data['year_data'][year]}]
            else:
                # append the entry
                year_group_grouping[year].append({'entity': sic_code['name'] + ' (' + str(year) + ')',
                                                  'data': data['year_data'][year]})

    # generate report data and get the report path
    report_path = DataReports.generate_consumption_report(config.report_year, config.benchmark_year,
                                                          intensity_chart_info, total_energy_chart_info,
                                                          year_group_grouping, submitted_by_user, submitted_to,
                                                          SharedReporting.get_y_unit_label(y_units))
    return report_path
def construct_row(syrx_num, component_values, unit):
    """
    Constructs a row for the table
    :param syrx_num: syrx_num that is being reported on
    :param component_values: dictionary containing ppsn, sum_value, and sum_hours_in_record
    :param unit: Unit the result should be in
    :return:
    """
    equipment_point = g.uow.equipment.get_equipment_point_by_syrx_num(syrx_num)
    equipment = g.uow.equipment.get_by_id(equipment_point['equipment_id'])
    component = g.uow.components.get_by_id(equipment_point['component_id'])
    row_dict = {
        'row': {
            'equipment_name':equipment.name, 'component_id': component.num,
            'description': equipment_point['point_code'],
            'units': SharedReporting.get_y_unit_label(unit)
        },
        'ppsn': component_values['ppsn'],
        'hours': component_values['sum_hours_in_record'],
        'consumption': component_values['sum_value'],
        'component_id': component.id,
        'syrx_num': syrx_num,
        'conversion_factor': None}
    return row_dict
def get_report(config):
    report_name = "DefaultReportName"
    report_path = ""

    # make sure submitted_to isn't empty
    if not config.submitted_to:
        abort(400)

    submitted_by_user = g.uow.users.get_user_by_id(session["current_user"]["id"])
    submitted_to = config.submitted_to

    # get submitted_by and submitted_to
    submitted_by_user, submitted_to = SharedReporting.get_submitted_contacts(submitted_by_user, submitted_to, g)

    total_energy_chart_info = TotalEnergyDataContainer()

    # determine the x units
    x_units = "F"
    total_energy_chart_info.x_axis_label = "Temperature (" + x_units + ")"
    if config.comparison_type == "dewpt":
        x_units = "Dewpt"
        total_energy_chart_info.x_axis_label = "Dewpt"
    elif config.comparison_type == "enthalpy":
        x_units = "Enthalpy"
        total_energy_chart_info.x_axis_label = "Enthalpy"

    # get actual y units to send back, and get their equivalent column in the database
    # then call the proper report function determined by config.report_type
    if config.report_type == "consumption":
        report_name = "Consumption_Report"
        if config.account_type.lower() == "electric":
            y_units = config.electric_units
            y_unit_map = 'sum_btu'
            total_energy_chart_info.title = 'Total Energy Usage - Electric'
        elif config.account_type.lower() == 'gas':
            y_units = config.gas_units
            y_unit_map = 'sum_btu'
            total_energy_chart_info.title = 'Total Energy Usage - Gas'
        else:
            y_units = config.btu_units
            y_unit_map = "sum_btu"
            total_energy_chart_info.title = 'Total Energy Usage'
        total_energy_chart_info.y_axis_label = 'Average Energy Usage (' + SharedReporting.get_y_unit_label(y_units) + ')'

        # generate consumption report
        report_path = generate_consumption_report(config, y_units, y_unit_map, total_energy_chart_info, submitted_by_user, submitted_to, g)
    elif config.report_type == "variance":
        report_name = "Variance Report"
        if config.account_type == "electric":
            y_units = config.electric_units
        elif config.account_type == "gas":
            y_units = config.gas_units
        else:
            y_units = config.btu_units
        y_unit_map = "sum_btu"
        report_path = generate_variance_report(config, y_units, y_unit_map, submitted_by_user, submitted_to, g)
    elif config.report_type == "kvar":
        report_name = "kVArh"
        y_units = "kvar"
        y_unit_map = "sum_kvar"
        total_energy_chart_info.y_axis_label = "Average Electric Usage (kVar)"
        total_energy_chart_info.title = "kVar"
        report_path = generate_kvarh_report(config, y_units, y_unit_map, total_energy_chart_info, submitted_by_user, submitted_to, g)
    elif config.report_type == "text":
        report_name = "Consumption Text Report"
        report_path = generate_consumptiontext_report(config, submitted_by_user, g)
    elif config.report_type == "kva":
        report_name = "kVah"
        y_units = "kva"
        y_unit_map = "kva"
        total_energy_chart_info.y_axis_label = "Average Electric Usage (kVa)"
        total_energy_chart_info.title = "kVa"
        report_path = generate_kvah_report(config, y_units, y_unit_map, total_energy_chart_info, submitted_by_user, submitted_to, g)
    elif config.report_type == "powerfactor":
        report_name = "Power Factor"
        y_units = "pf"
        y_unit_map = "pf"
        total_energy_chart_info.y_axis_label = "Average Power Factor"
        total_energy_chart_info.title = "Power Factor"
        report_path = generate_powerfactor_report(config, y_units, y_unit_map, total_energy_chart_info, submitted_by_user, submitted_to, g)
    elif config.report_type == "peak":
        report_name = "Peak Report"
        report_path = generate_peak_report(config, submitted_by_user, submitted_to, g)

    return send_file(report_path, mimetype='application/pdf', as_attachment=True, attachment_filename=report_name + '.pdf')
def get_total_energy_data(config):
    # determine the x units
    x_units = "F"
    x_axis_label = "Temperature (" + x_units + ")"
    if config.comparison_type == "dewpt":
        x_units = "Dewpt"
        x_axis_label = "Dewpt"
    elif config.comparison_type == "enthalpy":
        x_units = "Enthalpy"
        x_axis_label = "Enthalpy"

    # get actual y units to send back, and get their equivalent column in the database
    if config.report_type == "consumption":
        if config.account_type.lower() == "electric":
            y_units = config.electric_units
            y_unit_map = 'sum_btu'
            title = "Total Energy Usage - Electric"
        elif config.account_type.lower() == "gas":
            y_units = config.gas_units
            y_unit_map = 'sum_btu'
            title = "Total Energy Usage - Gas"
        else:
            y_units = config.btu_units
            y_unit_map = "sum_btu"
            title = "Total Energy Usage"
        y_axis_label = "Average Energy Usage (" + SharedReporting.get_y_unit_label(y_units) + ")"
    elif config.report_type == "kvar":
        y_units = "kvar"
        y_unit_map = "sum_kvar"
        y_axis_label = "Average Electric Usage (kVar)"
        title = "kVar"
    elif config.report_type == "kva":
        y_units = "kva"
        y_unit_map = "kva"
        y_axis_label = "Average Electric Usage (kVa)"
        title = "kVa"
    elif config.report_type == "powerfactor":
        y_units = "pf"
        y_unit_map = "pf"
        y_axis_label = "Average Power Factor"
        title = "Power Factor"
    else:
        abort(409)

    # make sure data exists, otherwise return an empty object
    if len(config.entity_ids) < 1 or config.entity_ids[0] is None:
        return_obj = [
            {
                'consumption-chart': [
                    {
                        'name': 'Reported Consumption',
                        'data': []
                    },
                    {
                        'name': 'Benchmark Consumption',
                        'data': []
                    }
                ],
                'difference-chart': [
                    {
                        'name': 'Reported Consumption',
                        'data': []
                    },
                    {
                        'name': 'Benchmark Consumption',
                        'data': []
                    }
                ],
                'yunits': y_units,
                'y_axis_label': y_axis_label,
                'xunits': x_units,
                'x_axis_label': x_axis_label,
                'title': title
            }
        ]
        return json.dumps(return_obj)

    # check to see if config is asking for a powerfactor report, as it requires a different function
    if config.report_type == 'powerfactor':
        data = get_pf_chart_data_web(config.entity_ids[0], config.report_year, config.benchmark_year, config.comparison_type, config.demand_type, g)
    else:
        # we only care about the first entity id since the configuration is being formatted before the request as [entity_id]
        data = get_total_energy_chart_data_web(config.entity_ids[0], config.report_year, config.benchmark_year,
                                               config.account_type, config.comparison_type, config.demand_type,
                                               y_units, y_unit_map, g)

    return_obj = [
        {
            'consumption-chart': [
                {
                    'name': 'Reported Consumption',
                    'data': data.reported_consumption
                },
                {
                    'name': 'Benchmark Consumption',
                    'data': data.benchmark_consumption
                }
            ],
            'difference-chart': [
                {
                    'name': 'Reported Consumption',
                    'data': data.diff
                },
                {
                    'name': 'Benchmark Consumption',
                    'data': data.benchmark_diff
                }
            ],
            'yunits': y_units,
            'y_axis_label': y_axis_label,
            'xunits': x_units,
            'x_axis_label': x_axis_label,
            'title': title
        }
    ]
    return json.dumps(return_obj)