usergroup.component.ts 13.6 KB
import { Component, OnInit, AfterViewInit, AfterViewChecked, Input, Output, EventEmitter, Pipe, PipeTransform, TemplateRef, ViewChild } from '@angular/core';
import { UserService } from './user.service';
import { Router, ActivatedRoute } from '@angular/router';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { License } from '../userentity/datamodel';
import { BsDatepickerModule } from 'ngx-bootstrap';
import { Http, Response } from '@angular/http';
import { DatePipe } from '@angular/common';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { ConfirmService } from '../../shared/confirm/confirm.service';
import { PagerComponent } from '../../shared/pager/pager.component';
import { LoadingService } from '../../shared/loading.service';
import { GlobalService } from '../../shared/global';
declare var $:JQueryStatic;
declare var jQuery: any;

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

export class UserGroup implements OnInit, AfterViewChecked {

  lstAccountNumbers: any;
  tempLstAccountNumbers: any;
  lstLicenseUserGroups: any;
  licenseUserGroup: any;
  lstLicenseUserGroupUsers: any;
  lstAllUsers: any;
  mode: string = 'Search';
  modalTitle: string = 'User Group';
  license: License;
  updateUserGroupFrm: FormGroup;
  error: any;
  alerts: string;
  modalAlerts: string;
  divClass: string = '';
  topPos: string = '2000px';
  selectedRow: number = -1;
  selectedId: number = -1;
  modalRef: BsModalRef;
  checkedRecords: Array<number>;
  NoRecord: string;
  @ViewChild(PagerComponent) pagerComponent: PagerComponent;
  recordCount: number;
  pageNo: number;
  pageLength: number;
  recordCountUser: number;
  pageNoUser: number;
  pageLengthUser: number;
  loopIdx: number;
  userGroupName: string;
    
  constructor(private userService: UserService, private router: Router,
    private activeRoute: ActivatedRoute, private fb: FormBuilder, private modalService: BsModalService,
    private _confirmService: ConfirmService, public global: GlobalService, private _loadingService: LoadingService) { }

