From d0543719b798296f9f0cf85a7cf7d25cbbb9e99f Mon Sep 17 00:00:00 2001
From: Muthukrishnanmatriot
 <76949556+muthukrishnanmatriot@users.noreply.github.com>
Date: Mon, 24 May 2021 08:38:54 +0530
Subject: [PATCH] Update the code for server side sorting

---
 .../tmss_webapp/src/components/ViewTable.js   | 54 +++++++++++++------
 .../routes/Scheduling/SchedulingUnitList.js   | 34 +++++++++---
 2 files changed, 64 insertions(+), 24 deletions(-)

diff --git a/SAS/TMSS/frontend/tmss_webapp/src/components/ViewTable.js b/SAS/TMSS/frontend/tmss_webapp/src/components/ViewTable.js
index ed11da3abf7..b3f2680002c 100644
--- a/SAS/TMSS/frontend/tmss_webapp/src/components/ViewTable.js
+++ b/SAS/TMSS/frontend/tmss_webapp/src/components/ViewTable.js
@@ -17,13 +17,14 @@ import { InputNumber } from "primereact/inputnumber";
 import { MultiSelect } from 'primereact/multiselect';
 import { RadioButton } from 'primereact/radiobutton';
 import { useExportData } from "react-table-plugins";
-import UIConstants from '../utils/ui.constants';
+//import UIConstants from '../utils/ui.constants';
 import Papa from "papaparse";
 import JsPDF from "jspdf";
 import "jspdf-autotable";
 
 let doServersideFilter = false;
 let tbldata = [], filteredData = [];
+let data = [];
 let selectedRows = [];
 let isunittest = false;
 let showTopTotal = true;
@@ -819,7 +820,7 @@ function Table(props) {
         sortBy: defaultSortColumn
       },
       manualPagination: true,
-      manualSortBy: true,
+      manualSortBy: doServersideFilter,
       manualFilters: doServersideFilter,
       //autoResetPage: false,
       //autoResetSortBy: false,
