110 lines
2.7 KiB
TypeScript
110 lines
2.7 KiB
TypeScript
import { Component, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
|
|
import { CommonModule } from '@angular/common';
|
|
import { FormsModule } from '@angular/forms';
|
|
import { firstValueFrom } from 'rxjs';
|
|
|
|
import { Tier } from '../interfaces/tier';
|
|
import { TierService } from '../services/tier.service';
|
|
|
|
@Component({
|
|
selector: 'app-admin-tier-form',
|
|
standalone: true,
|
|
imports: [CommonModule, FormsModule],
|
|
templateUrl: './admin-tier-form.component.html',
|
|
styleUrl: './admin-tier-form.component.scss',
|
|
})
|
|
export class AdminTierFormComponent implements OnChanges {
|
|
private tierService = inject(TierService);
|
|
|
|
@Input() editItem: Tier | null = null;
|
|
@Output() saved = new EventEmitter<void>();
|
|
@Output() closed = new EventEmitter<void>();
|
|
|
|
id: number | null = null;
|
|
name = '';
|
|
amount = 0;
|
|
icon = '⭐';
|
|
benefits_text = '';
|
|
display_order = 1;
|
|
|
|
loading = false;
|
|
error = '';
|
|
submitted = false;
|
|
|
|
ngOnChanges(changes: SimpleChanges): void {
|
|
if (changes['editItem'] && this.editItem) {
|
|
this.edit(this.editItem);
|
|
}
|
|
}
|
|
|
|
edit(tier: Tier): void {
|
|
this.id = tier.id;
|
|
this.name = tier.name;
|
|
this.amount = tier.amount;
|
|
this.icon = tier.icon;
|
|
this.benefits_text = tier.benefits.join(', ');
|
|
this.display_order = tier.display_order;
|
|
}
|
|
|
|
formatError(err: any): string {
|
|
if (err?.error?.detail) return err.error.detail;
|
|
if (err?.error?.message) return err.error.message;
|
|
if (err?.message) return err.message;
|
|
return 'Failed to save. Please try again.';
|
|
}
|
|
|
|
reset(): void {
|
|
this.id = null;
|
|
this.name = '';
|
|
this.amount = 0;
|
|
this.icon = '⭐';
|
|
this.benefits_text = '';
|
|
this.display_order = 1;
|
|
this.error = '';
|
|
this.submitted = false;
|
|
}
|
|
|
|
onClose(): void {
|
|
this.closed.emit();
|
|
this.reset();
|
|
}
|
|
|
|
async onSubmit(): Promise<void> {
|
|
this.submitted = true;
|
|
if (!this.name || this.amount <= 0) {
|
|
this.error = 'Please fill in all required fields.';
|
|
return;
|
|
}
|
|
|
|
this.loading = true;
|
|
this.error = '';
|
|
|
|
const benefits = this.benefits_text
|
|
.split(',')
|
|
.map((b) => b.trim())
|
|
.filter((b) => b.length > 0);
|
|
|
|
const payload = {
|
|
name: this.name,
|
|
amount: this.amount,
|
|
icon: this.icon,
|
|
benefits: benefits,
|
|
display_order: this.display_order,
|
|
};
|
|
|
|
try {
|
|
if (this.id) {
|
|
await firstValueFrom(this.tierService.updateTier(this.id, payload));
|
|
} else {
|
|
await firstValueFrom(this.tierService.createTier(payload));
|
|
}
|
|
this.saved.emit();
|
|
this.reset();
|
|
} catch (err: any) {
|
|
this.error = this.formatError(err);
|
|
} finally {
|
|
this.loading = false;
|
|
}
|
|
}
|
|
}
|