瀏覽代碼

changed api in assets component, removed tests component

onunez 6 年之前
父節點
當前提交
c96cf2f319

+ 29 - 13
src/app/components/assets/assets.component.html

@@ -5,19 +5,35 @@
       <label for="sel3">Plantas</label>
     </div>
   </div>
-  <div class="row">
-    <div class="col-lg-6 col-sm-4">
-      <div class="align-container">
-        <select class="custom-select"(onChange)="onChangeObj($event)" name="sel3">
-          <option *ngFor="let item of listAssets" [selected]="item._id===organizationId" [value]="item._id" >{{item.name}}</option>
-        </select>
+  <div class="row align-container" style="padding: 0 25px;">
+    <div class="col-lg-6 col-sm-4 p-1">
+      <div class="row">
+        <div class="col-lg-12 col-sm-12">
+          <select class="custom-select"(onChange)="onChangeObj($event)" name="sel3">
+            <option *ngFor="let item of listAssets" [selected]="item.id===organizationId" [value]="item.id" >{{item.name}}</option>
+          </select>
+        
+        </div>
+      </div>
+      <div class="row">
+        <div class="col-lg-6">
+            <div class="widget energy-stats">
+                <div class="mini-stats ">
+                  <span class="dark-yellow-skin"><i class="fa fa-bolt"></i></span>
+                  <h5 *ngIf="listEnergyProduced">
+                    {{listEnergyProduced.thisWeek.total_energy_kWh/1000 | number}}
+                    <small>MWh</small>
+                  </h5>
+                </div>
+              </div>
+          </div>
       </div>
-      <br>
+      
     </div>
 
     <!-- Weather card -->
-    <div class="col-lg-6 col-sm-8">
-      <div class="row align-container">
+    <div class="col-lg-6 col-sm-8 p-1">
+      <div class="row">
         <div class="col-lg-12">
           <app-weather-card></app-weather-card>
         </div>
@@ -101,10 +117,10 @@
 
           <p>Seleccione un rango de visualización</p>
 
-          <button class="btn" [class.btn-success]='isActive[0]' (click)="onMeasureClickDay()">Día</button>
-          <button class="btn" [class.btn-success]='isActive[1]' (click)="onMeasureClickWeek()">Semana</button>
-          <button class="btn" [class.btn-success]='isActive[2]' (click)="onMeasureClickMonth()">Mes</button>
-          <button class="btn" [class.btn-success]='isActive[3]' (click)="onMeasureYear()">Año</button>
+          <button class="btn" [class.btn-success]='isActive[0]' (click)="onMeasureClickRange('day')">Día</button>
+          <button class="btn" [class.btn-success]='isActive[1]' (click)="onMeasureClickRange('week')">Semana</button>
+          <button class="btn" [class.btn-success]='isActive[2]' (click)="onMeasureClickRange('month')">Mes</button>
+          <button class="btn" [class.btn-success]='isActive[3]' (click)="onMeasureClickRange('year')">Año</button>
           <div class="input-box-container">
             <input class="input-box" placeholder="Click to select a date" 
               angular-mydatepicker name="mydate" (click)="dp.toggleCalendar()" 

+ 0 - 4
src/app/components/assets/assets.component.scss

@@ -13,8 +13,6 @@
   }
 }
 
-
-
 table {
   width: 100%;
 }
