#6 merge purchase history

Слито
jmacura слито 16 коммит(ов) из jmacura/purchase-history в jmacura/main 3 лет назад

+ 25 - 8
src/app/bc-info/bc-info.component.html

@@ -14,29 +14,46 @@ Data URL: {{bcInfoService.dataUrl}} -->
             <p><b>Asset:</b> {{assetId}}</p>
             <p>
                 <b>Balance:</b> {{userBalance}}
-                <button type="button" [disabled]="getUserBalanceInProgress" class="btn btn-secondary btn-sm" (click)="refreshUserBalance()" title="Refresh balance">
-                    <i *ngIf="!getUserBalanceInProgress" class="icon-refresh"></i>             
-                    <span *ngIf="getUserBalanceInProgress" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 
+                <button type="button" [disabled]="getUserBalanceInProgress" class="btn btn-secondary btn-sm"
+                    (click)="refreshUserBalance()" title="Refresh balance">
+                    <i *ngIf="!getUserBalanceInProgress" class="icon-refresh"></i>
+                    <span *ngIf="getUserBalanceInProgress" class="spinner-border spinner-border-sm" role="status"
+                        aria-hidden="true"></span>
                 </button>
             </p>
         </span>
         <hr>
-        <button *ngIf="!selectingArea" type="button" class="btn btn-primary" (click)="onSelectArea()">Select
+        <button style="margin-bottom: 5px;" *ngIf="!selectingArea" type="button" class="btn btn-primary" (click)="onSelectArea()">Select
             area</button>
+
         <div *ngIf="selectingArea">
             <p>Select area with <b> Shift + Drag</b></p>
             <span *ngIf="price">
                 <p><b>Price:</b> {{price}}</p>
             </span>
             <p *ngIf="paymentHash"><b>Payment hash:</b> {{paymentHash}}</p>
-            <div>
+            <div style="margin-bottom: 5px;">
                 <button type="button" [disabled]="!price || buyInProgress" class="btn btn-success" (click)="onBuy()">
-                    <span *ngIf="buyInProgress" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
+                    <span *ngIf="buyInProgress" class="spinner-border spinner-border-sm" role="status"></span>
                     Buy
                 </button>
-                <button type="button" class="btn btn-danger" [disabled]="buyInProgress" (click)="onCancel()">Cancel</button>
+                <button type="button" class="btn btn-danger" [disabled]="buyInProgress"
+                    (click)="onCancel()">Cancel</button>
                 <a *ngIf="dataUrl" class="btn btn-primary" [href]="dataUrl">Download your data!</a>
             </div>
-        </div>        
+        </div>
+        <hr>
+        <div>
+            <h5>Purchase history</h5>
+            <div>
+                <purchase                    
+                    *ngFor="let purchase of lastPurchases; index as i"
+                    [hash]="purchase.hash"
+                    [amount]="purchase.amount"
+                    [extent]="purchase.extent"
+                    [timestamp]="purchase.timestamp"
+                    [user]="user"
+                ></purchase>
+            </div>
     </div>
 </div>

+ 46 - 18
src/app/bc-info/bc-info.component.ts

@@ -22,6 +22,7 @@ import {
 } from 'hslayers-ng';
 
 import { BcInfoService } from './bc-info.service';
