import {Component, Input, OnInit, ViewChild} from '@angular/core'; import {UsersService} from '../../services/users.service'; import {Router} from '@angular/router'; import {CupboardService} from '../../services/cupboard.service'; import {catchError, firstValueFrom, Observable, of} from 'rxjs'; import {AuthService} from '../../services/auth.service'; import {ToastsService, ToastType} from '../../services/toasts.service'; @Component({ selector: 'app-funding-basket', standalone: false, templateUrl: './funding-basket.component.html', styleUrl: './funding-basket.component.css' }) export class FundingBasketComponent implements OnInit { constructor( private router: Router, protected cupboardService: CupboardService, protected usersService: UsersService, private authService: AuthService, private toastService: ToastsService ) {} @ViewChild("contribution") contribution?: Input; @Input() isValid: boolean = true; // this is for login rerouting ngOnInit(): void { if (!this.authService.getCurrentUser()) { this.router.navigate(['/login'], {queryParams: {redir: this.router.url}}); return; } this.usersService.refreshBasket(); // this.usersService.removeNeed(); <- call this to remove } async checkout() { this.isValid = true; for (let c of document.querySelectorAll('.contribution')!) { let contribution = c as HTMLInputElement; contribution.setAttribute("style", ""); if (contribution.value == '' || contribution.valueAsNumber <= 0) { this.isValid = false; contribution.setAttribute("style", "border-color: #ff0000"); this.toastService.sendToast(ToastType.ERROR, "Invalid input in funding basket!") setTimeout(() => { contribution.setAttribute("style", "border-color: #ffffff"); }, 3000); } } // if (this.usersService.getBasket().value != await firstValueFrom(this.usersService.getUser(1)) // for (let c of this.usersService.getBasket().value) { // if (c == null) { // this.isValid = false; // this.statusText.next("One or more needs have been deleted") // } else { // this.statusText.next("test") // } // } if (this.isValid) { for (let c of document.querySelectorAll('.contribution')!) { let contribution = c as HTMLInputElement; let need = await firstValueFrom(this.cupboardService.getNeed(+contribution.id)); need.current += +contribution.value; this.usersService.removeNeed(+need.id); this.cupboardService.checkoutNeed(need.id, +contribution.value) .pipe(catchError((ex, _) => { if (ex.status == 500) { this.toastService.sendToast(ToastType.ERROR, 'Fields cannot be blank'); } else if (ex.status == 400) { this.toastService.sendToast(ToastType.ERROR, ex.error); } else { this.toastService.sendToast(ToastType.ERROR, 'Error on creating need'); } return new Observable(); })) .subscribe((result) => { if (result) { //this.needList?.refresh() } else { console.log('need update failed'); } this.toastService.sendToast(ToastType.INFO, "Checkout successful"); }); } } } protected readonly of = of; }