  ngOnInit(): void {
    this._loadingService.ShowLoading("global-loading");
    $('#accountSelect').chosen({allow_single_deselect:true,width:'200px',placeholder_text_single:'Select Account',search_contains:true});
    
    this.selectedRow = -1;
    this.selectedId = -1;
    this.divClass = 'col-sm-12';
    this.license = new License();
    this.alerts = '';
    this.loopIdx = 0;
    this.userGroupName = '';
    this.NoRecord = this.global.NoRecords;
    this._loadingService.ShowLoading("global-loading");
    this.recordCount = 0;
    this.pageNo = 1;
    this.pageLength = 10;
    this.recordCountUser = 0;
    this.pageNoUser = 1;
    this.pageLengthUser = 10;
    this.pagerComponent = new PagerComponent();
    this.updateUserGroupFrm = this.fb.group({
      userGroupName: ['', Validators.required],
    });
    if (this.global.UserType > 2) {
      this.lstAccountNumbers=[];
      this.lstAccountNumbers.push({m_Item1:this.global.AccLicId,m_Item2:this.global.AccountNumber});
      this.AccountNumberChanged(this.global.AccLicId);
     
      setTimeout(function(){               
        $('#accountSelect').prop('disabled', true).trigger("chosen:updated");
        $('#accountSelect').trigger('chosen:updated'); 
      
     }, 500);
     this._loadingService.HideLoading("global-loading");
    }
    else
    {    
      this.GetLicenseAccounts();
    }
    $('#accountSelect')
      .on('change', (e, args) => {
        var selectedValue = Number(args.selected);
        //var selectedText= $(".chosen-single span" ).text();
        this.AccountNumberChanged(selectedValue);
      });
   
  }

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }

  onChange(Idx: number, Id: number, isChecked: boolean) {
    if (isChecked) {
      this.checkedRecords[Idx] = Id;
    }
    else {
      this.checkedRecords[Idx] = 0;
    }
  }

  SetClickedRow(i: number, item: any) {
    this.selectedRow = i;
    this.selectedId = item['Id'];
    this.licenseUserGroup = item;
  }

  BindFormFields(data) {
    this.recordCount = data.RecordCount;
    this.lstLicenseUserGroups = data.UserGroupList;
    if (this.selectedRow > -1) {
      this.licenseUserGroup = this.lstLicenseUserGroups[this.selectedRow];
      this.selectedId = this.licenseUserGroup['Id'];
    }
    if (this.lstLicenseUserGroups.length > 0) {
      this.NoRecord = '';
      this._loadingService.HideLoading("global-loading");
    }
    if (this.lstLicenseUserGroups.length == 0) {
      this.NoRecord = this.global.NoRecords;
      this._loadingService.HideLoading("global-loading");
    }
  }

  BindUserFormFields(data) {
    this.recordCountUser = data.RecordCount;
    this.lstLicenseUserGroupUsers = data.UserList;
    if (this.mode == 'Edit') {
      this.checkedRecords = new Array<number>(this.lstLicenseUserGroupUsers.length);
      for (let i = 0; i < this.lstLicenseUserGroupUsers.length; i++) {
        if (this.lstLicenseUserGroupUsers[i].InGroup > 0) {
          this.checkedRecords[i] = this.lstLicenseUserGroupUsers[i].Id;
        }
      }
    }
    if (this.lstLicenseUserGroupUsers.length > 0) {
      this.NoRecord = '';
      this._loadingService.HideLoading("global-loading");
    }
    if (this.lstLicenseUserGroupUsers.length == 0) {
      this.NoRecord = this.global.NoRecords;
      this._loadingService.HideLoading("global-loading");
    }
  }

  GetLicenseAccounts() {
    this.lstAccountNumbers=[];
    this.userService.GetLicenseAccounts(1)
      .subscribe(st => {   
       var newOption = $('<option value=""></option>');
       $('#accountSelect').append(newOption);
        this.lstAccountNumbers=st;       
        setTimeout(function(){         
          $('#accountSelect').trigger('chosen:updated');  
       }, 500);
       this._loadingService.HideLoading("global-loading");

      }, error => this.error = <any>error);
  }

  GetLicenseUserGroups(evt: any) {
    this.alerts = '';
    this._loadingService.ShowLoading("global-loading");
    var tempArr = evt.split(',');
    this.pageNo = parseInt(tempArr[0]);
    this.pageLength = parseInt(tempArr[1]);
    this.userService.GetLicenseUserGroups(this.license.LicenseId, this.pageNo, this.pageLength)
      .subscribe(st => { this.BindFormFields(st); }, error => this.error = <any>error);
  }

  SearchRecords() {
    this.GetLicenseUserGroups('1, ' + this.pageLength);
  }

  GetLicenseUserGroupUsers(evt: any) {
    this.alerts = '';
    this._loadingService.ShowLoading("global-loading");
    var tempArr = evt.split(',');
    this.pageNoUser = parseInt(tempArr[0]);
    this.pageLengthUser = parseInt(tempArr[1]);
    var AllUsers = false;
    if (this.mode == 'Edit') {
      AllUsers = true;
    }
    this.userService.GetLicenseUserGroupUsers(this.license.LicenseId, this.selectedId, AllUsers, this.pageNoUser, this.pageLengthUser)
      .subscribe(st => { this.BindUserFormFields(st); }, error => this.error = <any>error);
  }

  SearchUserRecords() {
    this.GetLicenseUserGroupUsers('1, ' + this.pageLengthUser);
  }

  AccountNumberChanged(LicenseId: number) {
    this.license.LicenseId = LicenseId;
    this.selectedRow = -1;
    this.selectedId = -1;
    this.lstLicenseUserGroups = null;
    this.updateUserGroupFrm.controls['userGroupName'].setValue('');
    this.userGroupName = '';
    this.SearchRecords();
  }

  AfterDeleteData(data, template) {
    if (data.Status == "false") {
      this.alerts = "<span>License user group delete unsuccessfull</span>";
    } else {
      this._confirmService.activate("License user group deleted successfully.", "alertMsg");
      // this.modalAlerts = "<p>License user group deleted successfully</p>";
      //this.modalRef = this.modalService.show(template);
      this.selectedRow = -1;
      this.selectedId = -1;
      this.SearchRecords();
    }
  }

  AfterInsertData(data, template) {
    if (data.Status == "false") {
      this.alerts = "<span>License user group save unsuccessfull</span>";
    } else {
      this._confirmService.activate("License user group saved successfully.", "alertMsg");
      //this.modalAlerts = "<p>License user group saved successfully</p>";
      //this.modalRef = this.modalService.show(template);
      this.SearchRecords();
    }
  }

  AfterUpdateData(data, template) {
    if (data.Status == "false") {
      this.alerts = "<span>License user group update unsuccessfull</span>";
    } else {
      this._confirmService.activate("License user group updated successfully.", "alertMsg");
      //this.modalAlerts = "<p>License user group updated successfully</p>";
      //this.modalRef = this.modalService.show(template);
      this.SearchRecords();
    }
  }

  InsertLicenseUserGroup(title: string, template: TemplateRef<any>) {
    this.alerts = '';
    if (title == '' || title == undefined) {
      this.alerts = "<span>Please enter a name for user group.</span>";
      return;
    }
    var obj = {
      'id': 0, 'licenseId': this.license.LicenseId, 'title': title,
      'isActive': true, 'creationDate': new Date(),
      'modifiedDate': new Date()
    };
    if (this.alerts == '') {
      this.userService.CheckDuplicateLicenseUserGroup(this.license.LicenseId, title)
        .subscribe(
        data => {
            if(data == "True"){
              this.alerts = "<span>User group name already exists. Enter a different name.</span>";
            }
            else{
              this.userService.InsertUpdateLicenseUserGroup(obj)
                  .subscribe(
                  n => (this.AfterInsertData(n, template)),
                  error => this.error = <any>error);
            }
        },
        error => this.error = <any>error);
      }
  }

  UpdateLicenseUserGroup(template: TemplateRef<any>) {
    this.alerts = '';
    var obj = {
      'id': this.licenseUserGroup.Id,
      'licenseId': this.license.LicenseId,
      'title': this.updateUserGroupFrm.controls['userGroupName'].value,
      'isActive': this.licenseUserGroup.IsActive,
      'creationDate': this.licenseUserGroup.CreationDate,
      'modifiedDate': this.licenseUserGroup.ModifiedDate
    };
    if (this.alerts == '') {
        if(this.licenseUserGroup.Title.toString().toLowerCase().trim() != obj.title.toString().toLowerCase().trim())
        {
          this.userService.CheckDuplicateLicenseUserGroup(this.license.LicenseId, this.updateUserGroupFrm.controls['userGroupName'].value)
          .subscribe(
          data => {
              if(data == "True"){
                this.alerts = "<span>User group name already exists. Enter a different name.</span>";
              }
              else{
                this.userService.InsertUpdateLicenseUserGroup(obj)
                .subscribe(
                n => (
                  this.UpdateLicenseUserGroupUsers(template)
                ),
                error => this.error = <any>error);
              }
          },
          error => this.error = <any>error);
        }
        else{
          this.userService.InsertUpdateLicenseUserGroup(obj)
                .subscribe(
                n => (
                  this.UpdateLicenseUserGroupUsers(template)
                ),
                error => this.error = <any>error);
        }
    }
  }

  UpdateLicenseUserGroupUsers(template: TemplateRef<any>) {
    var userIds = '';
    for (let i = 0; i < this.lstLicenseUserGroupUsers.length; i++) {
      if (this.checkedRecords.find(C => C == this.lstLicenseUserGroupUsers[i].Id) > 0) {
        userIds += this.lstLicenseUserGroupUsers[i].Id + '-1,';
      }
      else {
        userIds += this.lstLicenseUserGroupUsers[i].Id + '-0,';
      }
    }
    if (userIds != '') {
      userIds = userIds.substr(0, userIds.length - 1);
    }
    return this.userService.UpdateLicenseUserGroupUsers(this.selectedId, userIds)
      .subscribe(
      n => (
        this.AfterUpdateData(n, template)
      ),
      error => this.error = <any>error);
  }

  DeleteLicenseUserGroup(template: TemplateRef<any>) {
    this.modalRef.hide();
    this.alerts = '';
    if (this.selectedId == 0) {
      this.alerts = "<span>Please select a license user group</span>";
    }
    if (this.alerts == '') {
      return this.userService.DeleteLicenseUserGroup(this.selectedId)
        .subscribe(
        data => (this.AfterDeleteData(data, template)),
        error => {
          this.error = <any>error;
          this.alerts = "<span>License user group delete unsuccessfull</span>";
        });
    }
  }

  EditLicenseUserGroup() {
    jQuery('.ft_r thead tr th:eq(0)').show();
    this.mode = 'Edit';
    this.modalTitle = 'Edit User Group';
    this.topPos = '100px';
    this.alerts = '';
    this.updateUserGroupFrm.controls['userGroupName'].setValue(this.licenseUserGroup.Title);
    this.recordCountUser = 0;
    this.pageNoUser = 1;
    this.pageLengthUser = 10;
    this.SearchUserRecords();
  }

  ngAfterViewChecked() {
    jQuery('#tblUserGroupUsers thead').css('width', jQuery('#tblUserGroupUsers tbody tr:eq(0)').width());
  }

  ViewLicenseUserGroup() {
    jQuery('.ft_r thead tr th:eq(0)').hide();
    this.mode = 'View';
    this.modalTitle = 'View User Group';
    this.topPos = '100px';
    this.alerts = '';
    this.updateUserGroupFrm.controls['userGroupName'].setValue(this.licenseUserGroup.Title);
    this.recordCountUser = 0;
    this.pageNoUser = 1;
    this.pageLengthUser = 10;
    this.SearchUserRecords();
  }

  CancelAddEdit() {
    this.mode = 'Search';
    this.modalTitle = 'User Group';
    this.topPos = '2000px';
    this.SearchRecords();
    this.selectedRow = this.lstLicenseUserGroups.findIndex(C => C.Id == this.selectedId);
    this.SetClickedRow(this.selectedRow, this.lstLicenseUserGroups.find(C => C.Id == this.selectedId));
  }
}