@@ -135,9 +133,7 @@ table {
 
       span {
         float: none;
-        height: auto;
         margin: 0;
-        width: auto;
         display: inline;
         border: none;
         font-size: 1.2rem;

+ 134 - 414
src/app/components/assets/assets.component.ts

@@ -31,7 +31,7 @@ import {AngularMyDatePickerDirective,IAngularMyDpOptions, IMyDateModel} from 'an
 
 
 export class AssetsComponent implements OnInit {
- 
+  
   title = "Plantas";
 
   organizationId:string;
@@ -39,7 +39,6 @@ export class AssetsComponent implements OnInit {
   listEnergyProduced:any;
   error:boolean;
   errorMessage:string;
-  test:any;
   errortest:any;
   chartjs:boolean;
   chart1: Chart;
@@ -47,14 +46,14 @@ export class AssetsComponent implements OnInit {
   metersValues:any;
   view:string;
 
+
   //For daterange
   daysLabels:any = {su: 'Dom', mo: 'Lun', tu: 'Mar', we: 'Mie', th: 'Jue', fr: 'Vie', sa: 'Sab'};
   monthsLabels:any = { 1: 'Ene', 2: 'Feb', 3: 'Mar', 4: 'Abr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Ago', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dic' };
   todayBtnTxt:string = 'Hoy';
   
-  
   myDpOptions: IAngularMyDpOptions = {
-    dateRange: true,
+    dateRange: false,
     dateFormat: 'dd/mm/yyyy',
     dayLabels: this.daysLabels,
     monthLabels: this.monthsLabels,
@@ -66,13 +65,10 @@ export class AssetsComponent implements OnInit {
 
   // For chartjs
   tsLabels: any[];
-  polarLabels: any[];
-  serieA: any[];
-  serieB: any[];
-  serieC: any[];
   barChartColors:any = ['#3c8dbc', '#00a65a', '#f56954']
-  
   metersData:any;
+  initialDate:any;
+
 
   public barChartType: ChartType;
   public barChartLegend:boolean;
@@ -103,27 +99,53 @@ export class AssetsComponent implements OnInit {
 
   ngOnInit() {
     
-    let plants = this.plantsService.getAssets();
+    let plants = this.plantsService.getAllAssets();
     let energy_produced = this.plantsService.getAssetsProducedEnergy();
 
+    // Default date is today and set it on a string var and initialize dateRange plugin
+    this.initialDate = new Date("2019-09-15").toISOString().slice(0, 10);
+    console.log(this.initialDate);
+    if (this.myDateInit) {
+      let begin: Date = new Date("2019-09-15");
+      this.model = {
+        isRange: false, 
+        singleDate: {
+          date: {
+            year: begin.getFullYear(), month: begin.getMonth() + 1, day: begin.getDate() + 1
+          }
+        }
+      };
+    }
+    
     // Observable of two objects
     forkJoin([plants, energy_produced]).subscribe(results => {
+      console.log(results[0]["data"]);
       if (localStorage.getItem("email") == "inverlec@grupomerelec.com"){
-        this.listAssets = [{
-          name: "Inversiones MERELEC S.A de C.V",
-          id: 1
-        }]
+        this.listAssets = [
+          {
+            name: "Inversiones MERELEC S.A de C.V",
+            id: '5d70330cb288f25b679c68a8'
+          },
+          {
+            name: "Inversiones MERELEC 2 S.A de C.V",
+            id: '5d70330cb288f25b679c68n8'
+          },          
+        ]
+
+        this.view = "month";
+        this.onMeasureClickRange(this.view, this.initialDate);
+
+        console.log(this.listAssets[0]["id"]);
       }
       else {
-
-        this.listAssets = results[0]["assets"];
-        this.route.queryParams.subscribe(params => {
-          this.organizationId = params['id'];
-          console.log(this.organizationId); // Print the parameter to the console.
-        });
+        this.listAssets = results[0]["data"];
+        console.log(this.listAssets[0]["id"]);
+        this.view = "month";
+        this.onMeasureClickRange(this.view, this.initialDate);
       }
       
-      this.listEnergyProduced = results[1];   
+      // Energy produced given an assetID
+      this.listEnergyProduced = results[1];      
     },
     (err) => {
       Swal.fire({
@@ -131,121 +153,15 @@ export class AssetsComponent implements OnInit {
         title: 'Error en el servidor',
         text: "No su pudo obtener la informacion"
       });
-    });
-    this.view = "month";
-  
-    this.isActive = [false, false, true, false];
-    this.logsService.getEnergyProducedByMonth().toPromise()
-    .then((data: any) => {
-      // Get all the keys(each meter name) of the returned promise
-      this.metersKeys = Object.keys(data["1M"]);
-      
-      // Get all the values according to each index (meter) 
-      this.metersValues = Object.values(data["1M"]).map(sub => sub);
-      let meterKeys2 = Object.keys(this.metersValues);
-      
-      // Re-Initialize Json object
-      this.metersData = [];
-
-      // Json object construction for passing its values to the chartjs datasets according to its requirements
-      for (let prop in meterKeys2) { 
-        let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersKeys[prop];
-        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: this.metersValues[prop].map(obj => obj.total_energy_kWh).reverse()});
-        this.barChartLabels = this.metersValues[prop].map(obj => formatDate(obj.dateMax, 'dd/MM','es-Es','-0600')).reverse();
-      }
-
-      // Chart draw
-      this.chart1 = new Chart('canvas', {
-        type: 'bar',
-        options: {
-          title: {
-            display: true,
-          },
-          tooltips: {
-            mode: 'index',
-            callbacks: {
-              // Get the total of the energy produced in every point and show it in the hover tooltip
-              label: function (tooltipItem, data) { 
-                var label = data.datasets[tooltipItem.datasetIndex].label || '';
-                var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
-                var total = 0;
-
-                for (var i = 0; i < data.datasets.length; i++)
-                  total += +data.datasets[i].data[tooltipItem.index];
+    });    
 
-                if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
-                  return label + " : " + value;
-                }
-                else {
-                  return [label + " : " + value, "TOTAL : " + Math.round(total)];
-                }
-              }
-            }
-          },
-          responsive: true,
-          maintainAspectRatio: false,
-          scales: {
-            xAxes: [{
-              stacked: true,
-            }],
-            yAxes: [{
-              stacked: true
-            }]
-          }
-        },
-        data: {
-          labels: this.barChartLabels,
-          datasets: 
-            this.metersData,
-        }, 
-      });
-      this.chartjs = true;
-    });
     this.chartjs = true;
     setTimeout(()=>{
       Swal.close();
     }, 2700);
-
-
-    if (this.myDateInit) {
-      // Initialize to specific date range with IMyDate object. 
-      // Begin date = today. End date = today + 3.
-      let begin: Date = new Date();
-      let end: Date = new Date();
-      begin.setDate(end.getDate() - 31);
-      console.log("if");
-      this.model = {
-        isRange: true, 
-        singleDate: null, 
-        dateRange: {
-          beginDate: {
-            year: begin.getFullYear(), month: begin.getMonth() + 1, day: begin.getDate()
-          },
-          endDate: {
-            year: end.getFullYear(), month: end.getMonth() + 1, day: end.getDate()
-          }
-        }
-      };
-    }
-    else {
-      // Initialize to specific date range with a javascript date object. 
-      // Begin date = today. End date = today + 3.
-      let begin: Date = new Date();
-      let end: Date = new Date();
-      end.setDate(end.getDate() + 3);
-      console.log("else");
-      this.model = {
-        isRange: true, 
-        singleDate: null, 
-        dateRange: {
-          beginJsDate: begin,
-          endJsDate: end
-        }
-      };
-    }
-
   }
  
+  // Default check asset dropdown if a value is equal to an assetID
   isSelected(){
     if(this.organizationId!=undefined){
       return true;
@@ -254,237 +170,126 @@ export class AssetsComponent implements OnInit {
       return false;
     }
   }
-  
-  onDateChanged(event: IMyDateModel) {
-    console.log('onDateChanged(): ', event);
-    let beginDate = `${event.dateRange.beginDate.year}-${event.dateRange.beginDate.month}-${event.dateRange.beginDate.day}`;
-    let endDate = `${event.dateRange.endDate.year}-${event.dateRange.endDate.month}-${event.dateRange.endDate.day}`;
 
+  // Trigger again the chart with the selected assetID
+  onChangeObj(event:any) {
+    this.onMeasureClickRange(this.view, this.initialDate, event.target.value);
+  }
+
+  // Change the date range of the chart, according to the selected view (daily, weekly, ...)
+  onDateChanged(event: IMyDateModel) {
+    let endDate = `${event.singleDate.date.year}-${event.singleDate.date.month}-${event.singleDate.date.day}`;
     switch (this.view)
     { 
       case "day": 
-        console.log("day");
-        this.onMeasureClickDay(beginDate);
+        this.onMeasureClickRange(this.view, endDate);
         break; 
       case "week": 
-        console.log("week");
-        this.onMeasureClickWeek(beginDate, endDate);
+        this.onMeasureClickRange(this.view, endDate);
         break; 
       case "month": 
-        console.log("month");
-        this.onMeasureClickMonth(beginDate, endDate);
+        this.onMeasureClickRange(this.view, endDate);
         break; 
       case "year":
-        console.log("year");
-        this.onMeasureYear(beginDate, endDate);
+        this.onMeasureClickRange(this.view, endDate);
         break;
       default: 
         console.log("nada");
     } 
   }
 
-  onMeasureClickDay(measureDate?:string): void {
+  // Draw a measure chart using chartjs, given some params, view, for daily, weekly, monthly or yearly measures;
+  // measureDate, for a date range given a view and a paramID, for an specific assetID selected in the dropdown  
+  onMeasureClickRange(view:string, measureDate?:string, paramId?:string): void {
     Swal.fire({
       allowOutsideClick: false,
       type: 'info',
       text: 'Espere por favor...'
     });
     Swal.showLoading();
-    this.isActive = [true, false, false, false];
-    this.view = "day";
-
-    this.chart1.destroy();
-
-     
-    this.logsService.getEnergyProducedByDay().toPromise()
-    .then((data: any) => {
-      // Get all the keys(each meter name) of the returned promise
-      this.metersKeys = Object.keys(data["1D"]);
-              
-      // Get all the values according to each index (meter) 
-      this.metersValues = Object.values(data["1D"]).map(sub => sub);
-      let meterKeys2 = Object.keys(this.metersValues);
+    this.view = view;
 
-      // Re-Initialize Json object
-      this.metersData = [];
-
-      // Json object construction for passing its values to the chartjs datasets according to its requirements
-      for (let prop in meterKeys2) { 
-        let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersKeys[prop];
-        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: this.metersValues[prop].map(obj => obj.total_energy_kWh).reverse()});
-        this.barChartLabels = this.metersValues[0].map(obj => formatDate(obj.dateMin, 'hh:mm:ss','es-Es','-0600')).reverse();
-      }
+    // Chart (re)initialize, to prevent double load on changing range or views
+    if (this.chart1 != undefined){
       this.chart1.destroy();
-      this.chart1 = undefined;
-      // Chart draw
-      this.chart1 = new Chart('canvas', {
-        type: 'bar',
-        options: {
-          title: {
-            display: true,
-          },
-          tooltips: {
-            mode: 'index',
-            callbacks: {
-              // Get the total of the energy produced in every point and show it in the hover tooltip
-              label: function (tooltipItem, data) { 
-                var label = data.datasets[tooltipItem.datasetIndex].label || '';
-                var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
-                var total = 0;
-
-                for (var i = 0; i < data.datasets.length; i++)
-                  total += +data.datasets[i].data[tooltipItem.index];
-
-                if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
-                  return label + " : " + value;
-                }
-                else {
-                  return [label + " : " + value, "TOTAL : " + Math.round(total)];
-                }
-              }
-            }
-          },
-          responsive: true,
-          maintainAspectRatio: false,
-          scales: {
-            xAxes: [{
-              stacked: true,
-            }],
-            yAxes: [{
-              stacked: true
-            }]
-          }
-        },
-        data: {
-          labels: this.barChartLabels,
-          datasets: 
-            this.metersData,
-        }, 
-      });
-      this.chartjs = true;
-    });
-    setTimeout(()=>{
-      Swal.close();
-    }, 2700)
-  }
+    }
+    this.chart1 = undefined;
+    
+    let dateRange:string;
+    if (measureDate === undefined){
+      dateRange = this.initialDate;
+    }
+    else {
+      dateRange = measureDate;
+    }
 
-  onMeasureClickWeek(measureDateBegin?:string, measureDateEnd?:string): void {;
+    // Set default assetID if paramId doesn't come in the function call
+    let assetId:string;
+    if (paramId === undefined){
+      assetId = this.listAssets[0]["id"]; // Grab the first object
+    }
+    else {
+      assetId = paramId;
+    }
+    
+    // Select an interval according to the API permitted param
+    let interval:string;
+    switch (view)
+    { 
+      case "day": 
+        interval = "1D";
+        this.isActive = [true, false, false, false];
+        break; 
+      case "week": 
+        interval = "7D";
+        this.isActive = [false, true, false, false];
+        break; 
+      case "month":
+        interval = "1M";
+        this.isActive = [false, false, true, false];
+        break; 
+      case "mtd": //TO DO
+        interval = "MTD";
+        break;
+      case "year":
+        interval = "YTD";
+        this.isActive = [false, false, false, true];
+        break;
+      default: 
+        console.log("nada");
+    }  
 
-    Swal.fire({
-      allowOutsideClick: false,
-      type: 'info',
-      text: 'Espere por favor...'
-    });
-    Swal.showLoading();
-    this.view = "week";
-    this.isActive = [false, true, false, false];
-    this.chart1.destroy();
- 
-    this.logsService.getEnergyProducedByWeek().toPromise()
+    this.logsService.getEnergyProducedByParams(assetId,interval,dateRange).toPromise()
     .then((data: any) => {
-      // Get all the keys(each meter name) of the returned promise
-      this.metersKeys = Object.keys(data["7D"]);
-      
+      this.metersData = [];      
+      this.metersKeys = Object.keys(data["data"][0]["dataset"]);
+
       // Get all the values according to each index (meter) 
-      this.metersValues = Object.values(data["7D"]).map(sub => sub);
+      this.metersValues = Object.values(data["data"][0]["dataset"]);
+
+      // Get the keys of those values
       let meterKeys2 = Object.keys(this.metersValues);
-      
-      // Re-Initialize Json object
-      this.metersData = [];
 
-      // Json object construction for passing its values to the chartjs datasets according to its requirements
       for (let prop in meterKeys2) { 
-        let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersKeys[prop];
-        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: this.metersValues[prop].map(obj => obj.total_energy_kWh).reverse()});
-        this.barChartLabels = this.metersValues[prop].map(obj => formatDate(obj.dateMax, 'EEEE dd','es-Es','-0600')).reverse();
+        let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersValues[prop]["label"];
+        let measure_values = Object.values(this.metersValues[prop]["data"].map(obj => obj.total_energy_kWh).reverse())
+        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: measure_values });
       }
-      this.chart1.destroy();
-      this.chart1 = undefined;
-      // Chart draw
-      this.chart1 = new Chart('canvas', {
-        type: 'bar',
-        options: {
-          title: {
-            display: true,
-          },
-          tooltips: {
-            mode: 'index',
-            callbacks: {
-              // Get the total of the energy produced in every point and show it in the hover tooltip
-              label: function (tooltipItem, data) { 
-                var label = data.datasets[tooltipItem.datasetIndex].label || '';
-                var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
-                var total = 0;
-
-                for (var i = 0; i < data.datasets.length; i++)
-                  total += +data.datasets[i].data[tooltipItem.index];
-
-                if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
-                  return label + " : " + value;
-                }
-                else {
-                  return [label + " : " + value, "TOTAL : " + Math.round(total)];
-                }
-              }
-            }
-          },
-          responsive: true,
-          maintainAspectRatio: false,
-          scales: {
-            xAxes: [{
-              stacked: true,
-            }],
-            yAxes: [{
-              stacked: true
-            }]
-          }
-        },
-        data: {
-          labels: this.barChartLabels,
-          datasets: 
-            this.metersData,
-        }, 
-      });
-      this.chartjs = true;
-    });
-
-    setTimeout(()=>{
-      Swal.close();
-    }, 2700)   
-  }
 
