Search This Blog

Friday, March 11, 2022

Behaviour Resuable code in angular

 import { Injectable } from '@angular/core';

import { BehaviorSubject, Observable, Subject } from 'rxjs';


@Injectable({ providedIn: 'root' })

export class FilterService {

        public openfilters = new BehaviorSubject<any>(null);

        public bookedfilter = new BehaviorSubject<any>(null);

        public rejectedfilter = new BehaviorSubject<any>(null);

    setFilterData(message, screen) {


        if(screen === 'open')

        {

            this.openfilters.next(message);

        }

        else if(screen === 'booked')

        {

            this.bookedfilter.next(message);

        }

        else if (screen === 'rejected')

        {

            this.rejectedfilter.next(message);

        }

   

     }


     getFilterData(screen): Observable<any> {


         let Observable = null;


        if(screen === 'open')

        {

            Observable = this.openfilters.asObservable();

        }

        else if(screen === 'booked')

        {

            Observable = this.bookedfilter.asObservable();

        }

        else if (screen === 'rejected')

        {

            Observable = this.rejectedfilter.asObservable();

        }

   


        return Observable;

    }

}




import { Component, OnInit, HostListener } from '@angular/core';

import { FormGroup, FormBuilder } from '@angular/forms';

import { CpbookingService } from 'src/app/modules/cpadmin/service/cpbooking.service';

import { UtilsService } from 'src/app/core/services/utils/utils.service';

import { MomentService } from 'src/app/core/services/utils/moment.service';

import { FormValidatorService } from 'src/app/core/services/formValidator/form-validator.service';

import { AgGridRouterComponent } from 'src/app/core/modules/shared/components/ag-grid-router/ag-grid-router.component';

import { AgGridMenuComponent } from 'src/app/core/modules/shared/components/ag-grid-router/ag-grid-menu.component';

import { Roles } from 'src/app/modules/auth/model/user';

import { IGetRowsParams } from 'ag-grid-community';

import { ActionItems } from 'src/app/core/services/constants';

import { StockReportService } from 'src/app/modules/common/service/stock-reports/stock-report.service';

import { StorageService } from 'src/app/core/services/storage/storage.service';

import { FilterService } from '../../../filterService';


@Component({

  selector: 'app-agent-my-booking',

  templateUrl: './agent-my-booking.component.html',

  styleUrls: ['./agent-my-booking.component.css']

})

export class AgentMyBookingComponent implements OnInit {


  

  public columnDefs;

  public defaultColDef

  public gridOptions;

  public gridApi;

  public gridColumnApi;

  public searchValue;

  public gridData =[];

  public cpName =[] ;

  otlList =[];


  public bookingSearchForm: FormGroup;

  clientNames=[]; 

  public parent_permission =[];

  public pageSize = 10;

  public editOpf = false;

  public editOpfActionMenu = false;

  public opfPermission;

  public partList=[];

  public role;

  public displayChannelPartnerKeys = ['name', 'cpnumber']

  public displayHospitalKeys = ['name', 'custNumber']

  public userEmail;

  public subscription;

  public cpnum:any;

  public custNumber :any;


  constructor(private _bookingService: CpbookingService,private _StockReportService:StockReportService,private _StorageService : StorageService,

    private _utilsService : UtilsService , private _momentService: MomentService, private fb: FormBuilder,private _formValidator: FormValidatorService,public _FilterService : FilterService ) { }

  @HostListener('window:resize', ['$event'])onResize(event) {

      this.gridApi.sizeColumnsToFit();

  }

