carnet-portal-app/src/app/region/region.component.ts

179 lines
5.8 KiB
TypeScript

import { AfterViewInit, Component, EventEmitter, inject, Input, OnInit, Output, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { AngularMaterialModule } from '../shared/module/angular-material.module';
import { CommonModule } from '@angular/common';
import { Region } from '../core/models/region/region';
import { CustomPaginator } from '../shared/custom-paginator';
import { UserPreferences } from '../core/models/user-preference';
import { ApiErrorHandlerService } from '../core/services/common/api-error-handler.service';
import { NotificationService } from '../core/services/common/notification.service';
import { RegionService } from '../core/services/region/region.service';
import { UserPreferencesService } from '../core/services/user-preference.service';
import { finalize } from 'rxjs';
@Component({
selector: 'app-region',
imports: [AngularMaterialModule, CommonModule, ReactiveFormsModule],
templateUrl: './region.component.html',
styleUrl: './region.component.scss',
providers: [{ provide: MatPaginatorIntl, useClass: CustomPaginator }],
})
export class RegionComponent implements OnInit, AfterViewInit {
@ViewChild(MatPaginator, { static: false })
set paginator(value: MatPaginator) {
this.dataSource.paginator = value;
}
@ViewChild(MatSort) sort!: MatSort;
displayedColumns: string[] = ['value', 'name', 'actions'];
dataSource = new MatTableDataSource<any>();
regionForm: FormGroup;
isEditing = false;
currentRegionId: number | null = null;
isLoading = false;
changeInProgress = false;
showForm = false;
showExpiredRecords = false;
regions: Region[] = [];
userPreferences!: UserPreferences;
// readOnlyFields: any = {
// lastChangedDate: null,
// lastChangedBy: null
// };
@Input() isEditMode = false;
@Input() spid: number = 0;
@Output() hasRegions = new EventEmitter<boolean>();
private fb = inject(FormBuilder);
private regionService = inject(RegionService);
private notificationService = inject(NotificationService);
private errorHandler = inject(ApiErrorHandlerService);
constructor(userPrefenceService: UserPreferencesService) {
this.userPreferences = userPrefenceService.getPreferences();
this.regionForm = this.fb.group({
value: ['', Validators.required],
name: ['', Validators.required]
});
}
ngOnInit(): void {
this.loadRegions();
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
loadRegions(): void {
this.isLoading = true;
this.regionService.getRegions(this.spid).pipe(finalize(() => {
this.isLoading = false;
}))
.subscribe({
next: (regions: Region[]) => {
this.regions = regions;
this.dataSource.data = this.regions;
// this.renderRecords();
},
error: (error: any) => {
let errorMessage = this.errorHandler.handleApiError(error, 'Failed to load regions');
this.notificationService.showError(errorMessage);
console.error('Error loading regions:', error);
}
});
}
// toggleShowExpiredRecords(): void {
// this.showExpiredRecords = !this.showExpiredRecords;
// this.renderRecords();
// }
// renderRecords(): void {
// // if (this.showExpiredRecords) {
// // this.dataSource.data = this.regions;
// // } else {
// // this.dataSource.data = this.regions; // Adjust if you have expired logic
// //}
// }
addNewRegion(): void {
this.showForm = true;
this.isEditing = false;
this.currentRegionId = null;
this.regionForm.reset({
value: '',
name: ''
});
this.regionForm.get('value')?.enable();
this.regionForm.get('name')?.enable();
}
editRegion(region: Region): void {
this.showForm = true;
this.isEditing = true;
this.currentRegionId = region.id;
this.regionForm.patchValue({
value: region.value,
name: region.name
});
// // Set readonly fields if available
// this.readOnlyFields.lastChangedDate = null; // Update based on your API response
// this.readOnlyFields.lastChangedBy = null; // Update based on your API response
this.regionForm.get('value')?.disable();
}
saveRegion(): void {
if (this.regionForm.invalid) {
this.regionForm.markAllAsTouched();
return;
}
const regionData: Region = {
id: this.currentRegionId || 0,
value: this.regionForm.get('value')?.value,
name: this.regionForm.get('name')?.value
};
const saveObservable = this.isEditing && this.currentRegionId
? this.regionService.updateRegion(this.currentRegionId, regionData)
: this.regionService.createRegion(regionData, this.spid);
this.changeInProgress = true;
saveObservable.pipe(finalize(() => {
this.changeInProgress = false;
})).subscribe({
next: () => {
this.notificationService.showSuccess(`Region ${this.isEditing ? 'updated' : 'added'} successfully`);
this.loadRegions();
this.cancelEdit();
this.hasRegions.emit(true);
},
error: (error) => {
let errorMessage = this.errorHandler.handleApiError(error, `Failed to ${this.isEditing ? 'update' : 'add'} region`);
this.notificationService.showError(errorMessage);
console.error('Error saving region:', error);
}
});
}
cancelEdit(): void {
this.showForm = false;
this.isEditing = false;
this.currentRegionId = null;
this.regionForm.reset();
this.regionForm.get('value')?.enable();
this.regionForm.get('name')?.enable();
}
}