-  onMeasureClickMonth(measureDateBegin?:string, measureDateEnd?:string): void {
-    Swal.fire({
-      allowOutsideClick: false,
-      type: 'info',
-      text: 'Espere por favor...'
-    });
-    Swal.showLoading();
-    this.view = "month";
-    this.isActive = [false, false, true, false];
-    this.chart1.destroy();
-     
-    this.logsService.getEnergyProducedByMonth().toPromise()
-    .then((data: any) => {
-      // Get all the keys(each meter name) of the returned promise
-      this.metersKeys = Object.keys(data["1M"]);
-      
-      // Get all the values according to each index (meter) 
-      this.metersValues = Object.values(data["1M"]).map(sub => sub);
-      let meterKeys2 = Object.keys(this.metersValues);
-      
-      // Re-Initialize Json object
-      this.metersData = [];
-
-      // Json object construction for passing its values to the chartjs datasets according to its requirements
-      for (let prop in meterKeys2) { 
-        let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersKeys[prop];
-        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: this.metersValues[prop].map(obj => obj.total_energy_kWh).reverse()});
-        this.barChartLabels = this.metersValues[prop].map(obj => formatDate(obj.dateMax, 'dd/MM','es-Es','-0600')).reverse();
+      switch (view){
+        case "day": 
+          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'hh:mm:ss','es-Es','-0600')).reverse();
+          break; 
+        case 'week':
+          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'EEEE dd','es-Es','-0600')).reverse();
+          break;
+        case "year":
+          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'MM/yyyy','es-Es','-0600')).reverse();
+          break;
+        default: 
+          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'dd/MM','es-Es','-0600')).reverse(); 
       }