  ngOnInit() {



   this.userEmail = this._StorageService.getUserDetails().email;

    this.loadopfPermission();

    this.role = this._StorageService.getUserDetails().role

    this.loadBookingSearchForm();

    this.setOtlList()

    this.setClientList();

    this.setCpList();

    this.setPartsList()

    this.checkEditAccessControl();

    this.defaultColDef = {

      sortable: true,

      filter: false,

      resizable: true

    };


    this.gridOptions = {

      rowHeight: 45,

      paginationPageSize: 10,

      cacheBlockSize : 10,

      rowModelType :'infinite',

      cacheOverflowSize:100,

      maxConcurrentDatasourceRequests: 2,

      onPaginationChanged: (params) => {

        if (params.newPage) {

            let currentPageBooked= params.api.paginationGetCurrentPage();    

           localStorage.setItem('currentPageBooked', JSON.stringify(currentPageBooked));

          }

        }

    };


    this.gridOptions.onSortChanged = event => {

      this.gridApi.redrawRows(); 

    }

    this.gridOptions.onFilterChanged = event => {

      this.gridApi.redrawRows(); 

    }

    this.columnDefs = [

      {

        field: 'id',

        headerName: 'S No.',

        width: 100,

        sortable: false,

        filter: false,

        valueGetter: "node.rowIndex + 1",

      },

      {

        headerName: 'OPF Number',

        field: 'OPFNumber',

        width: 190,

        cellRendererFramework: AgGridRouterComponent,

        cellRendererParams: {

          inRouterLink: '/agent/bookings/ba/view/',

        },

      },

      {

        headerName: 'Ordered Date and Time',

        field: 'created_on',

        valueFormatter : this.formatDate.bind(this),

        width: 250,

      },

      {

        headerName: 'Client Name',

        field: 'custName',

        width: 420,

      },

      {

        headerName: 'Channel Partner',

        field: 'cpName',

        width: 250,

      },

      {

        headerName: 'OTL No.',

        field: 'OTLNumber',

        width: 200,

      },

      {

        headerName: 'Net Amount (Rs.)',

        field: 'net_amount',

        width: 200,

        comparator: (param1, param2) => {

          return this._utilsService.numberSorting(param1,param2);

        },

        cellRenderer :(params) =>{

          return typeof params.value !== 'undefined' ? "<div class = 'text-right'>" + this._utilsService.rupeeFormat(this.RoundOFTwoDigit(params.value)) + "</div>"  : ''

        }


      },

      {

        headerName: 'Total Amount (Rs.)',

        field: 'total_amount',

        width: 200,

        comparator: (param1, param2) => {

          return this._utilsService.numberSorting(param1,param2);

        },

        cellRenderer :(params) =>{

          return typeof params.value !== 'undefined' ? "<div class = 'text-right'>" + this._utilsService.rupeeFormat(this.RoundOFTwoDigit(params.value))  + "</div>"   : ''

        }

      },

      {

        headerName: 'Order Status',

        field: 'status',

        width: 190,

      },

      {

        field: 'status',

        headerName: 'Action',

        sortable: false, 

        filter: false,

        width: 100,

        cellRendererFramework: AgGridMenuComponent,

        cellRendererParams:  (params) => {

          let menu = [];

          menu.push({

            name: 'View',

            link: '/agent/bookings/ba/view/',

          });

          if (this.editOpfActionMenu && params.data && !params.data['isInvoiced'] && this.editOpf) {

            menu.push({

                name: 'Edit',

                link: '/agent/bookings/ba/edit/',

              })

          }

          return { 

            menu

          }

        },

      }

    ];


  }

  setActionsPermission(name){

    return this.opfPermission && typeof this.opfPermission[ActionItems[name]] != 'undefined'  ?  true : false;

  }


  loadopfPermission(){

      this._bookingService.getActionPermission({model : 'opf'}, response =>{

        this.opfPermission= response['opf'];

        this.editOpfActionMenu = this.setActionsPermission('EDIT')

      });

  }


  checkEditAccessControl(){

    this._bookingService.getOPFAccessControls({module:'OPF_Edit', email: this.userEmail},response =>{

     //this.editOpf = response[0]['isBAAllowed'];

      //this.editOpf  = response.field_permission;


      this.editOpf  =  response.parent_permission[0]['is_allowed'];

      //this.parent_permission =  response.parent_permission[0]['is_allowed'];

  

    })

  }