@@ -891,10 +892,10 @@ function Table(props) {
   const onShowAllPage = (e) => {
     dataFetchStatus = true;
     setLoading(true);
-    gotoPage(e.page);
-    setcurrentPage(e.first);
-    setcurrentRows(e.rows);
-    setPageSize(tbldata.length)
+    gotoPage(0);
+    setcurrentPage(0);
+    setcurrentRows(0);
+    setPageSize(pageCount)
     setcustompagevalue();
   };
 
@@ -1086,7 +1087,7 @@ function Table(props) {
           </tbody>
         </table>
       </div>
-      <div style={{backgroundColor: 'yellow'}}>{loading &&  
+      <div style={{backgroundImage: '-webkit-linear-gradient(left, yellow, lightgray 60% 25%)'}}>{loading &&  
               <span style={{color: 'red'}}>Loading...</span> 
              }</div>
       <div className="pagination p-grid" >
@@ -1129,9 +1130,10 @@ filterGreaterThan.autoRemove = val => typeof val !== 'number'
 
 function ViewTable(props) {
   const history = useHistory();
-  // Data to show in table
-  //console.log("sessionStorage", JSON.parse(sessionStorage.getItem("sortedData")));
   tbldata = JSON.parse(sessionStorage.getItem("sortedData")) || props.data;
+  data = tbldata;
+  let pageCount = props.totalPage || data.length;
+
   showCSV = (props.showCSV) ? props.showCSV : false;
   doServersideFilter = (props.callBackFunction)?true:false;
   parentCallbackFunction = props.filterCallback;
@@ -1301,11 +1303,14 @@ function ViewTable(props) {
     return value;
   };
 
-  const [data, setData] = React.useState([]);
-  const [pageCount, setPageCount] = React.useState(0);
+  /**
+   * To fetch data from server side - Start
+   */
+  //const [data, setData] = React.useState([]);
+  //const [pageCount, setPageCount] = React.useState(0);
   const [loading, setLoading] = React.useState(false);
   const [currentPage, setCurrentPage] = React.useState(0);
-
+  
   const fetchData = React.useCallback( ({ state }) => {
       loadServerData(state);
   }, []);
@@ -1318,8 +1323,9 @@ function ViewTable(props) {
           Promise.all(promises).then(async responses => {
               tbldata = responses[0][0];
               if (tbldata) {
-                  setData(tbldata);
-                  setPageCount(Math.ceil(responses[0][1]));
+                  //setData(tbldata);
+                  //setPageCount(Math.ceil(responses[0][1]));
+                  pageCount = Math.ceil(responses[0][1]);
                   setLoading(false);
               }
           });
@@ -1327,14 +1333,30 @@ function ViewTable(props) {
           if(tbldata) {
               const startRow = state.pageSize * state.pageIndex;
               const endRow = startRow + state.pageSize;
-              setData(tbldata.slice(startRow, endRow));
-              setPageCount(Math.ceil(tbldata.length));
+              //setData(tbldata.slice(startRow, endRow));
+              //setPageCount(Math.ceil(tbldata.length));
+              data = tbldata.slice(startRow, endRow);
+              pageCount = Math.ceil(tbldata.length);
               setLoading(false);
           }
       }
   }
   // Set the filterCallback function to load on filter changes
   filterCallback = loadServerData;
+
+  /**
+   * Fetch data from server side - End
+   */
+
+  /** Required to load the data while non server side data loading and for outside table filters  */
+  if (!doServersideFilter && tableOptionsState) {
+      const startRow = tableOptionsState.pageSize * tableOptionsState.pageIndex;
+      const endRow = startRow + tableOptionsState.pageSize;
+      data = tbldata.slice(startRow, endRow);
+  } else {
+      data = tbldata.slice(0, defaultpagesize);
+  }
+
   return (
     <div>
       <Table fetchData={fetchData} pageCount={pageCount} currentPage={currentPage} dataFetchStatus={loading} columns={columns} data={data} defaultheader={defaultheader[0]} optionalheader={optionalheader[0]} showAction={props.showaction}
diff --git a/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/SchedulingUnitList.js b/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/SchedulingUnitList.js
index dce8d08f067..0a767953962 100644
--- a/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/SchedulingUnitList.js
+++ b/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/SchedulingUnitList.js
@@ -166,7 +166,7 @@ class SchedulingUnitList extends Component{
         this.reloadData = this.reloadData.bind(this);
         this.addTargetColumns = this.addTargetColumns.bind(this);
         this.fetchTableData = this.fetchTableData.bind(this);
-        this.changeSUType = this.changeSUType.bind(this);
+        this.changeScheduleUnitType = this.changeScheduleUnitType.bind(this);
     }
 
     /**
@@ -259,7 +259,6 @@ class SchedulingUnitList extends Component{
     }
 
     getAPIFilter(suFilters, columnDef) {
-       // let filterMap =  UIConstants.FILTER_MAP;
         let defaultColumsProps = columnDef;
         const defaultColKeys = Object.keys(columnDef);
         defaultColKeys.forEach(key => {
@@ -290,6 +289,9 @@ class SchedulingUnitList extends Component{
         return defaultColumsProps;
     }
 
+    /**
+     * Get server side filter column details form API
+     */
     async getFilterColumns() {
         const suFilters = await ScheduleService.getSchedulingUnitDraftFilter();
         this.columnMap = [];
@@ -300,7 +302,15 @@ class SchedulingUnitList extends Component{
         }
     }
 
-    
+    /**
+     * 
+     * @param {Boolean} isInitial - true => While loading page, false => while doing server side access
+     * @param {String} suType - SU type ( blueprint/draft)
+     * @param {String} filterQry - Table filter params
+     * @param {String} orderBy - Table order by param
+     * @param {Number} limit - Number of the rows to fetch
+     * @param {Number} offset - fetch row from nth position
+     */
     async getSchedulingUnitList (isInitial, suType, filterQry, orderBy, limit, offset) {
         if (isInitial) {
             const schedulingSet = await ScheduleService.getSchedulingSets();
@@ -666,13 +676,22 @@ class SchedulingUnitList extends Component{
         this.setState({dialogVisible: false});
     }
 
-    async changeSUType(type) {
+    /**
+     * Switch the SU type and fetch the data from the server
+     * @param {String} type - SU Type
+     */
+    async changeScheduleUnitType(type) {
         this.filterQry = '';
         this.orderBy = '';
         await this.setState({suType: type, showSpinner: true, scheduleunit: []});
-        await this.getSchedulingUnitList(true, this.state.suType.toLowerCase(), this.filterQry, this.orderBy, this.limit, this.offset);
+        await this.getSchedulingUnitList(false, this.state.suType.toLowerCase(),this.filterQry, this.orderBy, this.limit, this.offset);
     }
     
+    /**
+     * Fetch data from server side - while doing pagination, filtering, sorting
+     * @param {Table State} Table props state 
+     * @returns 
+     */
     async fetchTableData(state) {
         this.filterQry = '';
         this.orderBy = '';
@@ -692,7 +711,6 @@ class SchedulingUnitList extends Component{
                 this.orderBy = 'ordering='+((sortBy.desc)?'-':'')+columnDetails.orgField;
             }
         }
-
         this.filterQry = this.filterQry.substring(0,this.filterQry.length-1);
         await this.getSchedulingUnitList(false, this.state.suType, this.filterQry, this.orderBy, state.pageSize, (state.pageIndex*state.pageSize));
         this.setState({showSpinner: false});
@@ -713,7 +731,7 @@ class SchedulingUnitList extends Component{
                                     tooltip="Schedule Unit Type" tooltipOptions={this.tooltipOptions}
                                     value={this.state.suType}
                                     options={this.suTypeList} 
-                                    onChange={(e) => {this.changeSUType( e.value)}} 
+                                    onChange={(e) => {this.changeScheduleUnitType( e.value)}} 
                                     style={{width: '10em', marginLeft: '0.5em'}}
                                     />
                             </span>
@@ -745,7 +763,7 @@ class SchedulingUnitList extends Component{
                 </div>
 
                 {/* {   (this.state.scheduleunit && this.state.scheduleunit.length>0)? */}
-                { this.state.scheduleunit?
+                {  (this.state.scheduleunit)?
                     <ViewTable 
                         data={this.state.scheduleunit} 
                         totalPage={this.totalPage}
-- 
GitLab