-      this.chart1.destroy();
-      this.chart1 = undefined;
-      // Chart draw
+
       this.chart1 = new Chart('canvas', {
         type: 'bar',
         options: {
@@ -510,7 +315,7 @@ export class AssetsComponent implements OnInit {
                   return [label + " : " + value, "TOTAL : " + Math.round(total)];
                 }
               }
-            }
+            }         
           },
           responsive: true,
           maintainAspectRatio: false,
@@ -525,8 +330,7 @@ export class AssetsComponent implements OnInit {
         },
         data: {
           labels: this.barChartLabels,
-          datasets: 
-            this.metersData,
+          datasets: this.metersData,
         }, 
       });
       this.chartjs = true;
@@ -534,92 +338,8 @@ export class AssetsComponent implements OnInit {
 
     setTimeout(()=>{
       Swal.close();
-    }, 2700)
+    }, 1200)
 
   }
 
-  onMeasureYear(measureDateBegin?:string, measureDateEnd?:string): void {
-
-    Swal.fire({
-      allowOutsideClick: false,
-      type: 'info',
-      text: 'Espere por favor...'
-    });
-    Swal.showLoading();
-    this.view = "year";
-    this.isActive = [false, false, false, true];  
-    this.chart1.destroy();
-
-    this.http.get(`${environment.apiUrl}/logs/energyProduced/YTD`).toPromise()
-    .then((data: any) => {
-      // Get all the keys(each meter name) of the returned promise
-      this.metersKeys = Object.keys(data["YTD"]);
-
-      // Get all the values according to each index (meter) 
-      this.metersValues = Object.values(data["YTD"]).map(sub => sub);
-      let meterKeys2 = Object.keys(this.metersValues);
-      
-      // Re-Initialize Json object
-      this.metersData = [];
-
-      // Json object construction for passing its values to the chartjs datasets according to its requirements
-      for (let prop in meterKeys2) { 
-        let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersKeys[prop];
-        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: this.metersValues[prop].map(obj => obj.total_energy_kWh).reverse()});
-        this.barChartLabels = this.metersValues[prop].map(obj => formatDate(obj.dateMax, 'MMM','es-Es','-0600')).reverse();
-      }
-      this.chart1.destroy();
-      this.chart1 = undefined;
-      // Chart draw
-      this.chart1 = new Chart('canvas', {
-        type: 'bar',
-        options: {
-          title: {
-            display: true,
-          },
-          tooltips: {
-            mode: 'index',
-            callbacks: {
-              // Get the total of the energy produced in every point and show it in the hover tooltip
-              label: function (tooltipItem, data) { 
-                var label = data.datasets[tooltipItem.datasetIndex].label || '';
-                var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
-                var total = 0;
-
-                for (var i = 0; i < data.datasets.length; i++)
-                  total += +data.datasets[i].data[tooltipItem.index];
-
-                if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
-                  return label + " : " + value;
-                }
-                else {
-                  return [label + " : " + value, "TOTAL : " + Math.round(total)];
-                }
-              }
-            }
-          },
-          responsive: true,
-          maintainAspectRatio: false,
-          scales: {
-            xAxes: [{
-              stacked: true,
-            }],
-            yAxes: [{
-              stacked: true
-            }]
-          }
-        },
-        data: {
-          labels: this.barChartLabels,
-          datasets: 
-            this.metersData,
-        }, 
-      });
-      this.chartjs = true;
-    });
-    
-    setTimeout(()=>{
-      Swal.close();
-    }, 3200)
-  }
 }