+import { Purchase } from './purchase/purchase.component';
 
 @Component({
   selector: 'blockchain-info',
@@ -47,6 +48,8 @@ export class BcInfoComponent implements HsPanelComponent, OnInit {
   data: any;
   name: string = "bc-panel";
 
+  lastPurchases: Array<Purchase>;
+
   constructor(
     private bcInfoService: BcInfoService,
     private mapService: HsMapService,
@@ -59,14 +62,25 @@ export class BcInfoComponent implements HsPanelComponent, OnInit {
     this.onExtentChanged = this.onExtentChanged.bind(this);
   }
 
-  async ngOnInit(): Promise<void> {
-    await this.refreshUserBalance();
+  ngOnInit(): void {
+    this.refreshUserBalance();
+    this.refreshPurchaseHistory();
   }
 
   async refreshUserBalance(): Promise<void> {
-    this.getUserBalanceInProgress = true;
-    this.userBalance = await this.bcInfoService.getUserBalance(this.user, this.userPrivateKey, this.assetId);
-    this.getUserBalanceInProgress = false;
+    try {
+      this.getUserBalanceInProgress = true;
+      this.userBalance = await this.bcInfoService.getUserBalance(this.user, this.userPrivateKey, this.assetId);
+      this.getUserBalanceInProgress = false;
+    }
+    catch (err) {
+      this.getUserBalanceInProgress = false;
+      throw err;
+    }
+  }
+
+  async refreshPurchaseHistory(): Promise<void> {
+    this.lastPurchases = (await this.bcInfoService.getTransfers(this.user)) as Array<Purchase>;
   }
 
   isVisible(): boolean {
@@ -85,21 +99,33 @@ export class BcInfoComponent implements HsPanelComponent, OnInit {
   }
 
   async onBuy(): Promise<void> {
-    if (!confirm("You sure?")) {
-      return;
-    }
+    try {
+      if (!confirm("You sure?")) {
+        return;
+      }
 
-    this.buyInProgress = true;
+      this.buyInProgress = true;
 
-    let transformedExtent = transformExtent(this.extent, this.mapService.getMap().getView().getProjection(), "EPSG:4326");
-    transformedExtent = this.roundExtentCoords(transformedExtent);
-    //console.log(transformedExtent);
+      let transformedExtent = transformExtent(this.extent, this.mapService.getMap().getView().getProjection(), "EPSG:4326");      
+      transformedExtent = this.roundExtentCoords(transformedExtent);
+      //console.log(transformedExtent);
 
-    this.paymentHash = await this.bcInfoService.transferAssets(this.user, this.userPrivateKey, this.assetId, transformedExtent, this.price);
-    this.refreshUserBalance();
-    this.dataUrl = await this.bcInfoService.requestData(this.paymentHash, this.user);//"https://eo.lesprojekt.cz/produkty/S2/2020/S2A_MSIL2A_20200422T095031_N9999_R079_T33UXQ_20201127T165009_NDVI.tif"
+      this.paymentHash = await this.bcInfoService.transferAssets(this.user, this.userPrivateKey, this.assetId, transformedExtent, this.price);
+
+      await this.bcInfoService.archiveTransfer(this.user, this.price, this.paymentHash, transformedExtent, Date.now());
+
+      this.refreshPurchaseHistory();
+      this.refreshUserBalance();
+
+      this.dataUrl = await this.bcInfoService.requestData(this.paymentHash, this.user);//"https://eo.lesprojekt.cz/produkty/S2/2020/S2A_MSIL2A_20200422T095031_N9999_R079_T33UXQ_20201127T165009_NDVI.tif"
+
+      this.buyInProgress = false;
+    }
+    catch (err) {
+      this.buyInProgress = false;
+      throw err;
+    }
 
-    this.buyInProgress = false;
   }
 
   onCancel(): void {
@@ -128,8 +154,10 @@ export class BcInfoComponent implements HsPanelComponent, OnInit {
     }
   }
 
+
+
   onTest() {
-    this.bcInfoService.getUserTransactions(this.user, this.userPrivateKey);
+    //this.bcInfoService.getUserTransactions(this.user, this.userPrivateKey);
     //console.log(this.mapService.getMap().getView().getProjection());
   }
 
@@ -138,7 +166,7 @@ export class BcInfoComponent implements HsPanelComponent, OnInit {
     let roundedExtent: number[] = new Array<number>(4);
 
     for (let i = 0; i !== extent.length; i++) {
-      roundedExtent[i] = this.roundTwoDecimalPlaces(extent[i]);
+      roundedExtent[i] = Math.round((extent[i] + Number.EPSILON) * 1000000) / 1000000;
     }
 
     return roundedExtent;

+ 2 - 1
src/app/bc-info/bc-info.module.ts

@@ -4,11 +4,12 @@ import {CommonModule} from '@angular/common'
 import { HsPanelHelpersModule } from 'hslayers-ng';
 
 import {BcInfoComponent} from './bc-info.component';
+import { Purchase } from './purchase/purchase.component';
 
 @NgModule({
   imports: [CommonModule, HsPanelHelpersModule],
   exports: [BcInfoComponent],
-  declarations: [BcInfoComponent],
+  declarations: [BcInfoComponent, Purchase],
   providers: [],
 })
 export class BcInfoModule {}

+ 28 - 39
src/app/bc-info/bc-info.service.ts

@@ -16,14 +16,6 @@ export class BcInfoService {
 
   private readonly _bcConfig: BcConfig;
 
-
-  // extent = [ //bottom left and top right point should be enough
-  //   [48.5, 17],
-  //   [49, 17],
-  //   [49, 16.5],
-  //   [48.5, 16.5]
-  // ];
-
   constructor(private httpClient: HttpClient, private appSettings: AppConfigService) {
     this._bcConfig = appSettings.config;
 
@@ -56,35 +48,7 @@ export class BcInfoService {
     } catch (err) {
       console.error(err)
     }
-  }
-
-  async getUserTransactions(user: string, userPrivateKey: string) {
-    let queryOptions = {
-      privateKey: userPrivateKey,
-      creatorAccountId: user,
-      queryService: this.queryService,
-      timeoutLimit: 10000
-    };
-
-    let response = await queries.getAccountTransactions(queryOptions,
-      {
-        accountId: user,
-        pageSize: 10,
-        firstTxHash: undefined,
-        ordering:
-        {          
-          field: undefined,
-          direction: undefined
-        },
-        firstTxTime: undefined,
-        lastTxTime: undefined,
-        firstTxHeight: undefined,
-        lastTxHeight: undefined,
-      }
-    );
-
-    console.log(response);
-  }
+  } 
 
   async transferAssets(user: string, userPrivateKey: string, assetId: string, extent: number[], amount: number): Promise<string> {
 
@@ -114,14 +78,39 @@ export class BcInfoService {
   }
 
   async getPrice(area: number): Promise<number> {
-    let response = await this.httpClient.post(this._bcConfig.CHAIN4ALL_SERVICE_URL + '/price', { area }, { headers: this.basicAuthHeaders }).toPromise();
+    let response = await this.httpClient.post(
+      this._bcConfig.CHAIN4ALL_SERVICE_URL + '/price',
+      { area },
+      { headers: this.basicAuthHeaders }
+    ).toPromise();
 
     return response["price"];
   }
 
   async requestData(paymentHash: string, user: string): Promise<string> {
-    let response = await this.httpClient.post(this._bcConfig.CHAIN4ALL_SERVICE_URL + '/buy', { txHash: paymentHash, user }, { headers: this.basicAuthHeaders }).toPromise();
+    let response = await this.httpClient.post(
+      this._bcConfig.CHAIN4ALL_SERVICE_URL + '/buy',
+      { txHash: paymentHash, user },
+      { headers: this.basicAuthHeaders }
+    ).toPromise();
 
     return response["dataUrl"];
   }
+
+  async getTransfers(user: string): Promise<Array<Object>>{
+    let response = await this.httpClient.get(
+      this._bcConfig.CHAIN4ALL_SERVICE_URL + "/transfers/" + user,
+      { headers: this.basicAuthHeaders }
+    ).toPromise();
+
+    return response as Array<Object>;
+  }
+
+  async archiveTransfer(user: string, amount: number, txHash: string, extent: number[], timestamp: number){
+    let response = await this.httpClient.post(
+      this._bcConfig.CHAIN4ALL_SERVICE_URL + '/transfer',
+      { txHash, user, extent, amount, timestamp },
+      { headers: this.basicAuthHeaders }
+    ).toPromise();
+  }
 }

+ 23 - 0
src/app/bc-info/purchase/purchase.component.html

@@ -0,0 +1,23 @@
+<div class="card">
+
+    <div class="card-header">
+        <small>{{timestamp | date:"dd.MM.yyyy HH:mm:ss"}}</small>
+        <span style="float: right;">                            
+            <button [disabled]="loadingData" style="margin-right: 5px" class="btn btn-secondary btn-sm" (click)="onRequestData()">
+                Data
+                <span *ngIf="loadingData" class="spinner-border spinner-border-sm" role="status"></span>
+            </button>
+            <button style="margin-right: 5px" class="btn btn-sm" (click)="expanded = !expanded">
+                <i [class]="expanded ? 'icon-arrow-up' : 'icon-arrow-down'"></i>
+            </button>
+        </span>        
+    </div>
+
+    <div [class]="expanded ? '' : 'collapse'">
+        <div class="card-body">
+            Extent: {{extent}}
+            Amount: {{amount}}
+        </div>
+    </div>
+
+</div>

+ 36 - 0
src/app/bc-info/purchase/purchase.component.ts

@@ -0,0 +1,36 @@
+import { Component, Input } from '@angular/core'
+import { Extent } from 'ol/extent'
+import { BcInfoService } from '../bc-info.service'
+
+@Component({
+    selector: 'purchase',
+    templateUrl: 'purchase.component.html'
+})
+export class Purchase {
+    @Input() hash: string;
+    @Input() timestamp: string;
+    @Input() extent: Extent;
+    @Input() amount: number;
+    @Input() user: string;
+
+    expanded: boolean = false;
+    loadingData: boolean = false;
+
+    constructor(private bcInfoService: BcInfoService) {}
+
+    async onRequestData(): Promise<void> {
+        try{
+            this.loadingData = true;
+
+            let dataUrl = await this.bcInfoService.requestData(this.hash, this.user);
+            window.open(dataUrl);
+            
+            this.loadingData = false;
+        }
+        catch(err){
+            this.loadingData = false;
+            throw err;
+        }
+        
+    }
+}

+ 1 - 1
src/assets/config.json

@@ -1,6 +1,6 @@
 {
     "CHAIN4ALL_SERVICE_URL": "https://chain4all.lesprojekt.cz",
-    "IROHA_ADDRESS": "http://10.0.0.156:8080",
+    "IROHA_ADDRESS": "https://chain4all.lesprojekt.cz/iroha",
     "ASSET": "coin#test",
     "ADMIN_USER": "admin@test"
 }