github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/Decentralized-Energy-Composer-master/angular-app/src/app/TransactionRU/TransactionRU.component.ts (about)

     1  import { Component, OnInit, Input } from '@angular/core';
     2  import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
     3  import { Observable } from 'rxjs/Observable';
     4  import { TransactionRUService } from './TransactionRU.service';
     5  import 'rxjs/add/operator/toPromise';
     6  
     7  //provide associated components
     8  @Component({
     9  	selector: 'app-TransactionRU',
    10  	templateUrl: './TransactionRU.component.html',
    11  	styleUrls: ['./TransactionRU.component.css'],
    12    	providers: [TransactionRUService]
    13  })
    14  
    15  //TransactionRRComponent class
    16  export class TransactionRUComponent {
    17  
    18    //define rate of conversion
    19    private utilityCoinsPerEnergy = 1;
    20    private utilityEnergyPerCoins = (1 / this.utilityCoinsPerEnergy).toFixed(3);  
    21    
    22    //define variables
    23    private coinsExchanged;
    24    private energyValue;
    25  
    26    myForm: FormGroup;
    27    private errorMessage;
    28    private transactionFrom;
    29  
    30    private allResidents;
    31    private allUtilityCompanys;
    32  
    33    private resident;
    34    private utiltyCompany;  
    35    private energyToCoinsObj;
    36    private transactionID;
    37  
    38    private energyReceiverAsset;
    39    private energyProducerAsset;  
    40    private coinsCreditAsset;
    41    private coinsDebitAsset;
    42  
    43    //initialize form variables
    44    formResidentID = new FormControl("", Validators.required);
    45  	formUtilityID = new FormControl("", Validators.required); 
    46    action = new FormControl("", Validators.required); 
    47  	value = new FormControl("", Validators.required);
    48    
    49    constructor(private serviceTransaction:TransactionRUService, fb: FormBuilder) {
    50      //intialize form    
    51  	  this.myForm = fb.group({		  
    52  		  formResidentID:this.formResidentID,
    53  		  formUtilityID:this.formUtilityID,
    54        action:this.action,
    55        value:this.value,      
    56      });    
    57    };
    58  
    59    //on page initialize, load all residents and utility companies
    60    ngOnInit(): void {
    61      this.transactionFrom  = true;
    62      this.loadAllResidents()
    63      .then(() => {                     
    64              this.loadAllUtilityCompanys();
    65      });
    66      
    67    }
    68  
    69    //get all Residents
    70    loadAllResidents(): Promise<any> {
    71      
    72      //retrieve all residents in the tempList array
    73      let tempList = [];
    74  
    75      //call serviceTransaction to get all resident objects
    76      return this.serviceTransaction.getAllResidents()
    77      .toPromise()
    78      .then((result) => {
    79        this.errorMessage = null;
    80        
    81        //append tempList with the resident objects returned
    82        result.forEach(resident => {
    83          tempList.push(resident);
    84        });
    85  
    86        //assign tempList to allResidents
    87        this.allResidents = tempList;
    88      })
    89      .catch((error) => {
    90          if(error == 'Server error'){
    91              this.errorMessage = "Could not connect to REST server. Please check your configuration details";
    92          }
    93          else if(error == '404 - Not Found'){
    94  				this.errorMessage = "404 - Could not find API route. Please check your available APIs."
    95          }
    96          else{
    97              this.errorMessage = error;
    98          }
    99      });
   100    }
   101  
   102    //get all Utility Companies
   103    loadAllUtilityCompanys(): Promise<any> {
   104      
   105      //retrieve all utility companies in the tempList array
   106      let tempList = [];
   107  
   108      //call serviceTransaction to get all utility company objects
   109      return this.serviceTransaction.getAllUtilityCompanys()
   110      .toPromise()
   111      .then((result) => {
   112        this.errorMessage = null;
   113        
   114        //append tempList with the utilty company objects returned
   115        result.forEach(utilityCompany => {
   116          tempList.push(utilityCompany);
   117        });
   118  
   119        //assign tempList to allUtilityCompanys
   120        this.allUtilityCompanys = tempList;
   121      })
   122      .catch((error) => {
   123          if(error == 'Server error'){
   124              this.errorMessage = "Could not connect to REST server. Please check your configuration details";
   125          }
   126          else if(error == '404 - Not Found'){
   127  				this.errorMessage = "404 - Could not find API route. Please check your available APIs."
   128          }
   129          else{
   130              this.errorMessage = error;
   131          }
   132      });
   133    }
   134  
   135    //execute transaction
   136    execute(form: any): Promise<any> {
   137            
   138  
   139      //loop through all residents to find match with user provided resident
   140      for (let resident of this.allResidents) {
   141        if(resident.residentID == this.formResidentID.value){
   142          this.resident = resident;
   143        }     
   144      }
   145  
   146      //loop through all utility companies to find match with user provided utility company
   147      for (let utilityCompany of this.allUtilityCompanys) {
   148          console.log(utilityCompany.utilityID); 
   149        
   150        if(utilityCompany.utilityID == this.formUtilityID.value){
   151          this.utiltyCompany = utilityCompany;
   152        }     
   153      }
   154  
   155      //depending on action, identify energy and coins assets to be debited/credited
   156      if(this.action.value == 'buyEnergy') {
   157          this.energyValue = this.value.value;
   158          this.energyReceiverAsset = this.resident.energy;
   159          this.energyProducerAsset = this.utiltyCompany.energy;  
   160          this.coinsCreditAsset = this.utiltyCompany.coins;
   161          this.coinsDebitAsset = this.resident.coins;
   162      }
   163      else if(this.action.value == 'sellEnergy') {
   164          this.energyValue = this.value.value;
   165          this.energyReceiverAsset = this.utiltyCompany.energy;
   166          this.energyProducerAsset = this.resident.energy;  
   167          this.coinsCreditAsset = this.resident.coins;
   168          this.coinsDebitAsset = this.utiltyCompany.coins;
   169      }    
   170  
   171      //identify energy and coins id which will be debited from the string
   172      var splitted_energyID = this.energyProducerAsset.split("#", 2); 
   173      var energyID = String(splitted_energyID[1]);
   174  
   175      var splitted_coinsID = this.coinsDebitAsset.split("#", 2); 
   176      var coinsID = String(splitted_coinsID[1]);
   177  
   178      //calculate coins exchanges from the rate
   179      this.coinsExchanged = this.utilityCoinsPerEnergy * this.energyValue;
   180  
   181      //create transaction object
   182      this.energyToCoinsObj = {
   183        $class: "org.decentralized.energy.network.EnergyToCoins",
   184        "energyRate": this.utilityCoinsPerEnergy,
   185        "energyValue": this.energyValue,
   186        "coinsInc": this.coinsCreditAsset,
   187        "coinsDec": this.coinsDebitAsset,
   188        "energyInc": this.energyReceiverAsset,
   189        "energyDec": this.energyProducerAsset
   190      };
   191  
   192      //check coins and energy assets for enough funds before creating transaction
   193      //call serviceTransaction to get energy asset
   194      return this.serviceTransaction.getEnergy(energyID)
   195      .toPromise()
   196      .then((result) => {
   197        this.errorMessage = null;
   198        //check if enough value
   199        if(result.value) {
   200          if ((result.value - this.energyValue) < 0 ){          
   201            this.errorMessage = "Insufficient energy in producer account";
   202            return false;
   203          }
   204          return true;
   205        }
   206      })
   207      .then((checkProducerEnergy) => {
   208        //if positive on sufficient energy, then check coins asset whether sufficient coins
   209        if(checkProducerEnergy)
   210        {        
   211          //call serviceTransaction to get coins asset
   212          this.serviceTransaction.getCoins(coinsID)
   213          .toPromise()
   214          .then((result) => {
   215            this.errorMessage = null;
   216            //check if enough value
   217            if(result.value) {
   218              if ((result.value - this.coinsExchanged) < 0 ){              
   219                this.errorMessage = "Insufficient coins in consumer account";
   220                return false;
   221              }
   222              return true;
   223            }
   224          })
   225          .then((checkConsumerCoins) => {
   226            //if positive on sufficient coins, then call transaction
   227            if(checkConsumerCoins)
   228            {
   229              //call serviceTransaction call the energyToCoins transaction with energyToCoinsObj as parameter
   230              this.serviceTransaction.energyToCoins(this.energyToCoinsObj)
   231              .toPromise()
   232              .then((result) => {
   233                this.errorMessage = null;
   234                this.transactionID = result.transactionId;
   235                console.log(result);
   236              })
   237              .catch((error) => {
   238                  if(error == 'Server error'){
   239                      this.errorMessage = "Could not connect to REST server. Please check your configuration details";
   240                  }
   241                  else if(error == '404 - Not Found'){
   242                  this.errorMessage = "404 - Could not find API route. Please check your available APIs."
   243                  }
   244                  else{
   245                      this.errorMessage = error;
   246                  }
   247              }).then(() => {
   248                this.transactionFrom = false;
   249              });
   250            }
   251          });
   252        }        
   253      });
   254    }        
   255  }