+ 0 - 53
src/app/components/tests/tests.component.html

@@ -1,53 +0,0 @@
-<h2 class="floating-title">{{title}}</h2>
-<div class="main-content">
-  <div class="row align-container">
-    <div class="col-12">    
-      <label for="sel3">Plantas</label>
-    </div>
-  </div>
-  <div class="row">
-    <div class="col-lg-6 col-sm-4">
-      <div class="align-container">
-        <select class="custom-select" (change)="onChangeObj($event)" name="sel3">
-          <option *ngFor="let item of listAssets" [selected]="item.id===organizationId" [value]="item.id" >{{item.name}}</option>
-        </select>
-      </div>
-      <br>
-    </div>
-
-  </div>
-
-  <!-- Chartjs potency generation graphic -->
-  <div class="row align-container">
-    <div class="col-lg-12 col-md-12 col-sm-12">
-      <div class="widget">
-        <div class="mini-stats">
-          <!--
-          <div class="chart-container" style="display:none;">
-            <canvas baseChart #baseChart="base-chart" [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions"
-              [legend]="barChartLegend" [chartType]="barChartType"></canvas>
-          </div>
-          -->
-
-          <div class="chart-container" >
-            <canvas id="canvas">{{ chart1 }}</canvas>
-          </div>
-
-          <p>Seleccione un rango de visualización</p>
-
-          <button class="btn" [class.btn-success]='isActive[0]' (click)="onMeasureClickRange('day')">Día</button>
-          <button class="btn" [class.btn-success]='isActive[1]' (click)="onMeasureClickRange('week')">Semana</button>
-          <button class="btn" [class.btn-success]='isActive[2]' (click)="onMeasureClickRange('month')">Mes</button>
-          <button class="btn" [class.btn-success]='isActive[3]' (click)="onMeasureClickRange('year')">Año</button>
-          <div class="input-box-container">
-            <input class="input-box" placeholder="Click to select a date" 
-              angular-mydatepicker name="mydate" (click)="dp.toggleCalendar()" 
-              [(ngModel)]="model" [options]="myDpOptions" (dateChanged)="onDateChanged($event)" 
-              #dp="angular-mydatepicker"/>
-          </div>
-        </div>
-      </div>
-    </div>
-  </div>
-
-</div>

