diff --git a/models/enercoop_operation.py b/models/enercoop_operation.py index 03d13ef35224555e05d70ac77db3f11c198b494f..3bae7eb77f83cd08b8cc3cba39317b87682c9d58 100644 --- a/models/enercoop_operation.py +++ b/models/enercoop_operation.py @@ -3,6 +3,8 @@ from odoo import fields, models, api from datetime import datetime, timedelta +from odoo.tools import date_utils + import dateutil.parser as parser from dateutil.relativedelta import relativedelta @@ -10,77 +12,6 @@ from dateutil.relativedelta import relativedelta class EnercoopOperation(models.Model): _inherit = 'enercoop.operation' - # ------------------------------------------------------ - # Fields declaration - # ------------------------------------------------------ - - # ------------------------------------------------------ - # SQL Constraints - # ------------------------------------------------------ - - # ------------------------------------------------------ - # Default methods - # ------------------------------------------------------ - - # ------------------------------------------------------ - # Computed fields / Search Fields - # ------------------------------------------------------ - - # ------------------------------------------------------ - # Onchange / Constraints - # ------------------------------------------------------ - - # ------------------------------------------------------ - # CRUD methods (ORM overrides) - # ------------------------------------------------------ - @api.model - def graph_view(self, domain, scale, enercoop_counter_id=None): - """ - Fonction appelée lors du chargement de la vue Qweb - :param domain: représente le champ recherche de la vue - scale: type d'affichage des graphes - (day/week/month/semestre/year) - défini par le clic bouton - :return: dictionnaire pour la construction des graphes - """ - result_graph = {} - # Get the operations depending to the domain - operation_ids = self.env['enercoop.operation'].search(domain) - - if operation_ids: - # # Get date start and date end depending on type of scale if scale fill - # if scale: - # date_start, date_end = self.get_last_day(scale) - # - # # Get scale depending on the date start and date end - # if date_start and date_end: - # scale = self.get_scale(date_start, date_end) - - # Get date start and date end depending on type of scale - date_start, date_end = operation_ids.get_last_day(scale) - counter_id = None - if enercoop_counter_id: - counter_id = self.env['enercoop.counter'].search([('name', '=', enercoop_counter_id)]).id - # Get the data to display in chart - chart_data = operation_ids.get_cdc(type=scale, date_start=date_start, date_end=date_end, prm_id=counter_id) - - # Build the chart depending on data calculated - result_graph = operation_ids.chart_data_cons(chart_data) - result_graph_prod = operation_ids.chart_data_prod(chart_data) - result_graph.update(result_graph_prod) - result_graph.update({'scale': scale}) - - date_end = date_end.strftime("%d/%m/%Y") - date_min = operation_ids.get_first_day() - date_min = date_min.strftime("%d/%m/%Y") - result_graph.update({ - 'date_end': date_end, - 'date_min': date_min, - 'date_start': date_start, - }) - - return result_graph - # ------------------------------------------------------ # Actions # ------------------------------------------------------ @@ -203,19 +134,14 @@ class EnercoopOperation(models.Model): ], limit=1, order='date_slot DESC') date_end = last_record.date_slot - if scale == 'day': - date_build = str(last_record.date_slot.year) + '-' + str(last_record.date_slot.month) + '-' + str( - last_record.date_slot.day) + 'T00:00:00' - date_start = datetime.strptime(date_build, "%Y-%m-%dT%H:%M:%S") - date_end = date_start + timedelta(days=1) - elif scale == 'week': - date_start = date_end + timedelta(weeks=-1) - elif scale == 'semestre': + if scale == 'semestre': date_start = date_end - relativedelta(months=6) - elif scale == 'year': - date_start = date_end - relativedelta(years=1) - else: + elif scale == 'month': date_start = date_end - relativedelta(months=1) + date_start = date_utils.start_of(date_start, scale) + date_end = date_utils.end_of(date_start, scale) + else: + date_start = date_utils.start_of(date_end, scale) return date_start, date_end @@ -233,64 +159,250 @@ class EnercoopOperation(models.Model): date_min = first_record.date_slot return date_min - def get_scale(self, date_start, date_end): + def get_step_from_date(self, date_start, date_end): """ - Fonction retournant l'échelle à appliquer en fonction d'une date de début et une date de fin. - :return: scale: day/week/month/semestre/year + Fonction retournant le pas des courbes en fonction de 2 dates. + :return: step: hour/day/month/year """ - # Calculate delta between 2 dates - if date_start == date_end: - scale = 'day' - return scale + delta = (date_end - date_start).days + if delta <= 1: + step_display_courbe = 'hour' + step = 'hour' + elif delta <= 7: + step_display_courbe = 'day' + step = 'hour' + elif delta <= 181: + step = 'month' + step_display_courbe = 'month' + else: + step = 'year' + step_display_courbe = 'year' + + return step, step_display_courbe + + def get_cdc_by_query_cons(self, slot_type, date_start, date_end, prm_ids=None): + """ + Fonction permettant de récupérer les données pour la + construction des chart pour une ou des opérations données pour les consommateurs + :param slot_type: type de slot pour la query ('month' ou 'hour' ou 'year') + date_start: date début + date_end: date de fin + :return: un dictionnaire de données + (labels et data pour les charts à afficher) + """ + label = [] + data_autocons = [] + data_allocons = [] + data_cons = [] + data_prod = [] + data_surplus = [] + + query = """ + SELECT + date_trunc(%s, A.date_slot) AS date_slot, + (SUM( (CASE WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END) )/2) / 1000 as autocons, + (SUM( (CASE WHEN comp_data_type = 'prod' THEN A.power ELSE 0 END) )/2) / 1000 as prod, + ((SUM( (CASE WHEN comp_data_type = 'cons' THEN A.power ELSE 0 END)) - SUM(CASE WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END) ) / 2) / 1000 as allocons + FROM enercoop_enedis_cdc A + JOIN enercoop_operation E ON E.id = A.enercoop_operation_id + WHERE A.enercoop_operation_id IS NOT NULL + AND A.enercoop_operation_id IN %s + AND ( A.enercoop_counter_id IN %s OR A.comp_data_type = 'prod' ) + AND A.date_slot >= %s + AND A.date_slot < %s + GROUP BY date_trunc(%s, A.date_slot) + ORDER BY date_slot ASC; + """ + query_params = (slot_type, tuple(self.ids), tuple(prm_ids.ids), date_start, date_end, slot_type) + self.env.cr.execute(query, query_params) + raw_data = self.env.cr.fetchall() + for row in raw_data: + if slot_type == 'month' or slot_type == 'year': + data_autocons.append(int(row[1])) + data_prod.append(int(row[2])) + data_allocons.append(int(row[3])) + label.append(row[0]) + else: + data_autocons.append({'x': row[0], 'y': int(row[1])}) + data_prod.append({'x': row[0], 'y': int(row[2])}) + data_allocons.append({'x': row[0], 'y': int(row[3])}) + label.append(row[0]) + + cdc_jour = { + 'autocons': data_autocons, + 'prod': data_prod, + 'allocons': data_allocons, + 'label': label, + 'cons': data_cons, + 'surplus': data_surplus, + } + return cdc_jour + + def get_cdc_by_query(self, slot_type, date_start, date_end, prm_ids=None): + """ + Fonction permettant de récupérer les données pour la + construction des chart pour une ou des opérations données + :param slot_type: type de slot pour la query ('month' ou 'hour' ou 'year') + date_start: date début + date_end: date de fin + :return: un dictionnaire de données + (labels et data pour les charts à afficher) + """ + label = [] + data_autocons = [] + data_allocons = [] + data_cons = [] + data_prod = [] + data_surplus = [] + + if prm_ids: + query = """ + SELECT + date_trunc(%s, A.date_slot) AS date_slot, + (SUM((CASE WHEN comp_data_type = 'cons' THEN A.power ELSE 0 END)) / 2) / 1000 as cons, + (SUM((CASE WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as autocons, + (SUM((CASE WHEN comp_data_type = 'prod' THEN A.power ELSE 0 END)) / 2) / 1000 as prod, + (SUM((CASE WHEN comp_data_type = 'surplus' THEN A.power ELSE 0 END)) / 2) / 1000 as surplus, + ((SUM((CASE WHEN comp_data_type = 'cons' THEN A.power ELSE 0 END)) - SUM(CASE + WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as allocons + FROM enercoop_enedis_cdc A + JOIN enercoop_operation E ON E.id = A.enercoop_operation_id + WHERE A.enercoop_operation_id IS NOT NULL + AND A.enercoop_operation_id IN %s + AND A.enercoop_counter_id IN %s + AND A.date_slot >= %s + AND A.date_slot < %s + GROUP BY date_trunc(%s, A.date_slot) + ORDER BY date_slot ASC; + """ + query_params = (slot_type, tuple(self.ids), tuple(prm_ids.ids), date_start, date_end, slot_type) else: - delta = (date_end - date_start).days - if delta <= 7: - scale = 'week' - elif delta <= 31: - scale = 'month' - elif delta <= 180: - scale = 'semestre' + query = """ + SELECT + date_trunc(%s, A.date_slot) AS date_slot, + (SUM((CASE WHEN comp_data_type = 'cons' THEN A.power ELSE 0 END)) / 2) / 1000 as cons, + (SUM((CASE WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as autocons, + (SUM((CASE WHEN comp_data_type = 'prod' THEN A.power ELSE 0 END)) / 2) / 1000 as prod, + (SUM((CASE WHEN comp_data_type = 'surplus' THEN A.power ELSE 0 END)) / 2) / 1000 as surplus, + ((SUM((CASE WHEN comp_data_type = 'cons' THEN A.power ELSE 0 END)) - SUM(CASE + WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as allocons + FROM enercoop_enedis_cdc A + JOIN enercoop_operation E ON E.id = A.enercoop_operation_id + WHERE A.enercoop_operation_id IS NOT NULL + AND A.enercoop_operation_id IN %s + AND A.date_slot >= %s + AND A.date_slot < %s + GROUP BY date_trunc(%s, A.date_slot) + ORDER BY date_slot ASC; + """ + query_params = (slot_type, tuple(self.ids), date_start, date_end, slot_type) + self.env.cr.execute(query, query_params) + raw_data = self.env.cr.fetchall() + for row in raw_data: + if slot_type == 'month' or slot_type == 'year': + data_cons.append(int(row[1])) + data_autocons.append(int(row[2])) + data_prod.append(int(row[3])) + data_surplus.append(int(row[4])) + data_allocons.append(int(row[5])) + label.append(row[0]) else: - scale = 'year' + data_cons.append({'x': row[0], 'y': int(row[1])}) + data_autocons.append({'x': row[0], 'y': int(row[2])}) + data_prod.append({'x': row[0], 'y': int(row[3])}) + data_surplus.append({'x': row[0], 'y': int(row[4])}) + data_allocons.append({'x': row[0], 'y': int(row[5])}) + label.append(row[0]) - return scale + cdc_jour = { + 'autocons': data_autocons, + 'cons': data_cons, + 'prod': data_prod, + 'surplus': data_surplus, + 'allocons': data_allocons, + 'label': label, + } + return cdc_jour - def chart_data_cons(self, chart_data): + def get_cdc_by_query_histo(self, slot_type, date_start, date_end, prm_ids=None): + """ + Fonction permettant de récupérer les données pour la + construction des chart pour une ou des opérations données + :param slot_type: type de slot pour la query ('month' ou 'hour' ou 'year') + date_start: date début + date_end: date de fin + :return: un dictionnaire de données + (labels et data pour les charts à afficher) + """ + label_histo = [] + data_autocons_histo = [] + data_allocons_histo = [] + data_surplus_histo = [] + + if prm_ids: + query = """ + SELECT + date_trunc(%s, A.date_slot) AS date_slot, + (SUM((CASE WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as autocons, + (SUM((CASE WHEN comp_data_type = 'surplus' THEN A.power ELSE 0 END)) / 2) / 1000 as surplus, + ((SUM((CASE WHEN comp_data_type = 'cons' THEN A.power ELSE 0 END)) - SUM(CASE + WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as allocons + FROM enercoop_enedis_cdc A + JOIN enercoop_operation E ON E.id = A.enercoop_operation_id + WHERE A.enercoop_operation_id IS NOT NULL + AND A.enercoop_operation_id IN %s + AND A.enercoop_counter_id IN %s + AND A.date_slot >= %s + AND A.date_slot < %s + GROUP BY date_trunc(%s, A.date_slot) + ORDER BY date_slot ASC; + """ + query_params = (slot_type, tuple(self.ids), tuple(prm_ids.ids), date_start, date_end, slot_type) + else: + query = """ + SELECT + date_trunc(%s, A.date_slot) AS date_slot, + (SUM((CASE WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as autocons, + (SUM((CASE WHEN comp_data_type = 'surplus' THEN A.power ELSE 0 END)) / 2) / 1000 as surplus, + ((SUM((CASE WHEN comp_data_type = 'cons' THEN A.power ELSE 0 END)) - SUM(CASE + WHEN comp_data_type = 'autocons' THEN A.power ELSE 0 END)) / 2) / 1000 as allocons + FROM enercoop_enedis_cdc A + JOIN enercoop_operation E ON E.id = A.enercoop_operation_id + WHERE A.enercoop_operation_id IS NOT NULL + AND A.enercoop_operation_id IN %s + AND A.date_slot >= %s + AND A.date_slot < %s + GROUP BY date_trunc(%s, A.date_slot) + ORDER BY date_slot ASC; + """ + query_params = (slot_type, tuple(self.ids), date_start, date_end, slot_type) + self.env.cr.execute(query, query_params) + raw_data = self.env.cr.fetchall() + for row in raw_data: + data_autocons_histo.append(int(row[1])) + data_surplus_histo.append(int(row[2])) + data_allocons_histo.append(int(row[3])) + label_histo.append(row[0]) + + cdc_jour = { + 'autocons_histo': data_autocons_histo, + 'surplus_histo': data_surplus_histo, + 'allocons_histo': data_allocons_histo, + 'label_histo': label_histo, + } + return cdc_jour + + def chart_data_line_cons(self, chart_data, scale): """ Fonction retournant le dictionnaire permettant la construiction - des graphes de la partie consommation + des graphes de la partie consommation par mois :param chart_data: données à afficher dans les chart (labels et data) :return: un dictionnaire de chart """ result = {} - result['line_chart_conso'] = { - 'type': 'line', - 'data': { - 'labels': chart_data['label'], - 'datasets': [ - { - 'label': 'Allo Conso', - 'data': chart_data['cons'], - 'backgroundColor': 'rgba(57, 120, 187, 0.7)', - 'borderColor': 'rgba(57, 120, 187, 1)', - }, - { - 'label': 'Production solaire', - 'data': chart_data['prod'], - 'backgroundColor': 'rgba(244, 165, 25, 0)', - 'borderColor': 'rgba(244, 165, 25, 1)', - }, - { - 'label': 'Autoconso', - 'data': chart_data['autocons'], - 'backgroundColor': 'rgba(91, 154, 81, 0.7)', - 'borderColor': 'rgba(91, 154, 81, 1)', - }, - ], - }, - } + result['line_chart_conso_line'] = { 'type': 'line', 'data': { @@ -298,7 +410,7 @@ class EnercoopOperation(models.Model): 'datasets': [ { 'label': 'Allo Conso', - 'data': chart_data['cons_line'], + 'data': chart_data['allocons'], 'backgroundColor': 'rgba(57, 120, 187, 0.2)', 'borderColor': 'rgba(57, 120, 187, 1)', 'borderWidth': 1, @@ -307,7 +419,7 @@ class EnercoopOperation(models.Model): }, { 'label': 'Production solaire', - 'data': chart_data['prod_line'], + 'data': chart_data['prod'], 'backgroundColor': 'rgba(244, 165, 25, 0)', 'borderColor': 'rgba(244, 165, 25, 1)', 'borderWidth': 2, @@ -316,7 +428,7 @@ class EnercoopOperation(models.Model): }, { 'label': 'Autoconso', - 'data': chart_data['autocons_line'], + 'data': chart_data['autocons'], 'backgroundColor': 'rgba(91, 154, 81, 0.4)', 'borderColor': 'rgba(91, 154, 81, 1)', 'borderWidth': 2, @@ -325,72 +437,157 @@ class EnercoopOperation(models.Model): }, ], }, + 'options': { + 'scales': { + 'xAxes': [{ + 'type': 'time', + 'time': { + 'unit': scale, + }, + 'gridLines': { + 'offsetGridLines': True + } + }], + 'yAxes': [{ + 'scaleLabel': { + 'display': True, + 'labelString': 'kW', + } + }] + }, + 'elements': { + 'point': { + 'radius': 0 + } + } + }, } - result['donuts_chart_conso'] = { - 'type': 'doughnut', - 'data': { - 'labels': chart_data['label_doughnut'], - 'datasets': [{ - 'label': 'Inférieur à 3', - 'data': chart_data['doughnut_cons'], - 'backgroundColor': [ - 'rgba(91, 154, 81, 0.4)', - 'rgba(57, 120, 187, 0.4)', - ], - 'borderWidth': 1 - }], - }, - } + return result + + def chart_data_histo_cons(self, chart_data, scale, scale_spe): + """ + Fonction retournant le dictionnaire permettant la construiction + des graphes de la partie consommation par mois + :param chart_data: données à afficher dans les chart (labels et data) + :return: un dictionnaire de chart + """ + + result = {} + if scale_spe == 'week': + data_autocons = chart_data['autocons_histo'] + data_allocons = chart_data['allocons_histo'] + data_label = chart_data['label_histo'] + else: + data_autocons = chart_data['autocons'] + data_allocons = chart_data['allocons'] + data_label = chart_data['label'] result['histo_chart_conso'] = { 'type': 'bar', 'data': { - 'labels': chart_data['label_histo'], + 'labels': data_label, 'datasets': [ { 'label': 'AutoConso', - 'data': chart_data['autocons'], + 'data': data_autocons, 'backgroundColor': 'rgba(91, 154, 81, 0.4)', 'borderColor': 'rgba(91, 154, 81, 1)', }, { 'label': 'AlloConso', - 'data': chart_data['cons'], + 'data': data_allocons, 'backgroundColor': 'rgba(57, 120, 187, 0.4)', 'borderColor': 'rgba(57, 120, 187, 1)', }] + }, + 'options': { + 'plugins': { + 'datalabels': { + 'color': 'white', + 'font': { + 'weight': 'bold' + }, + } + }, + 'interaction': { + 'intersect': False, + }, + 'scales': { + 'xAxes': [{ + 'type': 'time', + 'time': { + 'unit': scale + }, + 'stacked': True, + 'offset': True, + 'gridLines': { + 'offsetGridLines': True + } + }], + 'yAxes': [{ + 'stacked': True, + 'ticks': { + 'beginAtZero': True, + }, + 'type': 'linear', + 'scaleLabel': { + 'display': True, + 'labelString': 'kWh', + } + }] } } + } return result - def chart_data_prod(self, chart_data): + def chart_data_donuts_cons(self, chart_data, scale): """ Fonction retournant le dictionnaire permettant la construiction - des graphes de la partie production + des graphes de la partie consommation par mois :param chart_data: données à afficher dans les chart (labels et data) :return: un dictionnaire de chart """ result = {} - result['line_chart_prod'] = { - 'type': 'line', + + if scale == 'hour': + sum_res1 = sum(int(item['y']) for item in chart_data['autocons']) + sum_res2 = sum(int(item['y']) for item in chart_data['allocons']) + else: + sum_res1 = sum(chart_data['autocons']) + sum_res2 = sum(chart_data['allocons']) + + tot_res = sum_res1 + sum_res2 + res = [int((sum_res1 * 100) / tot_res), int((sum_res2 * 100) / tot_res)] + + result['donuts_chart_conso'] = { + 'type': 'doughnut', 'data': { - 'labels': chart_data['label'], - 'datasets': [ - { - 'label': 'Surplus', - 'data': chart_data['surplus'], - 'backgroundColor': 'rgba(225, 80, 96, 0.7)', - 'borderColor': 'rgba(225, 80, 96, 1)', - }, - { - 'label': 'Autoconso', - 'data': chart_data['autocons'], - 'backgroundColor': 'rgba(91, 154, 81, 0.7)', - 'borderColor': 'rgba(91, 154, 81, 1)', - }, - ], + 'labels': ['Autoconso', 'Alloconso'], + 'datasets': [{ + 'label': 'Inférieur à 3', + 'data': res, + 'backgroundColor': [ + 'rgba(91, 154, 81, 0.4)', + 'rgba(57, 120, 187, 0.4)', + ], + 'borderWidth': 1 + }], }, + 'options': { + 'cutoutPercentage': 60, + } } + return result + + def chart_data_line_prod(self, chart_data, scale): + """ + Fonction retournant le dictionnaire permettant la construiction + des graphes de la partie production + :param chart_data: données à afficher dans les chart (labels et data) + :return: un dictionnaire de chart + """ + + result = {} result['line_chart_prod_line'] = { 'type': 'line', 'data': { @@ -398,7 +595,7 @@ class EnercoopOperation(models.Model): 'datasets': [ { 'label': 'Surplus', - 'data': chart_data['surplus_line'], + 'data': chart_data['surplus'], 'backgroundColor': 'rgba(225, 80, 96, 0.4)', 'borderColor': 'rgba(225, 80, 96, 1)', 'borderWidth': 2, @@ -407,7 +604,7 @@ class EnercoopOperation(models.Model): }, { 'label': 'Autoconso', - 'data': chart_data['autocons_line'], + 'data': chart_data['autocons'], 'backgroundColor': 'rgba(91, 154, 81, 0.4)', 'borderColor': 'rgba(91, 154, 81, 1)', 'borderWidth': 2, @@ -416,14 +613,77 @@ class EnercoopOperation(models.Model): }, ], }, + 'options': { + 'scales': { + 'xAxes': [{ + 'type': 'time', + 'time': { + 'unit': scale, + }, + 'ticks': { + # 'min': result.date_start, + }, + 'gridLines': { + 'offsetGridLines': True + } + }], + 'yAxes': [{ + 'stacked': True, + 'scaleLabel': { + 'display': True, + 'labelString': 'kW', + } + }] + }, + 'elements': { + 'point': { + 'radius': 0 + } + } + }, } + result['line_chart_prod_prm'] = { + 'type': 'line', + 'data': { + 'labels': chart_data['label'], + 'datasets': [ + { + 'label': 'Production solaire', + 'data': chart_data['prod'], + 'backgroundColor': 'rgba(244, 165, 25, 0)', + 'borderColor': 'rgba(244, 165, 25, 1)', + }, + ], + }, + } + return result + + def chart_data_donuts_prod(self, chart_data, scale): + """ + Fonction retournant le dictionnaire permettant la construiction + des graphes de la partie production + :param chart_data: données à afficher dans les chart (labels et data) + :return: un dictionnaire de chart + """ + + result = {} + if scale == 'hour': + sum_res1 = sum(int(item['y']) for item in chart_data['autocons']) + sum_res2 = sum(int(item['y']) for item in chart_data['surplus']) + else: + sum_res1 = sum(chart_data['autocons']) + sum_res2 = sum(chart_data['surplus']) + + tot_res = sum_res1 + sum_res2 + res = [int((sum_res1 * 100) / tot_res), int((sum_res2 * 100) / tot_res)] + result['donuts_chart_prod'] = { 'type': 'doughnut', 'data': { - 'labels': chart_data['label_doughnut_prod'], + 'labels': ['Autoconso', 'Surplus'], 'datasets': [{ 'label': 'Inférieur à 3', - 'data': chart_data['doughnut_prod'], + 'data': res, 'backgroundColor': [ 'rgba(91, 154, 81, 0.4)', 'rgba(225, 80, 96, 0.4)', @@ -432,332 +692,169 @@ class EnercoopOperation(models.Model): }], }, } + + return result + + def chart_data_histo_prod(self, chart_data, scale, scale_spe): + """ + Fonction retournant le dictionnaire permettant la construiction + des graphes de la partie production + :param chart_data: données à afficher dans les chart (labels et data) + :return: un dictionnaire de chart + """ + + result = {} + if scale_spe == 'week': + data_autocons = chart_data['autocons_histo'] + data_surplus = chart_data['surplus_histo'] + data_label = chart_data['label_histo'] + else: + data_autocons = chart_data['autocons'] + data_surplus = chart_data['surplus'] + data_label = chart_data['label'] + result['histo_chart_prod'] = { 'type': 'bar', 'data': { - 'labels': chart_data['label_histo'], + 'labels': data_label, 'datasets': [ { 'label': 'AutoConso', - 'data': chart_data['autocons'], + 'data': data_autocons, 'backgroundColor': 'rgba(91, 154, 81, 0.4)', 'borderColor': 'rgba(91, 154, 81, 1)', }, { 'label': 'Surplus', - 'data': chart_data['surplus'], + 'data': data_surplus, 'backgroundColor': 'rgba(225, 80, 96, 0.4)', 'borderColor': 'rgba(225, 80, 96, 1)', }] - } - } - result['line_chart_prod_prm'] = { - 'type': 'line', - 'data': { - 'labels': chart_data['label'], - 'datasets': [ - { - 'label': 'Production solaire', - 'data': chart_data['prod'], - 'backgroundColor': 'rgba(244, 165, 25, 0)', - 'borderColor': 'rgba(244, 165, 25, 1)', - }, - ], - }, - } - result['line_chart_prod_line_prm'] = { - 'type': 'line', - 'data': { - 'labels': chart_data['label'], - 'datasets': [ - { - 'label': 'Production solaire', - 'data': chart_data['prod_line'], - 'backgroundColor': 'rgba(244, 165, 25, 0)', - 'borderColor': 'rgba(244, 165, 25, 1)', - 'borderWidth': 2, - 'hoverRadius': 1, - 'radius': 0, - }, - { - 'label': 'Autoconso', - 'data': chart_data['autocons_line'], - 'backgroundColor': 'rgba(91, 154, 81, 0.4)', - 'borderColor': 'rgba(91, 154, 81, 1)', - 'borderWidth': 2, - 'hoverRadius': 1, - 'radius': 0, - }, - ], }, + 'options': { + 'plugins': { + 'datalabels': { + 'color': 'white', + 'font': { + 'weight': 'bold' + }, + } + }, + 'interaction': { + 'intersect': False, + }, + 'scales': { + 'xAxes': [{ + 'type': 'time', + 'time': { + 'unit': scale + }, + 'stacked': True, + 'offset': True, + 'gridLines': { + 'offsetGridLines': True + } + }], + 'yAxes': [{ + 'stacked': True, + 'ticks': { + 'beginAtZero': True, + }, + 'type': 'linear', + 'scaleLabel': { + 'display': True, + 'labelString': 'kWh', + } + }] + } + } } + return result - def get_cdc(self, type, date_start, date_end, prm_id=None): + def get_cdc(self, scale, step_courbe, date_start, date_end, prm_ids=None): """ Fonction permettant de récupérer les données pour la construction des chart pour une ou des opérations données - :param type: type d'affichage des graphes - (day/week/month/semestre/year) + :param step_courbe: Pas à prendre en courbe pour le calcul des courbes + (hour/day/week/month/year) date_start: date début date_end: date de fin + prm_ids: PRMs :return: un dictionnaire de données (labels et data pour les charts à afficher) """ - cdc_jour = [] + enercoop_counter_ids = self.env['enercoop.counter'].browse(prm_ids) if prm_ids else None - label_line_cons = [] - label_histo_cons = [] - data_autocons = [] - data_autocons_line = [] - data_cons = [] - data_cons_line = [] - data_prod = [] - data_prod_line = [] - data_surplus = [] - data_surplus_line = [] - - # Depending on type scale, define the date slot type - # Data by day / hour for type = day - # Data by week / day for type = week - # Data by month / day for type = month - # Data by year / months for type = year - if type == 'day': - type_date = 'date_slot:hour' - type_date_abs = 'date_slot:day' - type_date_histo = 'date_slot:hour' - elif type == 'year' or 'semestre': - type_date = 'date_slot:month' - type_date_abs = 'date_slot:month' - type_date_histo = 'date_slot:month' - else: - type_date = 'date_slot:day' - type_date_abs = 'date_slot:day' - type_date_histo = 'date_slot:day' - if type == 'week': - type_date = 'date_slot:hour' - - domain_all = [ - ('enercoop_operation_id', 'in', self.ids), - ('date_slot', '>=', date_start), - ('date_slot', '<', date_end), - ] - # Get PRM object if defined - enercoop_counter_id = self.env['enercoop.counter'].browse(prm_id) if prm_id else False - - if enercoop_counter_id: - domain_prm = domain_all + [('enercoop_counter_id', '=', enercoop_counter_id.id)] - # Get all data group by curves type and date - cdc_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_prm, - ['power', 'enercoop_operation_id', 'date_slot'], - ['comp_data_type', type_date], orderby='comp_data_type, date_slot ASC', lazy=False) - - if type == 'week': - cdc_histo_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_prm, - ['power', 'enercoop_operation_id', 'date_slot'], - ['comp_data_type', type_date_histo], orderby='comp_data_type, date_slot ASC', lazy=False) - - # Get the date for the abscissa axis - cdc_date_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_prm, - ['enercoop_operation_id', 'date_slot'], - [type_date_abs], orderby='date_slot ASC', lazy=False) - - # Get the date for the abscissa axis (histo) - if type == 'day': - cdc_date_histo_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_prm, - ['enercoop_operation_id', 'date_slot'], - [type_date], orderby='date_slot ASC', lazy=False) - else: - # Get all data group by curves type and date - cdc_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_all, - ['power', 'enercoop_operation_id', 'date_slot'], - ['comp_data_type', type_date], orderby='comp_data_type, date_slot ASC', lazy=False) - - if type == 'week': - cdc_histo_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_all, - ['power', 'enercoop_operation_id', 'date_slot'], - ['comp_data_type', type_date_histo], orderby='comp_data_type, date_slot ASC', lazy=False) - - # Get the date for the abscissa axis - cdc_date_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_all, - ['enercoop_operation_id', 'date_slot'], - [type_date_abs], orderby='date_slot ASC', lazy=False) - - # Get the date for the abscissa axis (histo) - if type == 'day': - cdc_date_histo_ids = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_all, - ['enercoop_operation_id', 'date_slot'], - [type_date], orderby='date_slot ASC', lazy=False) - - # Build the abscissa axis with the right format date - for cdc in cdc_date_ids: - value_hour = cdc[type_date_abs] - label_line_cons.append(value_hour) - label_histo_cons.append(value_hour) - - # Build the abscissa axis with the right format date (histo) - if type == 'day': - label_histo_cons = [] - for cdc in cdc_date_histo_ids: - value_hour = cdc[type_date] - label_histo_cons.append(value_hour) - - # Build the ordinate axis for each data type (autoconso/conso/prod/surplus) - for cdc in cdc_ids: - if type == 'day' or type == 'week': - value_power = round((cdc['power'] / 2), 2) - else: - value_power = round((cdc['power'] / 1000 / 2), 2) - - if cdc['comp_data_type'] == 'autocons': - data_autocons.append(value_power) - if cdc['comp_data_type'] == 'cons': - data_cons.append(value_power) - if cdc['comp_data_type'] == 'prod': - data_prod.append(value_power) - if cdc['comp_data_type'] == 'surplus': - data_surplus.append(value_power) - - # Build the ordinate axis for each data type (autoconso/conso/prod/surplus) for histo graph - if type == 'week': - data_autocons = [] - data_cons = [] - data_prod = [] - data_surplus = [] - for cdc in cdc_histo_ids: - value_power = round((cdc['power'] / 2), 2) - if cdc['comp_data_type'] == 'autocons': - data_autocons.append(value_power) - if cdc['comp_data_type'] == 'cons': - data_cons.append(value_power) - if cdc['comp_data_type'] == 'prod': - data_prod.append(value_power) - if cdc['comp_data_type'] == 'surplus': - data_surplus.append(value_power) - - # SQL Data Query - if type == 'day' or type == 'week': - if enercoop_counter_id: - query = """ - SELECT - A.comp_data_type AS comp_data_type, - A.date_slot AS date_slot, - SUM(A.power) AS power - FROM enercoop_enedis_cdc A - JOIN enercoop_operation E ON E.id = A.enercoop_operation_id - WHERE A.enercoop_operation_id IS NOT NULL - AND A.enercoop_operation_id IN %s - AND A.enercoop_counter_id = %s - AND A.date_slot >= %s - AND A.date_slot < %s - GROUP BY A.comp_data_type, A.date_slot - ORDER BY A.comp_data_type, A.date_slot ASC; - """ - query_params = (tuple(self.ids), enercoop_counter_id.id, date_start, date_end) - self.env.cr.execute(query, query_params) - raw_data = self.env.cr.dictfetchall() + chart_data = self.get_cdc_by_query(step_courbe, date_start, date_end, enercoop_counter_ids) + if scale == 'week': + chart_data_histo = self.get_cdc_by_query_histo('day', date_start, date_end, enercoop_counter_ids) + chart_data.update(chart_data_histo) + + return chart_data + + @api.model + def graph_view(self, domain, scale, first_day, last_day, enercoop_counter_id=None): + """ + Fonction appelée lors du chargement de la vue Qweb + :param domain: représente le champ recherche de la vue + scale: type d'affichage des graphes + (day/week/month/semestre/year) + défini par le clic bouton + :return: dictionnaire pour la construction des graphes + """ + result_graph = {} + # Get the operations depending to the domain + operation_ids = self.env['enercoop.operation'].search(domain) + + if operation_ids: + # Get date start and date end depending on type of scale + if first_day and last_day: + date_start = fields.Datetime.to_datetime(first_day) + date_end = fields.Datetime.to_datetime(last_day) + elif first_day: + date_start, date_end = operation_ids.get_last_day('day') else: - query = """ - SELECT - A.comp_data_type AS comp_data_type, - A.date_slot AS date_slot, - SUM(A.power) AS power - FROM enercoop_enedis_cdc A - JOIN enercoop_operation E ON E.id = A.enercoop_operation_id - WHERE A.enercoop_operation_id IS NOT NULL - AND A.enercoop_operation_id IN %s - AND A.date_slot >= %s - AND A.date_slot < %s - GROUP BY A.comp_data_type, A.date_slot - ORDER BY A.comp_data_type, A.date_slot ASC; - """ - query_params = (tuple(self.ids), date_start, date_end) - self.env.cr.execute(query, query_params) - raw_data = self.env.cr.dictfetchall() - - for cdc in raw_data: - if type == 'week' or type == 'day': - value_power = round((cdc['power']), 2) - value_hour = cdc['date_slot'] - - if cdc['comp_data_type'] == 'autocons': - data_autocons_line.append({'t': value_hour, 'y': value_power}) - if cdc['comp_data_type'] == 'cons': - data_cons_line.append({'t': value_hour, 'y': value_power}) - if cdc['comp_data_type'] == 'prod': - data_prod_line.append({'t': value_hour, 'y': value_power}) - if cdc['comp_data_type'] == 'surplus': - data_surplus_line.append({'t': value_hour, 'y': value_power}) - - # Get the data to build the chart Bilan - if enercoop_counter_id: - bilan_cdc = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_prm, - ['power', 'enercoop_operation_id'], - ['comp_data_type'], orderby='comp_data_type', lazy=False) - else: - bilan_cdc = self.env['enercoop.enedis.cdc'].sudo().read_group( - domain_all, - ['power', 'enercoop_operation_id'], - ['comp_data_type'], orderby='comp_data_type', lazy=False) - - # Build the ordinate axis for each data type (autoconso/conso/prod/surplus) - power_autocons = power_cons = power_surplus = power_prod = 0 - for bilan in bilan_cdc: - if bilan['comp_data_type'] == 'autocons': - power_autocons = bilan['power'] / 1000 / 2 - if bilan['comp_data_type'] == 'cons': - power_cons = bilan['power'] / 1000 / 2 - if bilan['comp_data_type'] == 'surplus': - power_surplus = bilan['power'] / 1000 / 2 - if bilan['comp_data_type'] == 'prod': - power_prod = bilan['power'] / 1000 / 2 - - power_tot = power_autocons + power_cons - - if power_tot > 0: - percent_autocons = int(power_autocons * 100 / power_tot) - percent_cons = int(power_cons * 100 / power_tot) - else: - percent_autocons = int(power_autocons * 100) - percent_cons = int(power_cons * 100) + date_start, date_end = operation_ids.get_last_day('month') - power_prod_tot = power_autocons + power_surplus - if power_prod_tot > 0: - percent_autocons_prod = int(power_autocons * 100 / power_prod_tot) - percent_surplus_prod = int(power_surplus * 100 / power_prod_tot) - else: - percent_autocons_prod = int(power_autocons * 100) - percent_surplus_prod = int(power_surplus * 100) + counter_ids = None + if enercoop_counter_id: + counter_ids = self.env['enercoop.counter'].search([('name', '=', enercoop_counter_id)]).ids - cdc_jour = { - 'autocons': data_autocons, - 'autocons_line': data_autocons_line, - 'cons': data_cons, - 'cons_line': data_cons_line, - 'prod': data_prod, - 'prod_line': data_prod_line, - 'surplus': data_surplus, - 'surplus_line': data_surplus_line, - 'label': label_line_cons, - 'label_histo': label_histo_cons, - 'label_doughnut': ['Autoconso', 'Alloconso'], - 'doughnut_cons': [percent_autocons, percent_cons], - 'label_doughnut_prod': ['Autoconso', 'Surplus'], - 'doughnut_prod': [percent_autocons_prod, percent_surplus_prod] - } + step_courbe, step_display_courbe = operation_ids.get_step_from_date(date_start=date_start, date_end=date_end) + # Get the data to display in chart + chart_data = operation_ids.get_cdc(scale=scale, step_courbe=step_courbe, date_start=date_start, date_end=date_end, + prm_ids=counter_ids) + + # Build the chart with data and options + result_graph_line = self.chart_data_line_prod(chart_data, step_display_courbe) + result_graph.update(result_graph_line) + result_graph_histo = self.chart_data_histo_prod(chart_data, step_display_courbe, scale) + result_graph.update(result_graph_histo) + result_graph_donuts = self.chart_data_donuts_prod(chart_data, step_courbe) + result_graph.update(result_graph_donuts) + + result_graph_line = self.chart_data_line_cons(chart_data, step_display_courbe) + result_graph.update(result_graph_line) + result_graph_histo = self.chart_data_histo_cons(chart_data, step_display_courbe, scale) + result_graph.update(result_graph_histo) + result_graph_donuts = self.chart_data_donuts_cons(chart_data, step_courbe) + result_graph.update(result_graph_donuts) + + # result_graph.update(result_graph2) + result_graph.update({'scale': scale}) - return cdc_jour + date_end = date_end.strftime("%d/%m/%Y") + date_min = operation_ids.get_first_day() + date_min = date_min.strftime("%d/%m/%Y") + result_graph.update({ + 'date_end': date_end, + 'date_min': date_min, + 'date_start': date_start, + }) + return result_graph # ------------------------------------------------------ # Functions to manage route # ------------------------------------------------------ @@ -772,20 +869,33 @@ class EnercoopOperation(models.Model): """ result_graph = {} - - # Get date start and date end depending on type of scale if scale fill - if scale: + if not date_start and not date_end: date_start, date_end = self.get_last_day(scale) - # Get scale depending on the date start and date end - if date_start and date_end: - scale = self.get_scale(date_start, date_end) + # Get the step to display courbe in chart + step_courbe, step_display_courbe = self.get_step_from_date(date_start=date_start, date_end=date_end) - # Get the data to display in chart - chart_data = self.get_cdc(scale, date_start, date_end, prm_id) + # New code implementation + enercoop_counter_ids = self.env['enercoop.counter'].browse(prm_id) if prm_id else None - # Build the chart depending on data calculated - result_graph = self.chart_data_cons(chart_data) + if enercoop_counter_ids: + chart_data = self.get_cdc_by_query_cons(step_courbe, date_start, date_end, enercoop_counter_ids) + if scale == 'week': + chart_data_histo = self.get_cdc_by_query_histo('day', date_start, date_end, enercoop_counter_ids) + chart_data.update(chart_data_histo) + else: + chart_data = self.get_cdc_by_query(step_courbe, date_start, date_end, enercoop_counter_ids) + if scale == 'week': + chart_data_histo = self.get_cdc_by_query_histo('day', date_start, date_end, enercoop_counter_ids) + chart_data.update(chart_data_histo) + + # Build the chart with data and options + result_graph_line = self.chart_data_line_cons(chart_data, step_display_courbe) + result_graph.update(result_graph_line) + result_graph_histo = self.chart_data_histo_cons(chart_data, step_display_courbe, scale) + result_graph.update(result_graph_histo) + result_graph_donuts = self.chart_data_donuts_cons(chart_data, step_courbe) + result_graph.update(result_graph_donuts) date_deb, date_max = self.get_last_day('day') date_max = date_max.strftime("%d/%m/%Y") @@ -811,20 +921,29 @@ class EnercoopOperation(models.Model): :return: dictionnaire pour la construction des graphes """ result_graph = {} - - # Get date start and date end depending on type of scale if scale fill - if scale: + # Get the step to display courbe in chart + if not date_start and not date_end: date_start, date_end = self.get_last_day(scale) - # Get scale depending on the date start and date end - if date_start and date_end: - scale = self.get_scale(date_start, date_end) - - # Get the data to display in chart - chart_data = self.get_cdc(scale, date_start, date_end, prm_id) - - # Build the chart depending on data calculated - result_graph = self.chart_data_prod(chart_data) + step_courbe, step_display_courbe = self.get_step_from_date(date_start=date_start, date_end=date_end) + + # New code implementation + enercoop_counter_ids = self.env['enercoop.counter'].browse(prm_id) if prm_id else None + + # if enercoop_counter_ids: + # chart_data = self.get_cdc_by_query(step_courbe, date_start, date_end, enercoop_counter_ids) + # else: + chart_data = self.get_cdc_by_query(step_courbe, date_start, date_end, enercoop_counter_ids) + if scale == 'week': + chart_data_histo = self.get_cdc_by_query_histo('day', date_start, date_end, enercoop_counter_ids) + chart_data.update(chart_data_histo) + + result_graph_line = self.chart_data_line_prod(chart_data, step_display_courbe) + result_graph.update(result_graph_line) + result_graph_histo = self.chart_data_histo_prod(chart_data, step_display_courbe, scale) + result_graph.update(result_graph_histo) + result_graph_donuts = self.chart_data_donuts_prod(chart_data, step_courbe) + result_graph.update(result_graph_donuts) date_deb, date_max = self.get_last_day('day') date_max = date_max.strftime("%d/%m/%Y") diff --git a/models/enercoop_operation_graph.py b/models/enercoop_operation_graph.py index ef3825336549309bfa8fda69c2a418c983d1f667..5aa38a121cf1f519e03112755637faee2ac5e745 100644 --- a/models/enercoop_operation_graph.py +++ b/models/enercoop_operation_graph.py @@ -20,22 +20,32 @@ class EnercoopOperation(models.Model): def _plan_prepare_values(self): values = {} - date_start, date_end = self.get_last_day('day') - last_day = date_start.strftime("%d %B %Y") + date_day_start, date_day_end = self.get_last_day('day') + last_day = date_day_start.strftime("%d %B %Y") + date_day_start = date_day_start.strftime("%Y-%m-%d") + date_day_end = date_day_end.strftime("%Y-%m-%d") - date_start, date_end = self.get_last_day('week') - last_week = date_start.strftime("%d %B %Y") + '-' + date_end.strftime("%d %B %Y") + date_week_start, date_week_end = self.get_last_day('week') + last_week = date_week_start.strftime("%d %B %Y") + '-' + date_week_end.strftime("%d %B %Y") + date_week_start = date_week_start.strftime("%Y-%m-%d") + date_week_end = date_week_end.strftime("%Y-%m-%d") - date_start, date_end = self.get_last_day('month') - last_month = date_start.strftime("%d %B %Y") + '-' + date_end.strftime("%d %B %Y") + date_month_start, date_month_end = self.get_last_day('month') + last_month = date_month_start.strftime("%d %B %Y") + '-' + date_month_end.strftime("%d %B %Y") + date_month_start = date_month_start.strftime("%Y-%m-%d") + date_month_end = date_month_end.strftime("%Y-%m-%d") - range_date = date_start.strftime("%d/%m/%Y") + ' - ' + date_end.strftime("%d/%m/%Y") + # range_date = date_start.strftime("%d/%m/%Y") + ' - ' + date_end.strftime("%d/%m/%Y") - date_start, date_end = self.get_last_day('semestre') - last_semester = date_start.strftime("%d %B %Y") + '-' + date_end.strftime("%d %B %Y") + date_semestre_start, date_semestre_end = self.get_last_day('semestre') + last_semester = date_semestre_start.strftime("%d %B %Y") + '-' + date_semestre_end.strftime("%d %B %Y") + date_semestre_start = date_semestre_start.strftime("%Y-%m-%d") + date_semestre_end = date_semestre_end.strftime("%Y-%m-%d") - date_start, date_end = self.get_last_day('year') - last_year = date_start.strftime("%d %B %Y") + '- ' + date_end.strftime("%d %B %Y") + date_year_start, date_year_end = self.get_last_day('year') + last_year = date_year_start.strftime("%d %B %Y") + '- ' + date_year_end.strftime("%d %B %Y") + date_year_start = date_year_start.strftime("%Y-%m-%d") + date_year_end = date_year_end.strftime("%Y-%m-%d") data_values = { 'last_day': last_day, @@ -43,7 +53,18 @@ class EnercoopOperation(models.Model): 'last_month': last_month, 'last_semestre': last_semester, 'last_year': last_year, - 'range_date': range_date, + # 'range_date': range_date, + 'date_day_start': date_day_start, + 'date_day_end': date_day_end, + 'date_week_start': date_week_start, + 'date_week_end': date_week_end, + 'date_month_start': date_month_start, + 'date_month_end': date_month_end, + 'date_semestre_start': date_semestre_start, + 'date_semestre_end': date_semestre_end, + 'date_year_start': date_year_start, + 'date_year_end': date_year_end, + } values['data_values'] = data_values diff --git a/static/src/js/operation_graph.js b/static/src/js/operation_graph.js index 939cac61bfdc485118dc3a39e341f34b87728dc6..6298c946a7ba90afdb324530ed2c5bc93275defb 100644 --- a/static/src/js/operation_graph.js +++ b/static/src/js/operation_graph.js @@ -42,170 +42,6 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { await this._super(...arguments); var result = self.state.chartValues; - if (result.scale == 'week'){ - var unit = 'day'; - } - if (result.scale == 'day'){ - var unit = 'hour'; - } - if (result.scale == 'week' || result.scale == 'day'){ - var options_line = { options: { - scales: { - xAxes: [{ - type: 'time', - time: { - // Luxon format string - unit: unit, - }, - ticks: { - min: result.date_start, - }, - gridLines: { - offsetGridLines: true - } - }], - yAxes: [{ - scaleLabel: { - display: true, - labelString: 'kW', - } - }] - }, - elements: { - point:{ - radius: 0 - } - } - }, - }; - - var options_line_stacked = { options: { - scales: { - xAxes: [{ - stacked: true, - type: 'time', - time: { - // Luxon format string - unit: unit, - }, - ticks: { - min: result.date_start, - }, - gridLines: { - offsetGridLines: true - } - }], - yAxes: [{ - stacked: true, - scaleLabel: { - display: true, - labelString: 'kW', - } - }] - }, - elements: { - point:{ - radius: 0 - } - } - }, - }; - } - var options = { options: { - scales: { - yAxes: { - beginAtZero: true, - } - } - }}; - - var options_donuts = { options: { -// showDatasetLabels : true, -// cutoutPercentage: 41, - plugins: { - color: "#1f4e56", - font: { - weight: "bold", - size: 16 - }, - padding: 6, - formatter: (value) => { - return value + "%"; - } - } - }}; - - var options_histo_stacked = { options: { - plugins: { - datalabels: { - color: 'white', - display: function(context) { - return context.dataset.data[context.dataIndex] > 0; - }, - font: { - weight: 'bold' - }, - formatter: Math.round - } - }, - interaction: { - intersect: false, - }, - scales: { - xAxes: [{ - stacked: true, - gridLines: { - offsetGridLines: true - } - }], - yAxes: [{ - stacked: true, - ticks: { - beginAtZero: true, - }, - type: 'linear', - scaleLabel: { - display: true, - labelString: 'kWh', - } - }] - } - }}; - - var options_histo = { options: { - plugins: { - datalabels: { - color: 'white', - display: function(context) { - return context.dataset.data[context.dataIndex] > 0; - }, - font: { - weight: 'bold' - }, - formatter: Math.round - } - }, - interaction: { - intersect: false, - }, - scales: { - xAxes: [{ - gridLines: { - offsetGridLines: true - } - }], - yAxes: [{ - ticks: { - beginAtZero: true, - }, - type: 'linear', - scaleLabel: { - display: true, - labelString: 'kWh', - } - }] - } - }}; var line_conso = self.$el.find('#line_chart_conso'); var donuts_conso = self.$el.find('#donuts_chart_conso'); @@ -222,39 +58,36 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { if (result.scale == 'week' || result.scale == 'day'){ chart_line_conso = new Chart( line_conso, - Object.assign({}, result.line_chart_conso_line, options_line) + Object.assign({}, result.line_chart_conso_line) ); } - console.log(options_line); - console.log(chart_line_conso); chart_donuts_conso = new Chart( donuts_conso, - Object.assign({}, result.donuts_chart_conso, options_donuts) + Object.assign({}, result.donuts_chart_conso) ); - console.log(options_donuts); - console.log(chart_donuts_conso); chart_histo_conso = new Chart( histo_conso, - Object.assign({}, result.histo_chart_conso, options_histo_stacked) + Object.assign({}, result.histo_chart_conso) ); if (result.scale == 'week' || result.scale == 'day'){ chart_line_prod = new Chart( line_prod, - Object.assign({}, result.line_chart_prod_line, options_line_stacked) + Object.assign({}, result.line_chart_prod_line) ); + console.log(chart_line_prod); } chart_donuts_prod = new Chart( donuts_prod, - Object.assign({}, result.donuts_chart_prod, options_donuts) + Object.assign({}, result.donuts_chart_prod) ); chart_histo_prod = new Chart( histo_prod, - Object.assign({}, result.histo_chart_prod, options_histo) + Object.assign({}, result.histo_chart_prod) ); this.$el.find('.o_enercoop_button').removeClass('active'); if (this.state.scale) { @@ -271,9 +104,14 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { e.preventDefault(); var $action = $(e.currentTarget); $action.addClass('active'); + var context = JSON.parse($action.attr('context').replace(/'/g, '"')); + var first_day = context.first_day; + var last_day = context.last_day; this.trigger_up('chart_open_action', { action_name: $action.attr('name'), action_context: $action.attr('context'), + action_first_day: first_day, + action_last_day: last_day, }); }, @@ -306,6 +144,8 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { __load: function (params) { if ('scales' in params) { this.scales = params.scales; + this.first_day = params.first_day; + this.last_day = params.last_day; } return this._loadChart(this._super.apply(this, arguments), params); }, @@ -316,6 +156,8 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { __reload: function (handle, params) { if ('scales' in params) { this.scales = params.scales; + this.first_day = params.first_day; + this.last_day = params.last_day; } return this._loadChart(this._super.apply(this, arguments), params); }, @@ -333,7 +175,7 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { var chart_def = this._rpc({ model: 'enercoop.operation', method: 'graph_view', - args: [domain, this.scales, enercoop_counter_id], + args: [domain, this.scales, this.first_day, this.last_day, enercoop_counter_id], context: this._state.context, }); return Promise.all([super_def, chart_def]).then(function(results) { @@ -349,6 +191,11 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { this.scales = scale; }, + setDate: function (first_day, last_day) { + this.first_day = first_day; + this.last_day = last_day; + }, + }); const Controller = qweb.Controller.extend({ @@ -360,6 +207,8 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { init: function (parent, model, renderer, params) { this._super.apply(this, arguments); this.scales = params.scales; + this.first_day = params.first_day; + this.last_day = params.last_day; }, /** @@ -368,8 +217,12 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { */ _onChartClicked: function (e) { this.model.setScale(e.data.action_name); + this.model.setDate(e.data.action_first_day, e.data.action_last_day); var state = this.model.get(); state.scale = e.data.action_name + var context = e.data.action_context + state.first_day = e.data.action_first_day + state.last_day = e.data.action_last_day this.reload(); }, @@ -402,6 +255,10 @@ odoo.define('enercoop_cdc.operation_graph', function (require) { this._super.apply(this, arguments); this.controllerParams.scales = 'month'; this.loadParams.scales = 'month'; + this.controllerParams.first_day = ''; + this.controllerParams.last_day = ''; + this.loadParams.first_day = ''; + this.loadParams.last_day = ''; }, }); diff --git a/views/enercoop_operation_templates.xml b/views/enercoop_operation_templates.xml index 732596cef061269ac027cfdd7a8424e7243ebe5d..04a95ac6fdc771842ec387ea818411ece126ec87 100644 --- a/views/enercoop_operation_templates.xml +++ b/views/enercoop_operation_templates.xml @@ -20,11 +20,11 @@ <div class="o_timesheet_plan_sale_timesheet"> <div class="o_timesheet_plan_sale_timesheet_dashboard"> <div class="container text-center mt32 mb32"> - <button name="day" class="btn btn-secondary o_enercoop_button" title="Dernier jour" aria-label="Dernier jour" data-mode="day"><strong>Dernière journée</strong><br/><t t-esc="data_values['last_day']"/></button> - <button name="week" class="btn btn-secondary o_enercoop_button" title="7 derniers jours" aria-label="7 derniers jours" data-mode="week"><strong>7 derniers jours</strong><br/><t t-esc="data_values['last_week']"/></button> - <button name="month" class="btn btn-secondary o_enercoop_button" title="Dernier mois" aria-label="Dernier mois" data-mode="month"><strong>Dernier mois</strong><br/><t t-esc="data_values['last_month']"/></button> - <button name="semestre" class="btn btn-secondary o_enercoop_button" title="6 derniers mois" aria-label="6 derniers mois" data-mode="semestre"><strong>6 derniers mois</strong><br/><t t-esc="data_values['last_semestre']"/></button> - <button name="year" class="btn btn-secondary o_enercoop_button" title="12 derniers mois" aria-label="12 derniers mois" data-mode="year"><strong>12 derniers mois</strong><br/><t t-esc="data_values['last_year']"/></button> + <button t-att-context="{'first_day': data_values['date_day_start'], 'last_day': ''}" name="day" class="btn btn-secondary o_enercoop_button" title="Dernier jour" aria-label="Dernier jour" data-mode="day"><strong>Dernière journée</strong><br/><t t-esc="data_values['last_day']"/></button> + <button t-att-context="{'first_day': data_values['date_week_start'], 'last_day': data_values['date_week_end']}" name="week" class="btn btn-secondary o_enercoop_button" title="7 derniers jours" aria-label="7 derniers jours" data-mode="week"><strong>7 derniers jours</strong><br/><t t-esc="data_values['last_week']"/></button> + <button t-att-context="{'first_day': data_values['date_month_start'], 'last_day': data_values['date_month_end']}" name="month" class="btn btn-secondary o_enercoop_button" title="Dernier mois" aria-label="Dernier mois" data-mode="month"><strong>Dernier mois</strong><br/><t t-esc="data_values['last_month']"/></button> + <button t-att-context="{'first_day': data_values['date_semestre_start'], 'last_day': data_values['date_semestre_end']}" name="semestre" class="btn btn-secondary o_enercoop_button" title="6 derniers mois" aria-label="6 derniers mois" data-mode="semestre"><strong>6 derniers mois</strong><br/><t t-esc="data_values['last_semestre']"/></button> + <button t-att-context="{'first_day': data_values['date_year_start'], 'last_day': data_values['date_year_end']}" name="year" class="btn btn-secondary o_enercoop_button" title="12 derniers mois" aria-label="12 derniers mois" data-mode="year"><strong>12 derniers mois</strong><br/><t t-esc="data_values['last_year']"/></button> </div> <div class="text-center o_title mt32"> <h2>Vues Consommateurs</h2>