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