+ 0 - 171
src/app/components/tests/tests.component.scss

@@ -1,171 +0,0 @@
-.input-box-container {
-  display: inline-block;
-  margin-left: 15px;
-  position: relative;
-  border-collapse: separate;
-  
-  input {
-    margin: 5px 0 0;
-    font-family: inherit;
-    font-size: inherit;
-    line-height: inherit;
-    padding: 6px;
-  }
-}
-
-
-
-table {
-  width: 100%;
-}
-
-.mat-form-field {
-  font-size: 14px;
-  width: 100%;
-}
-
-.example-loading-shade {
-  position: absolute;
-  top: 0;
-  left: 0;
-  bottom: 56px;
-  right: 0;
-  background: rgba(0, 0, 0, 0.15);
-  z-index: 1;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-}
-
-.example-rate-limit-reached {
-  color: #980000;
-  max-width: 360px;
-  text-align: center;
-}
-
-/* Structure */
-.example-container {
-  position: relative;
-  min-height: 200px;
-}
-
-.example-table-container {
-  position: relative;
-  //max-height: 400px;
-  overflow: auto;
-}
-
-.energy-stats {
-  height: 122px;
-}
-
-.widget {
-  background: #ffffff none repeat scroll 0 0;
-  float: left;
-  margin-top: 14px;
-  position: relative;
-  width: 100%;
-  border-radius: 5px;
-
-  .chart-padding {
-    padding: 10px;
-  }
-
-  .mini-stats {
-    background: #ffffff none repeat scroll 0 0;
-    border-radius: 5px;
-    float: left;
-    padding: 10px 15px;
-    width: 100%;
-    height: inherit;
-
-    p {
-      color: #878888;
-      //display: block;
-      font-size: 14px;
-      line-height: 35px;
-      margin: 6px 0 0;
-      text-transform: uppercase;
-      width: auto;
-    }
-
-    span {
-      border: 1px solid;
-      border-radius: 50%;
-      color: #fff;
-      //float: left;
-      font-size: 35px;
-      height: 60px;
-      line-height: 60px;
-      text-align: center;
-      width: 60px;
-      position: absolute;
-      right: 20px;
-      bottom: 15px;
-      //display: block;
-    }
-
-    h3 {
-      margin: 10px 0 0;
-      font-size: 2rem;
-      font-weight: 400;
-    }
-
-  }
-
-  .enviroment-stats {
-    background: #ffffff none repeat scroll 0 0;
-    border-radius: 5px;
-    padding: 20px;
-    display: table;
-
-    .enviromental-icon {
-      height: 128px;
-      display: table-cell;
-      vertical-align: middle;
-    }
-
-    .enviromental-text {
-      line-height: 1.2;
-      display: table-cell;
-      font-size: 1rem;
-      text-transform: initial;
-      padding-left: 10px;
-      vertical-align: middle;
-
-      span {
-        float: none;
-        height: auto;
-        margin: 0;
-        width: auto;
-        display: inline;
-        border: none;
-        font-size: 1.2rem;
-        font-weight: bold;
-        color: #386641;
-        vertical-align: middle;
-      }
-    }
-
-  }
-}
-
-.chart-container {
-  display: block; 
-  height:40vh; 
-  position: relative;
-}
-
-
-
-@media screen and (min-width: 960px) {
-  .mini-stats {
-    
-    p,
-    span,
-    h3 {
-      display: block;
-    }
-
-  }
-}

+ 0 - 25
src/app/components/tests/tests.component.spec.ts

@@ -1,25 +0,0 @@
-import { async, ComponentFixture, TestBed } from '@angular/core/testing';
-
-import { TestsComponent } from './tests.component';
-
-describe('TestsComponent', () => {
-  let component: TestsComponent;
-  let fixture: ComponentFixture<TestsComponent>;
-
-  beforeEach(async(() => {
-    TestBed.configureTestingModule({
-      declarations: [ TestsComponent ]
-    })
-    .compileComponents();
-  }));
-
-  beforeEach(() => {
-    fixture = TestBed.createComponent(TestsComponent);
-    component = fixture.componentInstance;
-    fixture.detectChanges();
-  });
-
-  it('should create', () => {
-    expect(component).toBeTruthy();
-  });
-});

+ 0 - 335
src/app/components/tests/tests.component.ts