  setOtlList(){

    this._bookingService.getListofOTLParts(res =>{

      this.otlList =  this._utilsService.groupByMultipleKeys(res,['name','OTLnumber'])

    })

  }


  setClientList(){

    this._bookingService.listHospital( res =>{

      this.clientNames = this._utilsService.groupByMultipleKeys(res,['name','custNumber'])

    })

  }


  setCpList(){

    this._bookingService.listChannelPartner(res=>{

      this.cpName = this._utilsService.groupByMultipleKeys(res,['name','cpnumber']) 

    })

  }

  formatDate(params){

    return params.data ? this._momentService.getDateTimeFormat(params.data.created_on) : ''

  }

  onGridReady(params) {

    this.gridApi = params.api;

    this.gridColumnApi = params.columnApi;

    this.gridApi.sizeColumnsToFit();

    this.setOpfParams();

  }


  setOpfParams(){

  //   let data = {

  //     from_date : this._momentService.getFilterFormat(this.bookingSearchForm.get('from_date').value),

  //     to_date : this._momentService.getFilterFormat(this.bookingSearchForm.get('to_date').value, "toDate"),

  //     status: 'Booked'

  //   }

  //  return  this.getOPFList(data);



   this.subscription = this._FilterService.getFilterData('booked').subscribe(res => {

    let data = {};


    if(res)

    {

    this._bookingService.listChannelPartner(res1=>{

   this.cpName =  this._utilsService.groupByMultipleKeys(res1,['name','cpnumber'])

  this.cpnum = this.cpName.filter(marker => {

    return marker.cpnumber === res.cpnumber;


 })


 this.bookingSearchForm.get('cpnumber').setValue({ name: this.cpnum[0].name, cpnumber: this.cpnum[0].cpnumber });


})


this._bookingService.listHospital( res2 =>{

  this.clientNames =  this._utilsService.groupByMultipleKeys(res2,['name','custNumber'])


     this.custNumber = this.clientNames.filter(clientnames => {

       return clientnames.custNumber  === res.custNumber

     })


     this.bookingSearchForm.get('custNumber').setValue({ name: this.custNumber[0].name, cpnumber: this.custNumber[0].custNumber });

})





       console.log(this.cpnum, this.bookingSearchForm);


      this.bookingSearchForm.get('OTLNumber').setValue({OTLnumber : res.OTLNumber});

      this.bookingSearchForm.get('partNumber').setValue({partNumber: res.partNumber});


      this.bookingSearchForm.get('OPFNumber').setValue(res.OPFNumber);


      //this.bookingSearchForm.get('status').setValue(res.status);

      this.bookingSearchForm.get('from_date').setValue(res.from_date);

      this.bookingSearchForm.get('to_date').setValue(res.to_date);

      this.getOPFList(res);


    }

    else

    {

       data = {

        from_date : this._momentService.getFilterFormat(this.bookingSearchForm.get('from_date').value),

        to_date : this._momentService.getFilterFormat(this.bookingSearchForm.get('to_date').value, "toDate"),

        status: 'Booked'

       }


      this.getOPFList(data);

    }


  });












  


  }



  getOPFList(data ?:any) {

    let payload = {};

    var datasource = {

      getRows: (params: IGetRowsParams) =>{

        if (data) {

          payload = data;

        }

        payload['page_size'] =this.pageSize

        payload['page'] = ((params.endRow % this.pageSize) == 0) ? (params.endRow / this.pageSize) : (params.endRow / this.pageSize)+1

        payload['sort_key'] =params.sortModel.length ? params.sortModel[0]['colId'] : ''

        payload['sort_type'] = params.sortModel.length ? params.sortModel[0]['sort'] : ''

          this._bookingService.searchBooking(payload,(res)=>{

            let length = res['total'];

            this.gridData = res['results'];

            params.successCallback(res['results'], length)

            const pageToNavigate = JSON.parse(localStorage.getItem('currentPageBooked'));

            this.gridApi.paginationGoToPage(pageToNavigate);

          })

      }

    }

    this.gridApi.setDatasource(datasource);

  }



