Thursday 7 November 2019

Filtering and data bind in gridview functionality in SPFX

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
//import styles from './PrFilter.module.scss';
import { escape } from '@microsoft/sp-lodash-subset';

import * as strings from 'PrFilterWebPartStrings';
import PrFilter from './components/PrFilter';
import { IPrFilterProps } from './components/IPrFilterProps';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import  Web, { Item }  from 'sp-pnp-js';
import { string } from 'prop-types';
import * as $ from 'jquery';
//import {  _spPageContextInfo  } from '@types/sharepoint';
//import * as Datetime from 'react-datetime';

export interface IPrFilterWebPartProps {
  description: string;
  //value:string;
}
export interface ISPLists {
  value: ISPList[];
}
export interface ISPList {
  PR_Number: string;
  Desc1: string;
  RequestDateIs: string;
  Status: string;
}




//const styles2 = require('./FilterCSS.css');
//const styles2 = require('./customCSS.css');
//let styles3 = require<any>('./FilterCSS.css');


export default class PrFilterWebPart extends BaseClientSideWebPart<IPrFilterWebPartProps>


  private _getListDataPageLoad(): Promise<ISPLists>
  { 
 //get all items
    //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?`, SPHttpClient.configurations.v1)
   
    // get login user in group
    //this.context.pageContext.legacyPageContext.webAbsoluteUrl

    let loginUserIDis = this.context.pageContext.legacyPageContext.userId;
    console.log(loginUserIDis);
    //let loginn2 = this.context.pageContext.legacyPageContext.currentUser;

    let loginName = this.context.pageContext.legacyPageContext.userLoginName;
     console.log("lname   " + loginName);
    let User = this.context.pageContext.user.displayName;
     console.log("dispaly name is " + User); 


    //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$select=PR_Number,Desc1,Status&$filter=Author/Id eq ${loginUserIDis}`, SPHttpClient.configurations.v1)
    return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$select=ID,PR_Number,Desc1,RequestDateIs,Status&$filter=Author/Id eq ${loginUserIDis}&$orderby=ID desc`, SPHttpClient.configurations.v1)
   
    //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?`, SPHttpClient.configurations.v1)
       .then((response: SPHttpClientResponse) => {
          //alert("login user is");
         return response.json();
       });
       
  }


  private __getListDataPRNumberSearch(): Promise<ISPLists>
  { 
   
    // let searchboxValPRnumber: string=(this.domElement.querySelector('#searchbox') as  HTMLInputElement).value;
    // searchboxValPRnumber ="";

    let queryString: string = '';
    let queryStringforPR: string = '';

    let loginUserIDis = this.context.pageContext.legacyPageContext.userId;
    console.log(loginUserIDis);

    let searchboxVal: string=(this.domElement.querySelector('#searchbox') as  HTMLInputElement).value;
    if(searchboxVal!="")
    {     
      //queryString="$filter=substringof('"+searchboxVal+"',PR_Number)";
      queryStringforPR = searchboxVal;
      //console.log("qurery string value is " + queryString);
      console.log("queryStringforPR value is " + queryStringforPR);
      //searchboxVal="";

      // $('#searchbox').attr("value", "");
     
      var input = $("#searchbox");
      input = input.val('').clone(true);

      var input = $("#Fromdt");
      input = input.val('').clone(true);
      var input = $("#Todt");
      input = input.val('').clone(true);


     
    }
   

      //Final
     //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$filter=Desc1 eq ${queryStringforPR}`, SPHttpClient.configurations.v1)
     //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$filter=PR_Number eq ${queryStringforPR}`, SPHttpClient.configurations.v1)
     return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$filter=((PR_Number eq ${queryStringforPR}) and (Author/Id eq ${loginUserIDis}))`, SPHttpClient.configurations.v1)
   
        .then((response: SPHttpClientResponse) =>
        {
          return response.json();         
        });       
  }



  private _getListDataDateBetween(): Promise<ISPLists> {

    let FromDateIs: string=(this.domElement.querySelector('#Fromdt') as  HTMLInputElement).value;
    let ToDateIs: string=(this.domElement.querySelector('#Todt') as  HTMLInputElement).value;

    let loginUserIDis = this.context.pageContext.legacyPageContext.userId;
    console.log(loginUserIDis);

    console.log("dt  "+ FromDateIs);
    console.log("dt  "+ ToDateIs);

     //date between
     //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$select=PR_Number,Desc1,RequestDateIs,Status,Created&$orderby=Created &$filter=Created ge datetime'${FromDateIs}T00%3a00%3a00' and Created le datetime'${ToDateIs}T00%3a00%3a00'`, SPHttpClient.configurations.v1)
   
     //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$select=PR_Number,Desc1,RequestDateIs,Status,Created&$filter=Created ge datetime'${FromDateIs}T00%3a00%3a00' and Created le datetime'${ToDateIs}T00%3a00%3a00' and (Author/Id eq ${loginUserIDis})`, SPHttpClient.configurations.v1)       

     return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$select=ID,PR_Number,Desc1,RequestDateIs,Status,Created&$orderby=ID desc&$filter=Created ge datetime'${FromDateIs}T00%3a00%3a00' and Created le datetime'${ToDateIs}T00%3a00%3a00' and (Author/Id eq ${loginUserIDis})`, SPHttpClient.configurations.v1)             

     //return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('PurchaseRequest')/Items?$select=PR_Number,Desc1,RequestDateIs,Created&$orderby=Created &$filter=Created ge datetime'2019-10-10T00%3a00%3a00' and Created le datetime'2019-10-15T00%3a00%3a00'`, SPHttpClient.configurations.v1)   
        .then((response: SPHttpClientResponse) => {
          return response.json();
        });

      //   $('#datebtn').click(function(e){
      //     e.preventDefault();
      //     // Code goes here
      // });
       
  }



  private _renderListAsync(): void
  { 
     //Bind gridview on Page load
    this._getListDataPageLoad()
    .then((response) => {
      this._renderList(response.value);
    });

  }

  private _renderListAsyncPRNumberSearch(): void
  { 
    //Bind grdiview when PR Number search
    this.__getListDataPRNumberSearch()
    .then((response) => {   
      this._renderList(response.value);
    });

  }


  private _renderListAsyncDateBetween(): void
  { 

    //Bind grdiview when Date between search
    this._getListDataDateBetween()
    .then((response) => {
      this._renderList(response.value);
    });

  }





  private _renderList(items: ISPList[]): void
  {
    //debugger;
    let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse: collapse;">';
    html += `<th style="text-align:center"; >PR Number</th><th style="text-align:center";>Description</th><th style="text-align:center";>Request Date</th><th style="text-align:center";>Status</th>`;
    items.forEach((item: ISPList) => {
      html += `
          <tr>
          <td style="text-align:center"; >${item.PR_Number}</td>
          <td style="text-align:center";>${item.Desc1}</td>
          <td style="text-align:center";>${item.RequestDateIs}</td>
          <td style="text-align:center";>${item.Status}</td>
          </tr>
          `;
    });
    html += `</table>`;
    const listContainer: Element = this.domElement.querySelector('#spListContainer');
    listContainer.innerHTML = html;
  }


  private _setSearchBtnEventHandlers(): void
  {
    //debugger;
    this.domElement.querySelector('#searchBtn').addEventListener('click', () => {
     
        this._renderListAsyncPRNumberSearch();
    });

    //for date selection
    this.domElement.querySelector('#datebtn').addEventListener('click', () => {
      this._renderListAsyncDateBetween();

  });

 } 
  public render(): void {

    this.domElement.innerHTML = `
    <div>
    <div>
    <style>
    #textInput3 {
      color: #fff;
      font-size: 0;
      width: 135px;
      height: 60px;
      border: none;
      margin: 0;
      padding: 0;
      background: #0c0 url(image) 0 0 no-repeat;
     }
    </style>
      <div class="ms-Grid-row ms-fontColor-white">
        <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">     
          <p class="ms-font-l ms-fontColor-white" style="text-align: left">P2P Tool</p>
        </div>
      </div>
      <div class="ms-Grid-row ms-fontColor-white ">
      <div width="100%">
        <input id="searchbox" type="textbox" placeholder="Enter PR No"  onfocus="this.value=''" style="width:95px;"/><input id="searchBtn" type="button" value="Search" style="margin-right:30px;"/>
        <input id="searchboxPONumber" type="textbox" placeholder="Enter PO No"  style="width:95px;" onfocus="this.value=''"/><input id="searchBtnPONumber" type="button" value="Search" style="margin-right:26px;"/>
        From: <input type="date" id="Fromdt" name="FromDate" onfocus="this.value=''">       
        To: <input type="date" id="Todt" name="Todate">
        <input type="submit" id="datebtn" value="search">
        </div>   
        <br>
        <div id="spListContainer" style="width:843px;" />
      </div>
    </div>
  </div>`;
    this._renderListAsync();
    this._setSearchBtnEventHandlers();
  }
 
  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}