@@ -1,335 +0,0 @@
-import { Component, OnInit, ViewChild,OnChanges } from '@angular/core';
-import { Chart, ChartOptions, ChartType, ChartDataSets } from 'chart.js';
-import { Label, BaseChartDirective } from 'ng2-charts';
-
-import { MeasuresService } from 'src/app/services/measures.service';
-import { PlantsService } from 'src/app/services/plants.service';
-import { LogsService } from 'src/app/services/logs.service';
-
-import { OrganizationsService } from '@app/services/organizations.service';
-
-import { ActivatedRoute } from '@angular/router';
-import { Observable, forkJoin } from 'rxjs';
-
-
-import * as moment from 'moment';
-
-import Swal from 'sweetalert2';
-import { environment } from '@environments/environment';
-import { HttpClient } from '@angular/common/http';
-import { formatDate } from '@angular/common';
-
-import {AngularMyDatePickerDirective,IAngularMyDpOptions, IMyDateModel} from 'angular-mydatepicker';
-
-
-
-@Component({
-  selector: 'app-tests',
-  templateUrl: './tests.component.html',
-  styleUrls: ['./tests.component.scss']
-})
-
-
-export class TestsComponent implements OnInit {
- 
-  title = "Plantas";
-
-  organizationId:string;
-  listAssets:any;
-  listEnergyProduced:any;
-  error:boolean;
-  errorMessage:string;
-  errortest:any;
-  chartjs:boolean;
-  chart1: Chart;
-  metersKeys:any;
-  metersValues:any;
-  view:string;
-
-
-  //For daterange
-  daysLabels:any = {su: 'Dom', mo: 'Lun', tu: 'Mar', we: 'Mie', th: 'Jue', fr: 'Vie', sa: 'Sab'};
-  monthsLabels:any = { 1: 'Ene', 2: 'Feb', 3: 'Mar', 4: 'Abr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Ago', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dic' };
-  todayBtnTxt:string = 'Hoy';
-  
-  myDpOptions: IAngularMyDpOptions = {
-    dateRange: false,
-    dateFormat: 'dd/mm/yyyy',
-    dayLabels: this.daysLabels,
-    monthLabels: this.monthsLabels,
-    // other options are here...
-  };
-
-  myDateInit: boolean = true;
-  model: IMyDateModel = null;
-
-  // For chartjs
-  tsLabels: any[];
-  barChartColors:any = ['#3c8dbc', '#00a65a', '#f56954']
-  metersData:any;
-  initialDate:any;
-
-
-  public barChartType: ChartType;
-  public barChartLegend:boolean;
-  public barChartLabels: Label[];
-  public barChartOptions: ChartOptions;
-  public barChartData: ChartDataSets[];
-
-  isActive:[boolean,boolean,boolean,boolean]; //Activated param (chart)
-
-  constructor(
-    private orgService: OrganizationsService, 
-    private route: ActivatedRoute, 
-    private plantsService: PlantsService,
-    private http: HttpClient,
-    private logsService: LogsService,
-    private measService: MeasuresService) {
-      
-      Swal.fire({
-        allowOutsideClick: false,
-        type: 'info',
-        text: 'Espere por favor...'
-      });
-      Swal.showLoading();
-      
-  }
-
-  @ViewChild("baseChart",null) chart: BaseChartDirective;
-
-  ngOnInit() {
-    
-    let plants = this.plantsService.getAllAssets();
-
-    let energy_produced = this.plantsService.getAssetsProducedEnergy();
-
-    // Default date is today and set it on a string var and initialize dateRange plugin
-    this.initialDate = new Date().toISOString().slice(0, 10);
-    if (this.myDateInit) {
-      let begin: Date = new Date();
-      this.model = {
-        isRange: false, 
-        singleDate: {
-          date: {
-            year: begin.getFullYear(), month: begin.getMonth() + 1, day: begin.getDate()
-          }
-        }
-      };
-    }
-    
-    // Observable of two objects
-    forkJoin([plants, energy_produced]).subscribe(results => {
-      console.log(results[0]["data"]);
-      if (localStorage.getItem("email") == "inverlec@grupomerelec.com"){
-        this.listAssets = [
-          {
-            name: "Inversiones MERELEC S.A de C.V",
-            id: '5d70330cb288f25b679c68a8'
-          },
-          {
-            name: "Inversiones MERELEC 2 S.A de C.V",
-            id: '5d70330cb288f25b679c68n8'
-          },          
-        ]
-
-        this.view = "month";
-        this.onMeasureClickRange(this.view, this.initialDate);
-
-        console.log(this.listAssets[0]["id"]);
-      }
-      else {
-        this.listAssets = results[0]["data"];
-        console.log(this.listAssets[0]["id"]);
-        this.view = "month";
-        this.onMeasureClickRange(this.view, this.initialDate);
-      }
-      
-      // Energy produced given an assetID
-      this.listEnergyProduced = results[1];      
-    },
-    (err) => {
-      Swal.fire({
-        type: 'error',
-        title: 'Error en el servidor',
-        text: "No su pudo obtener la informacion"
-      });
-    });    
-
-    this.chartjs = true;
-    setTimeout(()=>{
-      Swal.close();
-    }, 2700);
- 
-  }
- 
-  // Default check asset dropdown if a value is equal to an assetID
-  isSelected(){
-    if(this.organizationId!=undefined){
-      return true;
-    }
-    else{
-      return false;
-    }
-  }
-
-  // Trigger again the chart with the selected assetID
-  onChangeObj(event:any) {
-    this.onMeasureClickRange(this.view, this.initialDate, event.target.value);
-  }
-
-  // Change the date range of the chart, according to the selected view (daily, weekly, ...)
-  onDateChanged(event: IMyDateModel) {
-    let endDate = `${event.singleDate.date.year}-${event.singleDate.date.month}-${event.singleDate.date.day}`;
-    switch (this.view)
-    { 
-      case "day": 
-        this.onMeasureClickRange(this.view, endDate);
-        break; 
-      case "week": 
-        this.onMeasureClickRange(this.view, endDate);
-        break; 
-      case "month": 
-        this.onMeasureClickRange(this.view, endDate);
-        break; 
-      case "year":
-        this.onMeasureClickRange(this.view, endDate);
-        break;
-      default: 
-        console.log("nada");
-    } 
-  }
-
-  // Draw a measure chart using chartjs, given some params, view, for daily, weekly, monthly or yearly measures;
-  // measureDate, for a date range given a view and a paramID, for an specific assetID selected in the dropdown  
-  onMeasureClickRange(view:string, measureDate?:string, paramId?:string): void {
-    Swal.fire({
-      allowOutsideClick: false,
-      type: 'info',
-      text: 'Espere por favor...'
-    });
-    Swal.showLoading();
-    this.view = view;
-
-    // Chart (re)initialize, to prevent double load on changing range or views
-    if (this.chart1 != undefined){
-      this.chart1.destroy();
-    }
-    this.chart1 = undefined;
-    
-    let dateRange:string;
-    if (measureDate === undefined){
-      dateRange = this.initialDate;
-    }
-    else {
-      dateRange = measureDate;
-    }
-
-    // Set default assetID if paramId doesn't come in the function call
-    let assetId:string;
-    if (paramId === undefined){
-      assetId = this.listAssets[0]["id"]; // Grab the first object
-    }
-    else {
-      assetId = paramId;
-    }
-    
-    // Select an interval according to the API permitted param
-    let interval:string;
-    switch (view)
-    { 
-      case "day": 
-        interval = "1D";
-        this.isActive = [true, false, false, false];
-        break; 
-      case "week": 
-        interval = "7D";
-        this.isActive = [false, true, false, false];
-        break; 
-      case "month":
-        interval = "1M";
-        this.isActive = [false, false, true, false];
-        break; 
-      case "mtd": //TO DO
-        interval = "MTD";
-        break;
-      case "year":
-        interval = "YTD";
-        this.isActive = [false, false, false, true];
-        break;
-      default: 
-        console.log("nada");
-    }  
-
-    this.logsService.getEnergyProducedByParams(assetId,interval,dateRange).toPromise()
-    .then((data: any) => {
-      this.metersData = [];
-      
-      this.metersKeys = Object.keys(data["data"][0]["dataset"]);
-
-      // Get all the values according to each index (meter) 
-      this.metersValues = Object.values(data["data"][0]["dataset"]);
-
-      let meterKeys2 = Object.keys(this.metersValues);
-
-      for (let prop in meterKeys2) { 
-        let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersValues[prop]["label"];
-        //let keys = Object.keys();
-        let test = Object.values(this.metersValues[prop]["data"].map(obj => obj.total_energy_kWh).reverse())
-
-        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: test });
-        this.barChartLabels = this.metersValues[prop]["data"].map(obj => formatDate(obj.dateMax, 'dd/MM','es-Es','-0600')).reverse();
-      }
-
-      this.chart1 = new Chart('canvas', {
-        type: 'bar',
-        options: {
-          title: {
-            display: true,
-          },
-          tooltips: {
-            mode: 'index',
-            callbacks: {
-              // Get the total of the energy produced in every point and show it in the hover tooltip
-              label: function (tooltipItem, data) { 
-                var label = data.datasets[tooltipItem.datasetIndex].label || '';
-                var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
-                var total = 0;
-
-                for (var i = 0; i < data.datasets.length; i++)
-                  total += +data.datasets[i].data[tooltipItem.index];
-
-                if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
-                  return label + " : " + value;
-                }
-                else {
-                  return [label + " : " + value, "TOTAL : " + Math.round(total)];
-                }
-              }
-            }         
-          },
-          responsive: true,
-          maintainAspectRatio: false,
-          scales: {
-            xAxes: [{
-              stacked: true,
-            }],
-            yAxes: [{
-              stacked: true
-            }]
-          }
-        },
-        data: {
-          labels: this.barChartLabels,
-          datasets: this.metersData,
-        }, 
-      });
-      this.chartjs = true;
-    });
-
-    setTimeout(()=>{
-      Swal.close();
-    }, 1200)
-
-  }
-
-}

