subscriptionprice.component.ts 15.2 KB
import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, TemplateRef, Pipe, PipeTransform, ViewChild,HostListener } from '@angular/core';
import { SubscriptionPriceService } from './subscriptionprice.service';
import { Router } from '@angular/router';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SubscriptionPriceModel }  from '../userentity/datamodel';
import { BsDatepickerModule } from 'ngx-bootstrap';
import { Http, Response } from '@angular/http';
import { DatePipe } from '@angular/common';
import { ContenteditableModelDirective } from '../../shared/contenteditabledirective'
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { PagerComponent } from '../../shared/pager/pager.component';
import { LoadingService } from '../../shared/loading.service';
import { GlobalService } from '../../shared/global';
import { ConfirmService } from '../../shared/confirm/confirm.service';
declare var $:any;

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

export class SubscriptionPrice implements OnInit {

Mode: string = 'Search';
subscriptionPrice: SubscriptionPriceModel;
subscriptionPrices: Array<SubscriptionPriceModel>;
subscriptionPriceFrm: FormGroup;
insertSubscriptionPriceFrm: FormGroup;
checkedRecords: Array<number>;
error: any;
alerts: string;
modalAlerts: string;
topPos: string = '2000px';
datePipe: DatePipe = new DatePipe('en-US');
selectedEditionId: number = 1;
divClass: string = '';
modalRef: BsModalRef;
NoRecord: string;
@ViewChild(PagerComponent) pagerComponent: PagerComponent;
recordCount: number;
pageNo: number;
pageLength: number;
RecordDeleted: number[];
// Declare height and width variables
scrHeight:any;
scrWidth:any;
 SearchField:any={
	  editionId:1,
	  sortColumn:'Id', 
	  sortOrder:'asc',
	  pageNo:1,
      pageLength:10	  
    }
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {

 var $ua = navigator.userAgent;
 if (($ua.match(/(iPod|iPhone|iPad|android)/i))) {
   this.scrHeight = window.innerHeight-400;
 }
 else
 {
   this.scrHeight = window.innerHeight-330;
 }
  if(this.scrHeight<=360) this.scrHeight=360;
	
   $(".ft_container").css("height",this.scrHeight);
}

  constructor(private subscriptionPriceService: SubscriptionPriceService, private router: Router,
    private fb: FormBuilder, private modalService: BsModalService, public global: GlobalService, 
    private _loadingService: LoadingService, private _confirmService: ConfirmService) { this.getScreenSize();}
  
