adduser.component.ts 9.31 KB
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, HostListener } from '@angular/core';
import { UserService } from '../userentity/user.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { User,License } from '../userentity/datamodel';
import { Http, Response } from '@angular/http';
import { GlobalService } from '../../shared/global';
import { LicenseService } from '../licenseentity/license.service';
import { ConfirmService } from '../../shared/confirm/confirm.service';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import { LoadingService } from '../../shared/loading.service';
declare var $:JQueryStatic;

@Component({
  templateUrl: './adduser.component.html'
})

export class AddUser implements OnInit {
  user: User;
  baseUrl: string = "User";
  adduserFrm: FormGroup;
  useFname: string;
  error;
  status: boolean;
  alerts: string;
  emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
  public UserTypeList: any;
  tempLstAccountNumbers: any;
  public ProductEditionList: any;
  modalTitle: string;
  license: License;
  LicenseTypeId:number=0;
  LicenseId:number=0;
  AccountNumber:string='';
  
  constructor(private _loadingService: LoadingService, private userservice: UserService, private router: Router, private fb: FormBuilder, private http: Http,
    private _confirmService: ConfirmService, public commonService: GlobalService,private licenseService: LicenseService) { }

  ngOnInit(): void {
    this._loadingService.ShowLoading("global-loading");
    $('#accountSelect').chosen({allow_single_deselect:true,width:'300px',placeholder_text_single:'Select Account',search_contains:true });
 
    this.user = new User();
    this.alerts = '';
    this.adduserFrm = this.fb.group({
      id: [''],
      UserName: ['', [Validators.required, Validators.minLength(8)]],
      Password: ['', [Validators.required, Validators.minLength(8)]],
      ConfirmPassword: ['', [Validators.required]],
      FirstName: ['', [Validators.required,this.noWhitespaceValidator]],
      LastName: ['', [Validators.required,this.noWhitespaceValidator]],
      EmailId: ['', [Validators.required]],
      AccountNumberId: ['', Validators.required],
      UserTypeId: ['', Validators.required],
      ProductEditionId: ['', Validators.required]
    });

    this.bindUsers(0);
      if (this.commonService.UserType > 2) {
        this.tempLstAccountNumbers=[];
        this.tempLstAccountNumbers.push({Id:this.commonService.AccLicId,AccountNumber:this.commonService.AccountNumber});
        this.AccountNumberChanged(this.commonService.AccLicId,this.commonService.AccountNumber);
       
        setTimeout(function(){         
          $('#accountSelect').prop('disabled', true).trigger("chosen:updated");
          $('#accountSelect').trigger('chosen:updated'); 
        
       }, 500);
       this._loadingService.HideLoading("global-loading");
      }
      else
      {    
        this.GetAccountNumber();
      }
      $('#accountSelect')
        .on('change', (e, args) => {
          var selectedValue = Number(args.selected);
          var selectedText= $(".chosen-single span" ).text();
          this.AccountNumberChanged(selectedValue,selectedText);
        });  
  
  }

  redirect() {
    this.router.navigate(['/']);
  }

  public noWhitespaceValidator(control: FormControl) {
    // new validation for intial whaite space
    //****Birendra *****/
     var isValid=false;
     if(control.value!=null)
     {
      var controlLen=control.value.length;
      if(controlLen==undefined)//undefined for integer value
      {
       isValid=true;
      }
     else if(controlLen!=0)
      {
        const isWhitespace = (control.value || '').trim().length === 0;
         isValid = !isWhitespace;
        if(!isValid)
        {
          control.setValue('');
          
        }
      }
     }  
     // can use also on page of input control
     //
     return isValid ? null: { 'whitespace': true };
     
 }
  GetUserTypeByLicenseId() {
    this.userservice.GetUserTypeByLicenseType({
      AccountNumberId: this.LicenseId
    }).subscribe(x => {
       this.UserTypeList = x; 
      }, error => this.error = <any>error);
  }

  GetAccountNumber() {
    this.tempLstAccountNumbers=[];
    this.userservice.GetAccountNumber()
      .subscribe(x => {
        var newOption = $('<option value=""></option>');
        $('#accountSelect').append(newOption);
         this.tempLstAccountNumbers=x;       
         setTimeout(function(){             
           $('#accountSelect').trigger('chosen:updated');  
        }, 500);

        this._loadingService.HideLoading("global-loading");
      },
      error => this.error = <any>error);
  }

  GetProductEdition() {
    this.userservice.GetProductEdition({
      AccountNumberId: this.LicenseId
    })
      .subscribe(x => { 
        console.log(x); 
        this.ProductEditionList = x ;
        this._loadingService.HideLoading("global-loading");
      }, error => this.error = <any>error);
  }
 