+ 0 - 2
src/app/layouts/admin/admin.module.ts

@@ -16,7 +16,6 @@ import { DashboardComponent } from '../../components/dashboard/dashboard.compone
 import { ProfileComponent } from '../../components/profile/profile.component';
 import { AssetsComponent } from '../../components/assets/assets.component';
 import { OrganizationsComponent } from '../../components/organizations/organizations.component';
-import { TestsComponent } from '../../components/tests/tests.component';
 
 import { PluginsModule } from '../../components/plugins/plugins.module';
 
@@ -63,7 +62,6 @@ import {
     ProfileComponent,
     AssetsComponent,
     OrganizationsComponent,
-    TestsComponent
   ]
 })
 

+ 0 - 5
src/app/layouts/admin/admin.routing.ts

@@ -4,7 +4,6 @@ import { DashboardComponent } from '../../components/dashboard/dashboard.compone
 import { ProfileComponent } from '../../components/profile/profile.component';
 import { AssetsComponent } from '@app/components/assets/assets.component';
 import { OrganizationsComponent } from '@app/components/organizations/organizations.component';
-import { TestsComponent } from '@app/components/tests/tests.component';
 
 /*
 import { TableListComponent } from '../../table-list/table-list.component';
@@ -30,10 +29,6 @@ export const AdminLayoutRoutes: Routes = [
   { path: 'organizations', 
     component: OrganizationsComponent,
     data: {title: "Listado de organizaciones"}
-  },
-  { path: 'tests', 
-    component: TestsComponent,
-    data: {title: "Listado de tst"}
   }
   /*
   { path: 'table-list',     component: TableListComponent },