    ngOnInit(): void {
        this.divClass = 'col-sm-12';
        this.subscriptionPrice = new SubscriptionPriceModel();
        this.alerts = '';
        this.subscriptionPriceFrm = this.fb.group({
            subscriptionPrices: this.fb.array([])
        });
        this.insertSubscriptionPriceFrm = this.fb.group({
            subscriptionPriceId: [''],
            title: ['', [Validators.required,this.noWhitespaceValidator]],
            price: ['', [Validators.required, Validators.pattern('[0-9.]*'),this.noWhitespaceValidator]],
            duration: ['', [Validators.required, Validators.pattern('[0-9]*'),this.noWhitespaceValidator]],
            editionId: [''],
            isActive: ['false']
        });
        $('#fixed_hdr2').fxdHdrCol({
          fixedCols: 0,
          width: "100%",
          height: this.scrHeight,
          colModal: [
            { width: 150, align: 'center' },
            { width: 490, align: 'center' },
            { width: 200, align: 'Center' },
            { width: 200, align: 'Center' },
            { width: 200, align: 'Center' },
          ],
          sort: true
        });

        this.global.ValidationMsg = '';
        this.pageNo = 1;
        this.pageLength = 10;
        this.NoRecord = this.global.NoRecords;
        this.recordCount = 0;
        this.pagerComponent = new PagerComponent();
 
        // if(document.getElementById("fixed_table_rc") != null){
            // document.getElementById("fixed_table_rc").remove();
            // var testScript = document.createElement("script");
            // testScript.setAttribute("id", "fixed_table_rc");
            // testScript.setAttribute("src", "../assets/scripts/fixed_table_rc.js");
            // testScript.setAttribute("type", "text/javascript");
            // document.body.appendChild(testScript);
        // }
		
		var thisObject=this;//class object
		$(".ft_rwrapper table thead tr th").on("click",function(event){  
				
		  if(event.currentTarget.id!=undefined && event.currentTarget.id!="" && event.currentTarget.id!=null && event.currentTarget.id!="unknown")
		  {
			var fieldName=event.currentTarget.id;
			var sortType=''
			var isAscSort = $(".ft_rwrapper table thead tr #"+fieldName).hasClass('fx_sort_asc'); 
			$(".ft_rwrapper table thead tr th").removeClass('fx_sort_asc fx_sort_desc'); 
			$(".ft_rwrapper table thead tr #unknown").removeClass('fx_sort_bg');
		  
			if (isAscSort) { 
			  $(".ft_rwrapper table thead tr #"+fieldName).addClass('fx_sort_desc').removeClass('fx_sort_asc'); 
			  sortType="desc";
			} else { 
			  $(".ft_rwrapper table thead tr #"+fieldName).addClass('fx_sort_asc').removeClass('fx_sort_desc'); 
			  sortType="asc";
			}
	  
			thisObject.SortTableRecords(fieldName,sortType);  

		  }
		 
		});
    }
	
    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 };
         
     }

   SortTableRecords(fieldName:string,sortType:string) {  
	this.SearchField.sortColumn=fieldName;
	this.SearchField.sortOrder=sortType;
	
	this.GetPriceList();
   }
   
    public SearchSubscriptionPrices(evt: any) {
        var tempArr = evt.split(',');
        this.pageNo = parseInt(tempArr[0]);
        this.pageLength = parseInt(tempArr[1]);
		this.SearchField.pageNo=this.pageNo;
	    this.SearchField.pageLength=this.pageLength;
		
		this.GetPriceList();
        
    }

    SearchRecords(searchEditionId: number) {
		this.selectedEditionId = searchEditionId;
		this.pageNo=1;
		this.SearchField.editionId=this.selectedEditionId;
		this.SearchField.pageNo=this.pageNo;
		
		this.GetPriceList();
    }
	
   GetPriceList() {
     this._loadingService.ShowLoading("global-loading");
	 $(".ft_rwrapper table thead tr #unknown").removeClass('fx_sort_bg');
        this.subscriptionPriceService.GetSubscriptionPrices(this.SearchField)
        .subscribe(x => { this.BindFormFields(x) }, error => this.error = error);   
    
   }

    openModal(template: TemplateRef<any>) {
        if(this.checkedRecords.filter(C => C > 0).length == 0) return;
        this.modalRef = this.modalService.show(template);
    }

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

    AfterDeleteData(data, template) {
        if (data.Status == "false") {
            this._confirmService.activate("Subscription prices delete unsuccessfull", "alertMsg");
        } else {
            this.modalAlerts = "<p>Subscription prices deleted successfully</p>";
            this.modalRef = this.modalService.show(template);
            this.SearchRecords(this.selectedEditionId);
        }
    }

    AfterInsertData(data, template) {
        if (data.Status == "false") {
          this.modalAlerts = "<p>Subscription insert unsuccessfull</p>";
          this.modalRef = this.modalService.show(template);
          this._loadingService.HideLoading("global-loading");
        } else {
          this._confirmService.activate("Subscription saved successfull", "alertMsg");
            this.CancelAdd();
            
        }
		
    }

    AfterUpdateData(data, template) {
      if (data.Status == "false") {
        this.modalAlerts = "<p>Subscription prices update unsuccessfull</p>";
        this.modalRef = this.modalService.show(template);
         
        } else {
          this._confirmService.activate("Subscriptions updated successfully", "alertMsg");
        }
		this._loadingService.HideLoading("global-loading");
    }

    BindFormFields(data){
        this.recordCount = data.RecordCount;
        this.subscriptionPrices = data.SubscriptionPriceList;
        this.checkedRecords = new Array<number>(this.subscriptionPrices.length);
        this.subscriptionPriceFrm.setControl('subscriptionPrices', this.fb.array(this.subscriptionPrices));
        if (this.subscriptionPrices.length > 0) {
            this.NoRecord = '';
            this._loadingService.HideLoading("global-loading");
        }
        if (this.subscriptionPrices.length == 0) {
            this.NoRecord = this.global.NoRecords;
            this._loadingService.HideLoading("global-loading");
        }
    }

    UpdateSubscriptionPrices(template: TemplateRef<any>){
        console.log(this.subscriptionPriceFrm.value);  
        this.alerts = '';
        if(this.alerts == ''){
			this._loadingService.ShowLoading("global-loading");
            var obj = this.subscriptionPriceFrm.controls['subscriptionPrices'].value;   
                this.subscriptionPriceService.UpdateSubscriptionPrices(obj).subscribe(
                data => (this.AfterUpdateData(data, template)),
                error => {
					this._loadingService.HideLoading("global-loading");
                    this.error = <any>error; 
                    this.alerts = "<span>" + this.error + "</span>";
                });
        }
    }

    InsertSubscriptionPrice(template: TemplateRef<any>){
        console.log(this.insertSubscriptionPriceFrm.value);  
        this.alerts = '';
        if(this.alerts == ''){
			this._loadingService.ShowLoading("global-loading");
            var obj = this.insertSubscriptionPriceFrm.value;
                return this.subscriptionPriceService.InsertSubscriptionPrice(obj)
                .subscribe(
                data => (this.AfterInsertData(data, template)),
                error => {
                    this.error = <any>error; 
                    this.alerts = "<span>" + this.error + "</span>";
                });
        }
    }

    DeleteSubscriptionPrices(template: TemplateRef<any>){
        this.modalRef.hide();
        console.log(this.checkedRecords);  
        this.alerts = '';
        var deletedSubscriptions = '';
        var unDeletedSubscriptions = '';
        let cnt = 0;
        if(this.alerts == ''){
			 this._loadingService.ShowLoading("global-loading");
            this.RecordDeleted = [];
            this.checkedRecords.filter(C => C > 0).forEach(element => {
                this.subscriptionPriceService.CheckSubscriptionPlanForLicense(element)
                .subscribe(
                data => { 
                    if (data == "True") {
                        cnt++;
                        unDeletedSubscriptions += this.subscriptionPrices.find(C => C.Id == element).Title + ", ";
                        if(cnt == this.checkedRecords.filter(C => C > 0).length)
                        {
                            this.modalAlerts = '';
                            if(deletedSubscriptions != ''){
                                this.modalAlerts = "<p>Subscription prices " + deletedSubscriptions.substr(0, deletedSubscriptions.length - 2) + " deleted successfully</p>";
                            }
                            if(unDeletedSubscriptions != ''){
                                this.modalAlerts += "<p>Subscription prices " + unDeletedSubscriptions.substr(0, unDeletedSubscriptions.length - 2) + " are already mapped to licenses and cannot be deleted.</p>";
                            }
                            this.modalRef = this.modalService.show(template);
                            this.SearchRecords(this.selectedEditionId);
                        }
                    } 
                    else{
                        this.subscriptionPriceService.DeleteSubscriptionPrice(element)
                        .subscribe(
                        data => { 
                            if (data == "True") {
                                cnt++;
                                deletedSubscriptions += this.subscriptionPrices.find(C => C.Id == element).Title + ", ";
                            }
                            if(cnt == this.checkedRecords.filter(C => C > 0).length)
                            {
                                this.modalAlerts = '';
                                if(deletedSubscriptions != ''){
                                    this.modalAlerts = "<p>Subscription prices " + deletedSubscriptions.substr(0, deletedSubscriptions.length - 2) + " deleted successfully</p>";
                                }
                                if(unDeletedSubscriptions != ''){
                                    this.modalAlerts += "<p>Subscription prices " + unDeletedSubscriptions.substr(0, unDeletedSubscriptions.length - 2) + " are already mapped to licenses and cannot be deleted.</p>";
                                }
                                this.modalRef = this.modalService.show(template);
                                this.SearchRecords(this.selectedEditionId);
                            }
                        },
                        error => {
                            this.error = <any>error; 
                            this.alerts = "<span>" + this.error + "</span>";
                        })
                    }
                },
                error => {
                    this.error = <any>error; 
                    this.alerts = "<span>" + this.error + "</span>";
                });
            });
            
        }
    }

    AddSubscriptionPrice(){
        this.Mode = 'Add';
        this.topPos = '100px';
        this.divClass = 'col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3';
        this.insertSubscriptionPriceFrm.reset();
        this.alerts = '';
        this.insertSubscriptionPriceFrm.controls['subscriptionPriceId'].setValue(0);
        this.insertSubscriptionPriceFrm.controls['title'].setValue('');
        this.insertSubscriptionPriceFrm.controls['price'].setValue('');
        this.insertSubscriptionPriceFrm.controls['duration'].setValue('');
        this.insertSubscriptionPriceFrm.controls['editionId'].setValue(this.selectedEditionId);
        this.insertSubscriptionPriceFrm.controls['isActive'].setValue('false');
    }

    CancelAdd(){
        this.Mode = 'Search';
        this.topPos = '2000px';
        this.divClass = 'col-sm-12';
        this.insertSubscriptionPriceFrm.reset();
        this.alerts = '';
        this.SearchSubscriptionPrices(this.pageNo + ', ' + this.pageLength);
    }
    
    redirect() {
      this.router.navigate(['/']);
    }

}