Files
kmtnflower/src/app/admin/admin-team-form.component.ts
T
2026-06-21 05:24:40 +00:00

109 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 { TeamMember } from '../interfaces/team-member';
import { TeamMemberService } from '../services/team-member.service';
@Component({
selector: 'app-admin-team-form',
standalone: true,
imports: [CommonModule, FormsModule],
templateUrl: './admin-team-form.component.html',
styleUrl: './admin-team-form.component.scss',
})
export class AdminTeamFormComponent implements OnChanges {
private teamMemberService = inject(TeamMemberService);
@Input() editItem: TeamMember | null = null;
@Output() saved = new EventEmitter<void>();
@Output() closed = new EventEmitter<void>();
id: number | null = null;
name = '';
title = '';
bio = '';
photo_url = '';
display_order = 0;
active = true;
loading = false;
error = '';
submitted = false;
ngOnChanges(changes: SimpleChanges): void {
if (changes['editItem'] && this.editItem) {
this.edit(this.editItem);
}
}
edit(member: TeamMember): void {
this.id = member.id;
this.name = member.name;
this.title = member.title;
this.bio = member.bio ?? '';
this.photo_url = member.photo_url ?? '';
this.display_order = member.display_order;
this.active = member.active;
}
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.title = '';
this.bio = '';
this.photo_url = '';
this.display_order = 0;
this.active = true;
this.error = '';
this.submitted = false;
}
onClose(): void {
this.closed.emit();
this.reset();
}
async onSubmit(): Promise<void> {
this.submitted = true;
if (!this.name || !this.title) {
this.error = 'Please fill in all required fields.';
return;
}
this.loading = true;
this.error = '';
const payload = {
name: this.name,
title: this.title,
bio: this.bio || null,
photo_url: this.photo_url || null,
display_order: this.display_order,
active: this.active,
};
try {
if (this.id) {
await firstValueFrom(this.teamMemberService.updateTeamMember(this.id, payload));
} else {
await firstValueFrom(this.teamMemberService.createTeamMember(payload));
}
this.saved.emit();
this.reset();
} catch (err: any) {
this.error = this.formatError(err);
} finally {
this.loading = false;
}
}
}