import { Component, OnInit, ViewChild, Optional, OnChanges } from '@angular/core'; import { DynamicDialogRef, DynamicDialogConfig, MessageService, Message } from 'primeng/api'; import { IStaff } from '../shared/core/IStaff'; import { StaffService } from '../shared/service/staff.service'; import { StaffSocialComponent } from '../staff-social/staff-social.component'; import { IRole } from '../shared/core/IRole'; import { IAddress } from '../shared/core/IAddress'; import { CommonService } from '../shared/service/common.service'; import { ICountry } from '../shared/core/ICountry'; import { IState } from '../shared/core/IState'; import { OrganisationService } from '../shared/service/organisation.service'; import { FormGroup, FormBuilder, FormArray, FormControl } from '@angular/forms'; import { IStaffMoreDetails } from '../shared/core/IStaffMoreDetails'; import { ILocalisation } from '../shared/core/ILocalisation'; import { ICompanySuggetion } from '../shared/core/ICompanySuggetion'; import { IJobTitleSuggetion } from '../shared/core/IJobTitleSuggetion'; import { Content } from '@angular/compiler/src/render3/r3_ast'; import { PermissionsComponent } from '../permissions/permissions.component'; @Component({ selector: 'app-new-staff', templateUrl: './new-staff.component.html', styleUrls: ['./new-staff.component.css'] }) export class NewStaffComponent implements OnInit, OnChanges { //this var is for staff social component @ViewChild(StaffSocialComponent) staffSocialComponent: StaffSocialComponent; //permission as a child @ViewChild(PermissionsComponent) permissionComponent: PermissionsComponent; //this var bind data of a staff staff: IStaff; //this var gets staff adress staffAddress: IAddress; //this var also bind data of a staff tempStaff: IStaff; //this get staff id from dialog box staffId: number; //this will be true if the staff has permission showLocalisations: boolean //using for permission component as a input roleForPermission: IRole; //using for permission component as a input organisationIdForPermission: number; //country list for dropdown countryList: ICountry[] = []; //use when select from dropdown selectedCountry: ICountry; //states list for dropdown stateList: IState[] = []; //use when select from state dropdown selectedState: IState; //suggetion list for company autocomplete field companySuggetions: ICompanySuggetion[]; //this will hold currently selected company name suggetion selectedCompanySuggetion: ICompanySuggetion; //temp var tempSelectedCompanySuggetion: ICompanySuggetion; //suggetion list for job title autocomplete field jobTitleSuggetions: IJobTitleSuggetion[]; //this will hold currently selected role name suggetion selectedRoleSuggetion: any; //temp var tempSelectedRoleSuggetion: IJobTitleSuggetion; //mobile country code tempMobileCountryCode: ICountry; //country, code list for autocomplete countryCodeList: ICountry[]; //default id for person defaultId = '0'; //whne creating new staff, this guid will use defaultGUID = "00000000-0000-0000-0000-000000000000"; //error/success message errMsg: Message[] = []; //curently active tab index activeTabIndex: number = 0; // use to get newly added social account fields staffMoreDetailsForm: FormGroup; //data bind to this var staffMoreDetailsList: IStaffMoreDetails[]; //this will use to hide and show staff more details removal dialog box displayMoreDetailRemove: boolean = false //currently selected row index to be deleted currentRowDeleteIndex: number = -1; //new localisation list newLocalisationList: ILocalisation; //this field will have value of a staff when new staff popup open from organisation chart superiorId: string; filechanged: boolean; imageFile: File; profilePicture: string = 'https://placehold.it/120x120'; disableSaveBtn:boolean = false; constructor( @Optional() public ref: DynamicDialogRef, @Optional() public config: DynamicDialogConfig, private messageService: MessageService, private staffService: StaffService, private commonService: CommonService, private organisationService: OrganisationService, private fb: FormBuilder) { } ngOnInit() { this.activeTabIndex = 0; //for company autocomplete this.companySuggetions = [{ Id: 0, CompanyName: "Select" }]; //using for mobile country code this.tempMobileCountryCode = { Id: 0, CountryName: "Select" }; //error message init this.errMsg = []; // get input staff id for exisitng staff this.staffId = this.config.data.id; // set the active tab if(this.config.data.activeTabIndex!=undefined){ this.activeTabIndex=this.config.data.activeTabIndex; } //check whether the sperior is entered if (this.config.data.superior) { this.superiorId = this.config.data.superior; } //for new staff , this id will be -1 if (this.staffId > -1) { //call method to get staff data this.getStaff(this.staffId); //call method to get staff more details this.getStaffMoreDetails(this.staffId); //method call to get staff permission this.getStaffPermission(this.staffId.toString()); } else { //initializing empty staff object this.staff = { Id: 0, UniqueIdentifier: this.defaultGUID, FirstName: "", LastName: "", Company: { Id: 0, CompanyName: "", Type: "", Country: "", Website: "", Email: "", Phone: "" }, Email: "", RoleName: "", Role: { Id: 0, OrganisationId: 0, RoleName: "", StaffCount: 0, RoleDescription: "" }, ProfilePicture: "", JobTitleId: 0 } this.showLocalisations = true; this.selectedCompanySuggetion = { Id: 0, CompanyName: "" } this.selectedRoleSuggetion ={ Id :0, TitleName : "" } //if company data avaible, it will add to staff object. this will happen when adding new staff in organisation chart if (this.config.data.company) { this.selectedCompanySuggetion.Id = this.config.data.company.Id; this.selectedCompanySuggetion.CompanyName =this.config.data.company.CompanyName; this.staff.Company.Id = this.selectedCompanySuggetion.Id; this.staff.Company.CompanyName = this.selectedCompanySuggetion.CompanyName; } //get staff role from staff object to input to permission component this.roleForPermission = this.staff.Role; //get staff company from staff object to input to permission component this.organisationIdForPermission = this.staff.Company.Id; } //loarding countries list this.getCountries(); //load country codes this.getCountryCode(); //creating form for staff more details rows this.staffMoreDetailsForm = this.fb.group({ moreDetailsList: this.fb.array([]) }) } ngOnChanges() { } //this meths call the service to get the staff getStaff(id: number) { //this var use to convert id to string var let idVal = id.toString(); //calling the service this.staffService.getStaffList(idVal,null).subscribe(staff => { this.staff = staff[0]; this.tempStaff = staff[0]; // set profile picture preview this.profilePicture = (this.tempStaff.PictureName != null && this.tempStaff.PictureName !="") ? this.tempStaff.ProfilePicture : 'https://placehold.it/120x120'; this.selectedCompanySuggetion = { Id: this.staff.Company.Id, CompanyName: this.staff.Company.CompanyName }; this.tempSelectedCompanySuggetion = { Id: this.staff.Company.Id, CompanyName: this.staff.Company.CompanyName }; this.selectedRoleSuggetion = this.staff.JobTitle this.tempSelectedRoleSuggetion = { Id: this.staff.Role.Id, TitleName: this.staff.Role.RoleName } this.tempMobileCountryCode = { Id: 0, CountryCode: this.staff.MobileCountryCode, CountryName: "" } console.log(this.staff.Company.Id); //get staff role from staff object to input to permission component this.roleForPermission = this.staff.Role; //get staff company from staff object to input to permission component this.organisationIdForPermission = this.staff.Company.Id; }) } //this method call service and get staff address data getStaffAddress(id?: number) { let staff = id.toString(); this.staffService.getStaffAddress(staff).subscribe(address => { this.staffAddress = address; this.selectState(); }) } //get more details of the staff and create form array getStaffMoreDetails(id?: number) { let staff = id.toString(); this.staffService.getStaffMoreDetails(staff).subscribe(details => { this.staffMoreDetailsList = details; this.fillStaffMoreDetailsRows(this.staffMoreDetailsList); }) } //get country list getCountries() { this.commonService.getCountries().subscribe(countries => { this.countryList = countries; this.countryList.unshift({ Id: 0, CountryCode: null, CountryName: "Select Country", ISOCode: null }); this.getStaffAddress(this.staffId); }); } //this method will get staff permissions for hide and show functionality getStaffPermission(id: string) { this.commonService.getStaffPermission(id).subscribe(res => { this.showLocalisations = res.ShowLocalisationTab; }) } // get method to access staff more details new elements as a form array get detailsList() { return this.staffMoreDetailsForm.get('moreDetailsList') as FormArray; } //get Title(): any { return this.detailsList.controls[0].value; } //this method create new row to be added createMoreDetailsRow(): FormGroup { return this.fb.group({ Id: 0, Title: '', Content: '', ForAll: false, Staff: [{ Id: this.staffId }], StaffId: this.staffId, IsDisabled: false }); } //this method add new row for staff more details, parameter 'data' contains the data to be fill when adding a row addMoreDetailsRow(data: IStaffMoreDetails) { var row = this.createMoreDetailsRow(); //if data available, it will patch to the formarray list if (data) { row.patchValue({ Id: data.Id, Title: data.Title, Content: data.Content, ForAll: data.ForAll, StaffId: this.staffId, IsDisabled: false }); } this.detailsList.push(row); } //this method show dialog box for more detail delete showDeleteDialogBox(index) { this.displayMoreDetailRemove = true; //track current index to be deleted this.currentRowDeleteIndex = index; } //this method get the confirmation to delete for all staff deleteRowConfirmation(isConfirmed: boolean) { //getting the row to be deleted var currentDeleteRow = this.detailsList.controls[this.currentRowDeleteIndex].value; //checking whether id is available if (currentDeleteRow['Id'] > 0) { //if clicked yes from pop up if (isConfirmed == true) { //for all - value will change as true currentDeleteRow['ForAll'] = true } currentDeleteRow['IsDisabled'] = true; var deleteCollection: IStaffMoreDetails[] = [{ Id: currentDeleteRow["Id"], Title: currentDeleteRow["Title"], Content: currentDeleteRow["Content"], IsDisabled: currentDeleteRow['IsDisabled'], ForAll: currentDeleteRow['ForAll'], StaffId: currentDeleteRow['StaffId'] }] // here we need to call a servce to delete more details of staff or staffs this.staffService.deleteStaffMoreDetails(deleteCollection).subscribe(res => { //delete response from api }) } this.displayMoreDetailRemove = false; //row will be removed from front end but data save to db when click save button underneath this.deleteMoreDetailsRow(this.currentRowDeleteIndex); } //this method remove clicked row from social media list deleteMoreDetailsRow(index) { this.currentRowDeleteIndex = -1; this.detailsList.removeAt(index); } //when staff already has more details, this method will create fields with data fillStaffMoreDetailsRows(dataObject: IStaffMoreDetails[]) { //loop the object and run add new row method if (dataObject.length > 0) { for (var x in dataObject) { this.addMoreDetailsRow(dataObject[x]); } } } //getting new localisaiton detail from localisation component getNewLocalisation(event) { this.newLocalisationList = event; } //this method will save staff details saveStaff() { this.disableSaveBtn = true; //every time the button click, this will clear and add new data if available this.errMsg = []; //if styaff profile details validation doesnt return true, then method will stop continuing if (!this.StaffProfileValidation()) { this.disableSaveBtn = false; return; } //check staff address validity if (!this.staffAddressValidation()) { this.disableSaveBtn = false; return; } //check staff more details validity if(!this.staffMoreDetailsValidation()){ this.disableSaveBtn = false; return; } //check staff custom social media if(!this.staffCustomSocialMediaValidation()){ this.disableSaveBtn = false; return; } console.log(this.staffMoreDetailsForm.get('moreDetailsList').value); //modified staff to be send for service to add console.log(this.staff); //modified atsff address to be send for service to add console.log(this.staffAddress); // upload logo if (this.filechanged) { this.organisationService.uploadFile(this.imageFile).subscribe(data => { if (data != null) { this.staff.ProfilePicture = data; this.staff.PictureName = data; } //staff prifile details this.staffService.saveStaffProfile(this.staff).subscribe(res => { this.staffId = res; //this will send staff more details data to service as a collection this.saveStaffMoreDetails(); //save staff life events this.saveStaffLifeEvents(); //staff address saving service call this.saveStaffAddress(); //modified social media obejct to be send for service to add this.saveStaffSocialMedia(); //save staff places this.saveStaffPlacesLived(); //save staff relationships this.saveStaffRelationship(); //save staff family members this.saveStaffFamilyMembers(); if (this.superiorId) { // debugger; this.saveStaffOrganisationChart(this.staffId, this.superiorId); } if (this.newLocalisationList) { this.newLocalisationList.StaffId = this.staffId; //saving new localisation data this.saveStaffLocalisation(); } //if permission component available, permission data also saved if (this.permissionComponent) { this.permissionComponent.clickSavePermission(); console.log(this.permissionComponent.staffPermissionComponent.permission); } //save staff custom social media this.saveStaffCustomSocialMedia(); this.messageService.add({ severity: 'success', summary: 'New Staff', detail: 'Successfully saved!' }); this.disableSaveBtn = false; }) }); } else { //staff prifile details this.staffService.saveStaffProfile(this.staff).subscribe(res => { this.staffId = res; //this will send staff more details data to service as a collection this.saveStaffMoreDetails(); //save staff life events this.saveStaffLifeEvents(); //staff address saving service call this.saveStaffAddress(); //modified social media obejct to be send for service to add this.saveStaffSocialMedia(); //save staff places this.saveStaffPlacesLived(); //save staff relationships this.saveStaffRelationship(); //save staff family members this.saveStaffFamilyMembers(); if (this.superiorId) { // debugger; this.saveStaffOrganisationChart(this.staffId, this.superiorId); } if (this.newLocalisationList) { this.newLocalisationList.StaffId = this.staffId; //saving new localisation data this.saveStaffLocalisation(); } //if permission component available, permission data also saved if (this.permissionComponent) { this.permissionComponent.clickSavePermission(); console.log(this.permissionComponent.staffPermissionComponent.permission); } //save staff custom social media this.saveStaffCustomSocialMedia(); this.errMsg.push({ severity: 'success', summary: 'Success', detail: 'Staff saved successfully!' }); this.disableSaveBtn = false; }) } console.log(this.staffSocialComponent.newAccounts); } saveStaffMoreDetails() { //check staff more details validity if(!this.staffMoreDetailsValidation()){ return; } for (var x in this.detailsList.value) { this.detailsList.value[x].StaffId = this.staffId; } this.staffService.saveStaffMoreDetails(this.detailsList.value).subscribe(res => { console.log(res); }) } saveStaffAddress() { //this validation is using here also as if this method executes individually, then also its validated if (!this.staffAddressValidation()) { return; } this.staffAddress.StaffId = this.staffId; this.staffService.saveStaffAddress(this.staffAddress).subscribe(res => { console.log(res); }) } saveStaffSocialMedia() { //if staff social media obj available if(this.staffSocialComponent.accounts){ this.staffSocialComponent.accounts.StaffId = this.staffId; this.staffService.saveStaffSocialMedia(this.staffSocialComponent.accounts).subscribe(res => { console.log(res); }); } } saveStaffPlacesLived() { //if new place selected, it will be saved if(this.staffSocialComponent.newPlaceLived){ this.staffSocialComponent.newPlaceLived.StaffId = this.staffId; this.staffService.saveStaffPlacesLived(this.staffSocialComponent.newPlaceLived).subscribe(res => { console.log(res); }); } } saveStaffRelationship() { //if new family details have added, it will send to save if(this.staffSocialComponent.newFamily){ this.staffSocialComponent.newFamily.StaffId = this.staffId; this.staffService.saveStaffRelationship(this.staffSocialComponent.newFamily).subscribe(res => { console.log(res); }) } } saveStaffFamilyMembers() { //if new members are added or modified if(this.staffSocialComponent.newMembers){ for (var x in this.staffSocialComponent.newMembers) { this.staffSocialComponent.newMembers[x].StaffId = this.staffId; } this.staffService.saveStaffFamilyMembers(this.staffSocialComponent.newMembers).subscribe(res => { console.log(res); }) } } saveStaffCustomSocialMedia() { //this validation is using here also as if this method executes individually, then also its validated if(!this.staffCustomSocialMediaValidation()){ return; } //if new custom social accounts are added if(this.staffSocialComponent.newCustomAccounts){ for (var x in this.staffSocialComponent.newCustomAccounts) { this.staffSocialComponent.newCustomAccounts[x].StaffId = this.staffId; } this.staffService.saveStaffCustomSocialMedia(this.staffSocialComponent.newCustomAccounts).subscribe(res => { console.log(res); }) } } saveStaffLifeEvents() { // debugger; //if life events are added or modified if(this.staffSocialComponent.newLifeEvent){ for (var x in this.staffSocialComponent.newLifeEvent) { this.staffSocialComponent.newLifeEvent[x].StaffId = this.staffId; } this.staffService.saveStaffLifeEvents(this.staffSocialComponent.newLifeEvent).subscribe(res => { console.log(res); }) } } saveStaffLocalisation() { this.staffService.saveStaffLocalisation(this.newLocalisationList).subscribe(res => { console.log(res); }) } saveStaffOrganisationChart(id, superiorId) { this.staffService.assignInOrganisationChart(id, superiorId).subscribe(res => { this.messageService.add({ severity: 'success', summary: 'New Staff', detail: 'Successfully saved in organisation chart! Please reload the page.' }); }) } //get states of the selected country selectState() { if (this.staffAddress.Country) { this.commonService.getStates(this.staffAddress.Country.Id).subscribe(states => { this.stateList = states; this.stateList.unshift({ Id: 0, CountryId: null, StateName: "Select State" }); }) } } //get company suggetions for autocomplete searchCompany(event) { this.commonService.getOrganisationsSuggetions(event.query).subscribe(company => { this.companySuggetions = company; }) } //get job title suggetions for autocomplete searchJobTitle(event) { if (this.selectedCompanySuggetion.Id > -1) { this.commonService.getJobTitles(event.query).subscribe(title => { this.jobTitleSuggetions = title; }); } } //get country code list for dropdown getCountryCode() { this.commonService.getCountryCodes(this.defaultId).subscribe(codes => { this.countryCodeList = codes.filter(x => x.CountryCode != ''); }) } //this method will get selected suggetion in company name autocomplete and assign values to staff object getSelectedComapany(event) { if (this.companySuggetions.findIndex(x => x.CompanyName == this.selectedCompanySuggetion.CompanyName) > -1) { this.staff.Company.Id = this.selectedCompanySuggetion.Id; this.staff.Company.CompanyName = this.selectedCompanySuggetion.CompanyName; } else { this.selectedCompanySuggetion = { Id: this.tempSelectedCompanySuggetion.Id, CompanyName: this.tempSelectedCompanySuggetion.CompanyName } } } //this method will get selected suggetion in role name autocomplete and assign values to staff object getSelectedRole() { if (this.jobTitleSuggetions.findIndex(x => x.TitleName == this.selectedRoleSuggetion.TitleName) > -1) { this.staff.JobTitle = this.selectedRoleSuggetion; this.staff.JobTitleId = this.selectedRoleSuggetion.Id; }else{ this.staff.JobTitle = this.selectedRoleSuggetion; this.staff.JobTitleId = 0; } } //this method will get selected country code form autocomplete and assign to staff object getSelectedCountryCode() { this.staff.MobileCountryCode = this.tempMobileCountryCode.CountryCode; } cancel() { this.selectedCountry = this.staffAddress.Country; this.ref.close(this.staffId); } //get selected user image readURL(files: FileList) { this.filechanged = true; console.log(files.item(0)); this.imageFile = files.item(0); } //staff profile details validation such as firstname, company, job title StaffProfileValidation() { //check firstname if (this.staff.FirstName == "" || this.staff.FirstName == null) { this.activeTabIndex = 0; //by this line selecting prifle tab programatically if errors this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please fill firstname!' }); return false; } //check email format if(this.staff.Email !="" && !this.isEmail(this.staff.Email)){ this.activeTabIndex = 0; //by this line selecting prifle tab programatically if errors this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please check email format!' }); return false; } //validation for company if (!this.staff.Company || this.staff.Company.Id < 1) { this.activeTabIndex = 0; //by this line selecting prifle tab programatically if errors this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please select organisation!' }); return false; } if(!this.selectedRoleSuggetion || this.selectedRoleSuggetion==""){ this.activeTabIndex = 0; //by this line selecting prifle tab programatically if errors this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please add job title!' }); return false; }else if(this.selectedRoleSuggetion.TitleName==""){ this.activeTabIndex = 0; //by this line selecting prifle tab programatically if errors this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please add job title!' }); return false; } //if job title object not set or id is less than 1, it will be added as new if (!this.staff.JobTitle || this.staff.JobTitle.Id < 1) { this.staff.JobTitle = { Id : 0, TitleName : this.selectedRoleSuggetion }; this.staff.JobTitleId = 0; } //if all goes well, return true return true; } //staff address details validation staffAddressValidation() { //check staff street name in address if (this.staffAddress.StreetName == "" || this.staffAddress.StreetName == null) { this.errMsg = []; this.activeTabIndex = 1; this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please fill address line 1!' }); return false; } //check staff country in address if (!this.staffAddress.Country || this.staffAddress.Country.Id < 1) { this.errMsg = []; this.activeTabIndex = 1; this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please select country!' }); return false; } //check staff state in address if (!this.staffAddress.State || this.staffAddress.State.Id < 1) { this.errMsg = []; this.activeTabIndex = 1; this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please select state!' }); return false; } //check staff city in address if (this.staffAddress.City == "" || this.staffAddress.City == null) { this.errMsg = []; this.activeTabIndex = 1; this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please fill city!' }); return false; } return true; } //staff more details validations staffMoreDetailsValidation() { //looping all noew details fields and check empty for (var x in this.detailsList.value) { if (this.detailsList.value[x]['Title'] == "") { this.errMsg = []; this.activeTabIndex = 4; //by this line selecting tab programatically if errors this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please fill all more details!' }); return false; } } return true; } //staff more details validations staffCustomSocialMediaValidation() { //looping all noew details fields and check empty for (var x in this.staffSocialComponent.newCustomAccounts) { if (this.staffSocialComponent.newCustomAccounts[x].Name == "") { this.errMsg = []; this.activeTabIndex = 4; //by this line selecting tab programatically if errors this.errMsg.push({ severity: 'error', summary: 'Unable to save', detail: 'Please fill all custom social media fields!' }); return false; } } return true; } //email validation isEmail(search:string):boolean { var serchfind:boolean; var regexp = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/); serchfind = regexp.test(search); console.log(serchfind) return serchfind } //this will keep active tab index updated handleChange(e) { this.activeTabIndex = e.index; } }