arti-angular-app/src/app/asset-calculator/asset-calculator.component.ts

92 lines
2.9 KiB
TypeScript

import {Component, computed, effect, OnInit ,signal } from '@angular/core';
import {FormsModule, ReactiveFormsModule, FormControl, FormGroup, Validators} from '@angular/forms';
import {CurrencyPipe,DecimalPipe,PercentPipe} from '@angular/common';
import {AssetsModule} from './assets/assets.module'
import {Asset, Positions, AssetPlanPosition, TypeDepreciation } from './assets/asset';
import {AssetService} from './assets/service/asset.service'
@Component({
selector: 'app-asset-calculator',
standalone: true,
imports: [FormsModule, CurrencyPipe, DecimalPipe, PercentPipe, AssetsModule, ReactiveFormsModule ] ,
templateUrl: "asset-calculator.component.html",
styleUrl: 'asset-calculator.component.css'
})
export class AssetCalculatorComponent implements OnInit{
TypeDepreciation = TypeDepreciation;
// Asset{}
initialValueAsset = signal<number>( 3000 );
depreciationRate = signal<number>( 20 );
year = signal<number>( 2024 );
month = signal<number>( 10 );
typeDepreciation = signal< TypeDepreciation>( TypeDepreciation.linear );
factorValue = signal<number>( 2 );
// Asset
positions = new Positions();
assetsDepreciationForm = new FormGroup( {
initialValueAsset : new FormControl( this.initialValueAsset(), [ Validators.required, this.currencyValidator ]),
depreciationRate : new FormControl( this.depreciationRate() ) ,
year : new FormControl( this.year() ),
month : new FormControl( this.month() ),
typeDepreciation : new FormControl( this.typeDepreciation ),
factorValue : new FormControl( this.factorValue, [Validators.required,Validators.max(2)] )
} );
constructor(private assetService : AssetService ){
effect( () => { this.calculate();});
// this.assetsDepreciationForm.valueChanges.subscribe( (value)=> { this.calculateForAsset(value); });
}
ngOnInit(): void{
}
calculate(){
const asset : Asset = {
initialValueAsset : this.initialValueAsset(),
depreciationRate : this.depreciationRate(),
year : this.year(),
month : this.month(),
type : this.typeDepreciation(),
factorValue : this.factorValue()
}
this.calculateForAsset( asset );
}
calculateForAsset( asset : Asset ) {
this.assetService.calculate( asset ).subscribe(
positions => { this.positions=positions; this.calculateToValues() });
}
calculateToValues() {
let sum :number = 0;
for(let position of this.positions.positions ){
position.calculatedDepreciation = position.calculatedDepreciation *0.01;
sum += position.calculatedDepreciation;
position.sum = sum;
}
}
clazz(pos : AssetPlanPosition ){
return pos.when.year % 2 === 0 ? "table-light" : "table-dark";
}
// Walidator dla kwoty
currencyValidator(control: any) {
const value = control.value;
const regex = /^\d+(\.\d{1,2})?$/; // Akceptuje liczby z maksymalnie dwoma miejscami po przecinku
return regex.test(value) ? null : { invalidCurrency: true };
}
}