client-app/src/app/holder/holder-contacts/holder-contacts.component.ts
2025-07-14 19:30:28 +05:30

374 lines
12 KiB
TypeScript

import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { AngularMaterialModule } from '../../shared/module/angular-material.module';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { PhonePipe } from '../../shared/pipes/phone.pipe';
import { CommonModule } from '@angular/common';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { UserPreferences } from '../../core/models/user-preference';
import { NotificationService } from '../../core/services/common/notification.service';
import { MatDialog } from '@angular/material/dialog';
import { ApiErrorHandlerService } from '../../core/services/common/api-error-handler.service';
import { ContactFormModel, HolderContact } from '../../core/models/holder/contact';
import { ContactService } from '../../core/services/holder/contact.service';
@Component({
selector: 'app-holder-contacts',
imports: [AngularMaterialModule, ReactiveFormsModule, PhonePipe, CommonModule],
templateUrl: './holder-contacts.component.html',
styleUrl: './holder-contacts.component.scss'
})
export class HolderContactsComponent {
@Input() isEditMode: boolean = false;
@Input() holderid: number = 0;
@Input() userPreferences: UserPreferences = {};
@Output() hasContacts = new EventEmitter<boolean>();
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
displayedColumns: string[] = ['firstName', 'lastName', 'title', 'phone', 'mobile', 'email', 'actions'];
dataSource = new MatTableDataSource<any>();
contactForm: FormGroup;
isEditing = false;
currentContactId: number | null = null;
isLoading = false;
showForm = false;
showInactiveContacts = false;
contacts: HolderContact[] = [];
contactReadOnlyFields: any = {
lastChangedDate: null,
lastChangedBy: null,
isInactive: null,
inactivatedDate: null
};
constructor(
private fb: FormBuilder,
private contactService: ContactService,
private notificationService: NotificationService,
private dialog: MatDialog,
private errorHandler: ApiErrorHandlerService
) {
this.contactForm = this.fb.group({
firstName: ['', [Validators.required, Validators.maxLength(50)]],
lastName: ['', [Validators.required, Validators.maxLength(50)]],
middleInitial: ['', [Validators.maxLength(1)]],
title: ['', [Validators.required, Validators.maxLength(100)]],
phone: ['', [Validators.required, Validators.pattern(/^[0-9]{10,15}$/)]],
mobile: ['', [Validators.required, Validators.pattern(/^[0-9]{10,15}$/)]],
fax: ['', [Validators.pattern(/^[0-9]{10,15}$/)]],
email: ['', [Validators.required, Validators.email, Validators.maxLength(100)]],
// defaultContact: [false]
});
}
ngOnInit(): void {
if (this.holderid > 0) {
this.loadContacts();
}
// this.loadContacts();
}
InactivateHolderContact(HOLDERCONTACTID: number): void {
this.contactService.InactivateHolderContact(HOLDERCONTACTID).subscribe(
{
next: (basicData: any) => {
this.notificationService.showSuccess(`HolderContact Inactivated successfully`);
// this.loadContacts()
},
error: (error: any) => {
let errorMessage = this.errorHandler.handleApiError(error, `Failed to Inactivate HolderContact`);
this.notificationService.showError(errorMessage);
console.error('Error Inactivating HolderContact:', error);
}
}
);
}
ReactivateHolderContact(HOLDERCONTACTID: number): void {
this.contactService.ReactivateHolderContact(HOLDERCONTACTID).subscribe(
{
next: (basicData: any) => {
this.notificationService.showSuccess(`HolderContact Reactivated successfully`);
// this.loadContacts()
},
error: (error: any) => {
let errorMessage = this.errorHandler.handleApiError(error, `Failed to Reactivate HolderContact`);
this.notificationService.showError(errorMessage);
console.error('Error Reactivating HolderContact:', error);
}
}
);
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
loadContactsX(): void {
this.isLoading = true;
this.contacts = [
{
HOLDERCONTACTID: 101,
HOLDERID: 3001,
SPID: 5001,
FIRSTNAME: "Alice",
LASTNAME: "Johnson",
MIDDLEINITIAL: "M",
TITLE: "Product Manager",
PHONE: "1234567890",
MOBILE: "0987654321",
FAX: "1112223333",
EMAILADDRESS: "alice.johnson@example.com",
DATECREATED: new Date().toISOString(),
CREATEDBY: "admin",
INACTIVEFLAG: "Y",
INACTIVEDATE: new Date().toISOString(),
LASTUPDATEDBY: "alice",
LASTUPDATEDDATE: new Date().toISOString()
},
{
HOLDERCONTACTID: 102,
HOLDERID: 3001,
SPID: 5002,
FIRSTNAME: "Bob",
LASTNAME: "Smith",
MIDDLEINITIAL: null,
TITLE: "Sales Associate",
PHONE: "2345678901",
MOBILE: "8765432109",
FAX: null,
EMAILADDRESS: "bob.smith@example.com",
DATECREATED: new Date().toISOString(),
CREATEDBY: "hr_user",
INACTIVEFLAG: "Y",
INACTIVEDATE: new Date().toISOString(),
LASTUPDATEDBY: "hr_user",
LASTUPDATEDDATE: new Date().toISOString()
},
{
HOLDERCONTACTID: 103,
HOLDERID: 3002,
SPID: 5003,
FIRSTNAME: "Charlie",
LASTNAME: "Brown",
MIDDLEINITIAL: "R",
TITLE: "Developer",
PHONE: "3456789012",
MOBILE: "7654321098",
FAX: "4445556666",
EMAILADDRESS: "charlie.brown@example.com",
DATECREATED: new Date().toISOString(),
CREATEDBY: "it_admin",
INACTIVEFLAG: "N",
INACTIVEDATE: null,
LASTUPDATEDBY: "charlie",
LASTUPDATEDDATE: new Date().toISOString()
},
{
HOLDERCONTACTID: 104,
HOLDERID: 3003,
SPID: 5004,
FIRSTNAME: "Diana",
LASTNAME: "Evans",
MIDDLEINITIAL: "K",
TITLE: "Marketing Director",
PHONE: "4567890123",
MOBILE: "6543210987",
FAX: "7778889999",
EMAILADDRESS: "diana.evans@example.com",
DATECREATED: new Date().toISOString(),
CREATEDBY: "marketing_admin",
INACTIVEFLAG: "N",
INACTIVEDATE: null,
LASTUPDATEDBY: "diana",
LASTUPDATEDDATE: new Date().toISOString()
},
{
HOLDERCONTACTID: 105,
HOLDERID: 3003,
SPID: 5005,
FIRSTNAME: "Edward",
LASTNAME: "Norton",
MIDDLEINITIAL: null,
TITLE: "Finance Analyst",
PHONE: "5678901234",
MOBILE: "5432109876",
FAX: null,
EMAILADDRESS: "edward.norton@example.com",
DATECREATED: new Date().toISOString(),
CREATEDBY: "finance_team",
INACTIVEFLAG: "N",
INACTIVEDATE: null,
LASTUPDATEDBY: "edward",
LASTUPDATEDDATE: new Date().toISOString()
},
{
HOLDERCONTACTID: 106,
HOLDERID: 3004,
SPID: 5006,
FIRSTNAME: "Fiona",
LASTNAME: "Griffin",
MIDDLEINITIAL: "L",
TITLE: "HR Manager",
PHONE: "6789012345",
MOBILE: "4321098765",
FAX: "3334445555",
EMAILADDRESS: "fiona.griffin@example.com",
DATECREATED: new Date().toISOString(),
CREATEDBY: "hr_admin",
INACTIVEFLAG: "N",
INACTIVEDATE: null,
LASTUPDATEDBY: "fiona",
LASTUPDATEDDATE: new Date().toISOString()
}
];
this.renderContacts();
this.isLoading = false;
}
loadContacts(): void {
this.isLoading = true;
this.contactService.getHolderContactsByHolderId(this.holderid).subscribe({
next: (contacts: HolderContact[]) => {
this.contacts = contacts;
this.renderContacts();
this.isLoading = false;
},
error: (error: any) => {
let errorMessage = this.errorHandler.handleApiError(error, 'Failed to load contacts');
this.notificationService.showError(errorMessage);
this.isLoading = false;
console.error('Error loading contacts:', error);
}
});
}
addNewContact(): void {
this.showForm = true;
this.isEditing = false;
this.currentContactId = null;
this.contactForm.reset();
// this.contactForm.patchValue({ defaultContact: false });
}
editContact(contact: HolderContact): void {
this.showForm = true;
this.isEditing = true;
this.currentContactId = contact.HOLDERCONTACTID;
this.contactForm.patchValue({
firstName: contact.FIRSTNAME,
lastName: contact.LASTNAME,
middleInitial: contact.MIDDLEINITIAL,
title: contact.TITLE,
phone: contact.PHONE,
mobile: contact.MOBILE,
fax: contact.FAX,
email: contact.EMAILADDRESS
});
this.contactReadOnlyFields.lastChangedDate = contact.LASTUPDATEDDATE ?? contact.DATECREATED;
this.contactReadOnlyFields.lastChangedBy = contact.LASTUPDATEDBY ?? contact.CREATEDBY;
this.contactReadOnlyFields.isInactive = contact.INACTIVEFLAG === 'Y';
this.contactReadOnlyFields.inactivatedDate = contact.INACTIVEDATE;
}
saveContact(): void {
if (this.contactForm.invalid) {
this.contactForm.markAllAsTouched();
return;
}
// default the first contact
const contactData: ContactFormModel = this.contactForm.value;
// contactData.defaultContact = this.dataSource?.data?.length === 0;
console.log("Contact details : ", contactData);
const saveObservable = this.isEditing && (this.currentContactId! > 0)
? this.contactService.updateHolderContact(this.currentContactId!, contactData)
: this.contactService.createHolderContact(this.holderid, contactData);
saveObservable.subscribe({
next: () => {
this.notificationService.showSuccess(`Contact ${this.isEditing ? 'updated' : 'added'} successfully`);
this.loadContacts();
this.cancelEdit();
this.hasContacts.emit(true);
},
error: (error) => {
let errorMessage = this.errorHandler.handleApiError(error, `Failed to ${this.isEditing ? 'update' : 'add'} contact`);
this.notificationService.showError(errorMessage);
console.error('Error saving contact:', error);
}
});
}
toggleShowInactiveContacts(): void {
this.showInactiveContacts = !this.showInactiveContacts;
this.renderContacts();
}
renderContacts(): void {
if (this.showInactiveContacts) {
// this.dataSource.data = this.contacts;
this.dataSource.data = this.contacts.filter(contact => contact.INACTIVEFLAG === 'Y');
} else {
this.dataSource.data = this.contacts.filter(contact => contact.INACTIVEFLAG === 'N');
}
}
deleteContact(contactId: string): void {
// const dialogRef = this.dialog.open(ConfirmDialogComponent, {
// width: '350px',
// data: {
// title: 'Confirm Delete',
// message: 'Are you sure you want to delete this contact?',
// confirmText: 'Delete',
// cancelText: 'Cancel'
// }
// });
// dialogRef.afterClosed().subscribe(result => {
// if (result) {
// this.contactService.deleteContact(contactId).subscribe({
// next: () => {
// this.notificationService.showSuccess('Contact deleted successfully');
// this.loadContacts();
// },
// error: (error) => {
// let errorMessage = this.errorHandler.handleApiError(error, 'Failed to delete contact');
// this.notificationService.showError(errorMessage);
// console.error('Error deleting contact:', error);
// }
// });
// }
// });
}
createLogin(): void {
}
cancelEdit(): void {
this.showForm = false;
this.isEditing = false;
this.currentContactId = null;
this.contactForm.reset();
}
}