  AccountNumberChanged(LicenseId: number, AccountNumber: string) {
    this._loadingService.ShowLoading("global-loading");
    this.adduserFrm.controls['AccountNumberId'].setValue(LicenseId);
    this.LicenseId=LicenseId;
    this.AccountNumber=AccountNumber;

    this.licenseService.GetLicenseById(LicenseId)
      .subscribe(st => {        
        this.license = st;
        this.LicenseTypeId=this.license.LicenseTypeId;
      },
      error => this.error = <any>error);
      
    this.GetUserTypeByLicenseId();
    this.GetProductEdition();   
      
    return false;
  }

  public AddUser() {

    this.alerts = '';
    
    if (this.adduserFrm.value.UserName == '' ||(!this.adduserFrm.controls.UserName.valid))
    {
      this.alerts += '<span>User Name of minimum 8 characters is required.</span>';
    }
    if (this.adduserFrm.value.Password == '' ||(!this.adduserFrm.controls.Password.valid )) {
      this.alerts += '</br><span>Password of minimum 8 characters is required.</span>';
    }
   
    if (this.adduserFrm.value.ConfirmPassword == '') {
      this.alerts += '</br><span>Confirm Password is required.</span>';
    }
    if (this.adduserFrm.value.Password != this.adduserFrm.value.ConfirmPassword) {
      this.alerts += '</br><span>Password and confirm password must be same</span>';
    }
    
    if (this.adduserFrm.value.EmailId == '' ||(!this.adduserFrm.controls.EmailId.valid)) {
      this.alerts += '</br><span>Email Id is required.</span>';
    }
          
    if (this.adduserFrm.value.FirstName == '') {
    this.alerts += '</br><span>First Name is required.</span>';
    }
    if (this.adduserFrm.value.LastName == '') {
    this.alerts += '</br><span>Last Name is required.</span>';
     }
 
    if (this.adduserFrm.value.AccountNumberId == '0') {
      this.alerts += '</br><span>Please select account number</span>';
    }
    if (this.adduserFrm.value.UserTypeId == '0') {
      this.alerts += '</br><span>Please select user type</span>';
    }
    if (this.adduserFrm.value.ProductEditionId == '0') {
      this.alerts += '</br><span>Please select product edition</span>';
    }
    
    if (this.alerts == '') {
      var AddUserEntity = this.adduserFrm.value;
      return this.userservice.InsertUser(AddUserEntity)
        .subscribe(
        n => (this.AfterInsertData(n)),
        error => {
          this.error = <any>error;
          this.alerts = "<span>" + this.error + "</span>";
        });
    }

  }
  AfterInsertData(data) {
    if (data == "User added successfully") {
      this.alerts = '';
      this._confirmService.activate("User added successfully.", "alertMsg");
    }

  }
  ResetForm() {
   var lcid= this.adduserFrm.controls['AccountNumberId'].value;
    this._buildForm(lcid);
  }
  _buildForm(lcid) {
    this.adduserFrm = this.fb.group({
      id: [''],
      UserName: ['', [Validators.required, Validators.minLength(8)]],
      Password: ['', [Validators.required, Validators.minLength(8)]],
      ConfirmPassword: ['', [Validators.required]],
      FirstName: ['', [Validators.required,this.noWhitespaceValidator]],
      LastName: ['', [Validators.required,this.noWhitespaceValidator]],
      EmailId: ['', [Validators.required]],
      AccountNumberId: ['', Validators.required],
      UserTypeId: ['', Validators.required],
      ProductEditionId: ['', Validators.required]
    });
    this.bindUsers(lcid);
  }
  bindUsers(lcid) {
    this.alerts = '';
    if (this.commonService.UserTypeName == "Client Admin" || this.commonService.UserTypeName == "District Admin" ) 
    {
      this.adduserFrm.controls['AccountNumberId'].setValue(lcid)
    }
    else
    {
      this.adduserFrm.controls['AccountNumberId'].setValue(0);
      $('#accountSelect').val('').trigger('chosen:updated');
      this.UserTypeList=[];
      this.ProductEditionList=[];
    }
    
    this.adduserFrm.controls['id'].setValue(0)
    this.adduserFrm.controls['FirstName'].setValue('')
    this.adduserFrm.controls['LastName'].setValue('')
    this.adduserFrm.controls['EmailId'].setValue('')
    this.adduserFrm.controls['UserName'].setValue('')
    this.adduserFrm.controls['Password'].setValue('')
    this.adduserFrm.controls['ConfirmPassword'].setValue('')
    
    this.adduserFrm.controls['UserTypeId'].setValue(0)
   
    this.adduserFrm.controls['ProductEditionId'].setValue(0);

  }
}