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

     1  import { Component, OnInit, Input } from '@angular/core';
     2  import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
     3  import { ResidentService } from './Resident.service';
     4  import 'rxjs/add/operator/toPromise';
     5  
     6  //provide associated components
     7  @Component({
     8  	selector: 'app-Resident',
     9  	templateUrl: './Resident.component.html',
    10  	styleUrls: ['./Resident.component.css'],
    11    	providers: [ResidentService]
    12  })
    13  
    14  //ResidentComponent class
    15  export class ResidentComponent {
    16  
    17    //define variables
    18    myForm: FormGroup;
    19  
    20    private allResidents;
    21    private resident;
    22    private currentId;
    23    private errorMessage;
    24  
    25    private coins;
    26    private energy;
    27    private cash;
    28  
    29    //initialize form variables
    30    residentID = new FormControl("", Validators.required);
    31    firstName = new FormControl("", Validators.required);
    32    lastName = new FormControl("", Validators.required);
    33    coinsValue = new FormControl("", Validators.required);
    34    energyValue = new FormControl("", Validators.required);
    35    energyUnits = new FormControl("", Validators.required);
    36    cashValue = new FormControl("", Validators.required);
    37    cashCurrency = new FormControl("", Validators.required);
    38        
    39    constructor(private serviceResident:ResidentService, fb: FormBuilder) {
    40      //intialize form
    41      this.myForm = fb.group({       
    42            residentID:this.residentID,
    43            firstName:this.firstName,      
    44            lastName:this.lastName,
    45            coinsValue:this.coinsValue,
    46            energyValue:this.energyValue,
    47            energyUnits:this.energyUnits,
    48            cashValue:this.cashValue,
    49            cashCurrency:this.cashCurrency          
    50      });
    51    };
    52  
    53    //on page initialize, load all residents
    54    ngOnInit(): void {
    55      this.loadAll();
    56    }
    57  
    58    //load all residents and the energy, coins and cash assets associated to it 
    59    loadAll(): Promise<any>  {
    60      
    61      //retrieve all residents in the residentList array
    62      let residentList = [];
    63  
    64      //call serviceResident to get all resident objects
    65      return this.serviceResident.getAllResidents()
    66      .toPromise()
    67      .then((result) => {
    68        this.errorMessage = null;
    69        
    70        //append residentList with the resident objects returned
    71        result.forEach(resident => {
    72          residentList.push(resident);
    73        });     
    74      })
    75      .then(() => {
    76  
    77        //for each resident, get the associated coins, energy and cash asset
    78        for (let resident of residentList) {
    79  
    80          //get coinsID from the resident.coins string
    81          var splitted_coinsID = resident.coins.split("#", 2); 
    82          var coinsID = String(splitted_coinsID[1]);
    83  
    84          //call serviceResident to get coins asset
    85          this.serviceResident.getCoins(coinsID)
    86          .toPromise()
    87          .then((result) => {
    88            this.errorMessage = null;
    89            //update resident
    90            if(result.value){
    91              resident.coinsValue = result.value;
    92            }
    93          });
    94  
    95          //get energyID from the resident.energy string
    96          var splitted_energyID = resident.energy.split("#", 2); 
    97          var energyID = String(splitted_energyID[1]);
    98          
    99          //call serviceResident to get energy asset
   100          this.serviceResident.getEnergy(energyID)
   101          .toPromise()
   102          .then((result) => {
   103            this.errorMessage = null;
   104            //update resident
   105            if(result.value){
   106              resident.energyValue = result.value;
   107            }
   108            if(result.units){
   109              resident.energyUnits = result.units;
   110            }
   111          });
   112  
   113          //get cashID from the resident.cash string
   114          var splitted_cashID = resident.cash.split("#", 2); 
   115          var cashID = String(splitted_cashID[1]);
   116          
   117          //call serviceResident to get cash asset
   118          this.serviceResident.getCash(cashID)
   119          .toPromise()
   120          .then((result) => {
   121            this.errorMessage = null;
   122            //update resident
   123            if(result.value){
   124              resident.cashValue = result.value;
   125            }
   126            if(result.currency){
   127              resident.cashCurrency = result.currency;
   128            }
   129          });
   130        }
   131  
   132        //assign residentList to allResidents
   133        this.allResidents = residentList;
   134      });
   135  
   136    }
   137  
   138    //add Resident participant
   139    addResident(form: any): Promise<any> {
   140  
   141      //create assets for resisent and the resident on the blockchain network
   142      return this.createAssetsResident()
   143        .then(() => {           
   144          this.errorMessage = null;
   145          this.myForm.setValue({
   146              "residentID":null,
   147              "firstName":null,
   148              "lastName":null,
   149              "coinsValue":null,
   150              "energyValue":null,
   151              "energyUnits":null,
   152              "cashValue":null,
   153              "cashCurrency":null
   154          });
   155        })
   156      .catch((error) => {
   157          if(error == 'Server error'){
   158              this.errorMessage = "Could not connect to REST server. Please check your configuration details";
   159          }
   160          else if (error == '500 - Internal Server Error') {
   161            this.errorMessage = "Input error";
   162          }
   163          else{
   164              this.errorMessage = error;
   165          }
   166      });
   167    }
   168  
   169    //create coins, energy and cash assets associated with the Resident, followed by the Resident
   170    createAssetsResident(): Promise<any> {
   171  
   172      //create coins asset json
   173      this.coins = {
   174        $class: "org.decentralized.energy.network.Coins",
   175            "coinsID":"CO_" + this.residentID.value,
   176            "value":this.coinsValue.value,
   177            "ownerID":this.residentID.value,
   178            "ownerEntity":'Resident'
   179      };
   180      
   181      //create energy asset json
   182      this.energy = {
   183        $class: "org.decentralized.energy.network.Energy",
   184            "energyID":"EN_" + this.residentID.value,
   185            "units":this.energyUnits.value,
   186            "value":this.energyValue.value,
   187            "ownerID":this.residentID.value,
   188            "ownerEntity":'Resident'        
   189      };
   190  
   191      //create cash asset json
   192      this.cash = {
   193        $class: "org.decentralized.energy.network.Cash",
   194            "cashID":"CA_" + this.residentID.value,
   195            "currency":this.cashCurrency.value,
   196            "value":this.cashValue.value,
   197            "ownerID":this.residentID.value,
   198            "ownerEntity":'Resident'        
   199      };    
   200      
   201      //create resident participant json
   202      this.resident = {
   203        $class: "org.decentralized.energy.network.Resident",
   204            "residentID":this.residentID.value,
   205            "firstName":this.firstName.value,
   206            "lastName":this.lastName.value,
   207            "coins":"CO_" + this.residentID.value,
   208            "cash":"CA_" + this.residentID.value,
   209            "energy":"EN_" + this.residentID.value,
   210        };    
   211  
   212      //call serviceResident to add coins asset, pass created coins asset json as parameter
   213      return this.serviceResident.addCoins(this.coins)
   214      .toPromise()
   215  		.then(() => {
   216        
   217        //call serviceResident to add energy asset, pass created energy asset json as parameter
   218  			this.serviceResident.addEnergy(this.energy)
   219        .toPromise()
   220  		  .then(() => {
   221  
   222          //call serviceResident to add cash asset, pass created cash asset json as parameter
   223          this.serviceResident.addCash(this.cash)
   224          .toPromise()
   225          .then(() => {
   226            
   227            //call serviceResident to add resident participant, pass created resident participant json as parameter
   228            this.serviceResident.addResident(this.resident)
   229            .toPromise()
   230            .then(() => {
   231              //reload page to display the created resident
   232              location.reload();
   233            });            
   234          });
   235  		  });   
   236  		});
   237    }
   238  
   239    //allow update name of Resident
   240    updateResident(form: any): Promise<any> {
   241      
   242      //create json of resident participant to update name
   243      this.resident = {
   244        $class: "org.decentralized.energy.network.Resident",          
   245        "firstName":this.firstName.value,          
   246        "lastName":this.lastName.value,
   247        "coins": "resource:org.decentralized.energy.network.Coins#CO_" + form.get("residentID").value,
   248        "cash": "resource:org.decentralized.energy.network.Cash#CA_" + form.get("residentID").value,
   249        "energy": "resource:org.decentralized.energy.network.Energy#EN_" + form.get("residentID").value
   250      };
   251  
   252      //call serviceResident to update resident, pass residentID of which resident to update as parameter
   253      return this.serviceResident.updateResident(form.get("residentID").value,this.resident)
   254  		.toPromise()
   255  		.then(() => {
   256  			this.errorMessage = null;
   257  		})
   258  		.catch((error) => {
   259              if(error == 'Server error'){
   260  				this.errorMessage = "Could not connect to REST server. Please check your configuration details";
   261  			}
   262              else if(error == '404 - Not Found'){
   263  				this.errorMessage = "404 - Could not find API route. Please check your available APIs."
   264  			}
   265  			else{
   266  				this.errorMessage = error;
   267  			}
   268      });
   269    }
   270  
   271    //delete Resident and the coins and cash assets associated to it
   272    deleteResident(): Promise<any> {
   273  
   274      //call serviceResident to delete resident, pass residentID as parameter
   275      return this.serviceResident.deleteResident(this.currentId)
   276  		.toPromise()
   277  		.then(() => {
   278        this.errorMessage = null;
   279        
   280        //call serviceResident to delete coins asset, pass coinsID as parameter
   281        this.serviceResident.deleteCoins("CO_"+this.currentId)
   282        .toPromise()
   283        .then(() => {
   284  
   285            //call serviceResident to delete energy asset, pass energyID as parameter
   286            this.serviceResident.deleteEnergy("EN_"+this.currentId)
   287            .toPromise()
   288            .then(() => {
   289  
   290                //call serviceResident to delete cash asset, pass cashID as parameter
   291                this.serviceResident.deleteCash("CA_"+this.currentId)
   292                .toPromise()
   293                .then(() => {
   294                    console.log("Deleted")
   295                });
   296            });
   297        });            
   298  		})
   299  		.catch((error) => {
   300              if(error == 'Server error'){
   301  				this.errorMessage = "Could not connect to REST server. Please check your configuration details";
   302  			}
   303  			else if(error == '404 - Not Found'){
   304  				this.errorMessage = "404 - Could not find API route. Please check your available APIs."
   305  			}
   306  			else{
   307  				this.errorMessage = error;
   308  			}
   309      });
   310    }
   311  
   312    //set id
   313    setId(id: any): void{
   314      this.currentId = id;
   315    }
   316  
   317    //get form based on residentID
   318    getForm(id: any): Promise<any>{
   319  
   320      //call serviceResident to get resident participant object
   321      return this.serviceResident.getResident(id)
   322      .toPromise()
   323      .then((result) => {
   324  			this.errorMessage = null;
   325        let formObject = {        
   326              "residentID":null,          
   327              "firstName":null,          
   328              "lastName":null,
   329              "coinsValue":null,          
   330              "energyValue":null,          
   331              "energyUnits":null,          
   332              "cashValue":null,          
   333              "cashCurrency":null 
   334                        
   335        };
   336  
   337        //update formObject
   338        if(result.residentID){
   339          formObject.residentID = result.residentID;
   340        }else{
   341          formObject.residentID = null;
   342        }
   343      
   344        if(result.firstName){
   345          formObject.firstName = result.firstName;
   346        }else{
   347          formObject.firstName = null;
   348        }
   349      
   350        if(result.lastName){
   351          formObject.lastName = result.lastName;
   352        }else{
   353          formObject.lastName = null;
   354        }
   355  
   356        this.myForm.setValue(formObject);
   357  
   358      })
   359      .catch((error) => {
   360          if(error == 'Server error'){
   361              this.errorMessage = "Could not connect to REST server. Please check your configuration details";
   362          }
   363          else if(error == '404 - Not Found'){
   364  				this.errorMessage = "404 - Could not find API route. Please check your available APIs."
   365          }
   366          else{
   367              this.errorMessage = error;
   368          }
   369      });
   370  
   371    }
   372  
   373    //reset form
   374    resetForm(): void{
   375      this.myForm.setValue({           
   376            "residentID":null, 
   377            "firstName":null,       
   378            "lastName":null,
   379  
   380            "coinsValue":null,
   381            "energyValue":null,
   382            "energyUnits":null,
   383            "cashValue":null,
   384            "cashCurrency":null
   385        });
   386    }
   387  
   388  }