 //  search filter 

 loadBookingSearchForm(){

  this.bookingSearchForm = this.fb.group({

    custNumber: ['',this._formValidator.requireMatch],

    OPFNumber: [''],

    cpnumber: [''],

    OTLNumber: [''],

    from_date:[this._momentService.deceedDate(new Date(),31)],

    to_date:[new Date()],

    partNumber :  ['',this._formValidator.requireMatch],

  },{ validator: this._formValidator.dateValidation('from_date', 'to_date') });

}


searchBookingFilter(){

if (this.bookingSearchForm.valid){

  let data = this.getBookingPayload(this.bookingSearchForm.value);

  this._FilterService.setFilterData(data, 'booked');

  this._FilterService.getFilterData('booked').subscribe(res => {

  this.getOPFList(res);

 })

}

}


ngOnDestroy() {

  this.subscription.unsubscribe();

}


setPartsList(){

  // need to change api  

  this._StockReportService.getListParts(this.role,(res) => {

    this.partList = res  

  });

}

getBookingPayload(bookingValue){

   let data =  {};

  data['custNumber'] =  bookingValue.custNumber ? bookingValue.custNumber.custNumber : '';

  if(data['custNumber'] == undefined)

  {

    data['custNumber'] = bookingValue.custNumber.cpnumber;

  }

  data['cpnumber'] =  bookingValue.cpnumber ? bookingValue.cpnumber.cpnumber : '';

  if(data['cpnumber'] == undefined)

  {

    data['cpnumber'] = bookingValue.cpnumber.cpnumber;

  }

  data['OTLNumber'] = bookingValue.OTLNumber ? bookingValue.OTLNumber.OTLnumber : '';

  if(data['OTLNumber'] == undefined)

  {

    data['OTLNumber'] = "";

  }

  data['from_date'] = bookingValue.from_date ?  this._momentService.getFilterFormat(bookingValue.from_date,"toDate") : '';

  data['to_date'] = bookingValue.to_date ? this._momentService.getFilterFormat(bookingValue.to_date, "toDate") : '';

  data['OPFNumber'] =bookingValue.OPFNumber ? bookingValue.OPFNumber : '';

  data['partNumber'] =bookingValue.partNumber ? bookingValue.partNumber.partNumber : '';

  if(data['partNumber'] == undefined)

  {

    data['partNumber'] = "";

  }

   data['status'] =  'Booked'

 // data['status'] =  bookingValue.status ? bookingValue.status : 'Booked'

  return data;

}

cancelFilter(){

  this.bookingSearchForm.reset();

  this.bookingSearchForm.get('from_date').setValue(this._momentService.deceedDate(new Date(),31));

  this.bookingSearchForm.get('to_date').setValue(new Date())

  let data = {

    from_date : this._momentService.getFilterFormat(this.bookingSearchForm.get('from_date').value, "toDate"),

    to_date : this._momentService.getFilterFormat(this.bookingSearchForm.get('to_date').value, "toDate"),

    status: 'Booked' 

   }

   this.getOPFList(data);

   this._FilterService.setFilterData(data, 'booked');



  //this.setOpfParams();

}


exportBookingFilter(){

  let bookingPayload =  this.getBookingPayload(this.bookingSearchForm.value);

  // bookingPayload['from_date'] = bookingPayload['from_date'] ?  bookingPayload['from_date'] : this._momentService.getFilterFormat(this._momentService.deceedDate(new Date(),90))

  // bookingPayload['to_date'] =  bookingPayload['to_date'] ?  bookingPayload['to_date'] : this._momentService.getFilterFormat(new Date(), "toDate")

  bookingPayload['status'] = 'Booked'

 this._bookingService.exportBookingFilter(bookingPayload);

}

RoundOFTwoDigit(num: any){

  var number = Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2);

  return number;

}


}
















No comments:

Post a Comment

Validating to select in sequencial order using angular

    < input type = "checkbox" (change) = "handleSelectTaskItem($event, taskItem)" [checked] = " taskItem . i...