Skip to content
Snippets Groups Projects
Commit a637f59f authored by Nithya's avatar Nithya
Browse files
changes updated based on review comments
parent 0015df8c
No related branches found
No related tags found
1 merge request!351Resolve TMSS-570
import React, {useRef, useState } from "react"; import React, { useRef, useState } from "react";
import { useSortBy, useTable, useFilters, useGlobalFilter, useAsyncDebounce, usePagination, useRowSelect } from 'react-table' import { useSortBy, useTable, useFilters, useGlobalFilter, useAsyncDebounce, usePagination, useRowSelect, useColumnOrder } from 'react-table'
import matchSorter from 'match-sorter' import matchSorter from 'match-sorter'
import _ from 'lodash'; import _ from 'lodash';
import moment from 'moment'; import moment from 'moment';
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import {OverlayPanel} from 'primereact/overlaypanel'; import { OverlayPanel } from 'primereact/overlaypanel';
//import {InputSwitch} from 'primereact/inputswitch'; //import {InputSwitch} from 'primereact/inputswitch';
import {InputText} from 'primereact/inputtext'; import { InputText } from 'primereact/inputtext';
import { Calendar } from 'primereact/calendar'; import { Calendar } from 'primereact/calendar';
import {Paginator} from 'primereact/paginator'; import { Paginator } from 'primereact/paginator';
import {TriStateCheckbox} from 'primereact/tristatecheckbox'; import { TriStateCheckbox } from 'primereact/tristatecheckbox';
import { Slider } from 'primereact/slider'; import { Slider } from 'primereact/slider';
import { Button } from "react-bootstrap"; import { Button } from "react-bootstrap";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { InputNumber } from "primereact/inputnumber"; import { InputNumber } from "primereact/inputnumber";
import {MultiSelect} from 'primereact/multiselect'; import { MultiSelect } from 'primereact/multiselect';
import { RadioButton } from 'primereact/radiobutton'; import { RadioButton } from 'primereact/radiobutton';
import { useExportData } from "react-table-plugins"; import { useExportData } from "react-table-plugins";
import Papa from "papaparse"; import Papa from "papaparse";
import JsPDF from "jspdf"; import JsPDF from "jspdf";
import "jspdf-autotable"; import "jspdf-autotable";
let tbldata =[], filteredData = [] ; let tbldata = [], filteredData = [];
let selectedRows = []; let selectedRows = [];
let isunittest = false; let isunittest = false;
let showTopTotal = true; let showTopTotal = true;
...@@ -29,21 +29,21 @@ let showGlobalFilter = true; ...@@ -29,21 +29,21 @@ let showGlobalFilter = true;
let showColumnFilter = true; let showColumnFilter = true;
let allowColumnSelection = true; let allowColumnSelection = true;
let allowRowSelection = false; let allowRowSelection = false;
let columnclassname =[]; let columnclassname = [];
let parentCallbackFunction, parentCBonSelection; let parentCallbackFunction, parentCBonSelection;
let showCSV = false; let showCSV = false;
let anyOfFilter = ''; let anyOfFilter = '';
// Define a default UI for filtering // Define a default UI for filtering
function GlobalFilter({ function GlobalFilter({
preGlobalFilteredRows, preGlobalFilteredRows,
globalFilter, globalFilter,
setGlobalFilter, setGlobalFilter,
}) { }) {
const [value, setValue] = React.useState(globalFilter) const [value, setValue] = React.useState(globalFilter)
const onChange = useAsyncDebounce(value => {setGlobalFilter(value || undefined)}, 200) const onChange = useAsyncDebounce(value => { setGlobalFilter(value || undefined) }, 200)
return ( return (
<span style={{marginLeft:"-10px"}}> <span style={{ marginLeft: "-10px" }}>
<input <input
value={value || ""} value={value || ""}
onChange={e => { onChange={e => {
...@@ -75,11 +75,11 @@ function DefaultColumnFilter({ ...@@ -75,11 +75,11 @@ function DefaultColumnFilter({
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
}} }}
/> />
{value && <i onClick={() => {setFilter(undefined); setValue('') }} className="table-reset fa fa-times" />} {value && <i onClick={() => { setFilter(undefined); setValue('') }} className="table-reset fa fa-times" />}
</div> </div>
) )
} }
/* /*
Generate and download csv Generate and download csv
*/ */
...@@ -94,7 +94,7 @@ function getExportFileBlob({ columns, data, fileType, fileName }) { ...@@ -94,7 +94,7 @@ function getExportFileBlob({ columns, data, fileType, fileName }) {
const headerNames = columns.map((column) => column.exportValue); const headerNames = columns.map((column) => column.exportValue);
const doc = new JsPDF(); const doc = new JsPDF();
var index = headerNames.indexOf('Action'); var index = headerNames.indexOf('Action');
if (index > -1) { if (index > -1) {
headerNames.splice(index, 1); headerNames.splice(index, 1);
} }
doc.autoTable({ doc.autoTable({
...@@ -117,35 +117,36 @@ function SelectColumnFilter({ ...@@ -117,35 +117,36 @@ function SelectColumnFilter({
setValue(''); setValue('');
} }
}, [filterValue, value]); }, [filterValue, value]);
const options = React.useMemo(() => { const options = React.useMemo(() => {
const options = new Set() const options = new Set()
preFilteredRows.forEach(row => { preFilteredRows.forEach(row => {
options.add(row.values[id]) options.add(row.values[id])
}) })
return [...options.values()] return [...options.values()]
}, [id, preFilteredRows]) }, [id, preFilteredRows])
// Render a multi-select box // Render a multi-select box
return ( return (
<div onClick={e => { e.stopPropagation() }}> <div onClick={e => { e.stopPropagation() }}>
<select <select
style={{ style={{
height: '24.2014px', height: '24.2014px',
width: '60px', width: '60px',
border:'1px solid lightgrey', border: '1px solid lightgrey',
}} }}
value={value} value={value}
onChange={e => { setValue(e.target.value); onChange={e => {
setFilter(e.target.value|| undefined) setValue(e.target.value);
}} setFilter(e.target.value || undefined)
> }}
<option value="">All</option> >
{options.map((option, i) => ( <option value="">All</option>
<option key={i} value={option}> {options.map((option, i) => (
{option} <option key={i} value={option}>
</option> {option}
))} </option>
))}
</select> </select>
</div> </div>
) )
} }
...@@ -157,63 +158,64 @@ function MultiSelectColumnFilter({ ...@@ -157,63 +158,64 @@ function MultiSelectColumnFilter({
const [filtertype, setFiltertype] = useState('Any'); const [filtertype, setFiltertype] = useState('Any');
// Set Any / All Filter type // Set Any / All Filter type
const setSelectTypeOption = (option) => { const setSelectTypeOption = (option) => {
setFiltertype(option); setFiltertype(option);
anyOfFilter = option anyOfFilter = option
if(value !== ''){ if (value !== '') {
setFilter(value); setFilter(value);
} }
}; };
React.useEffect(() => { React.useEffect(() => {
if (!filterValue && value) { if (!filterValue && value) {
setValue(''); setValue('');
setFiltertype('Any'); setFiltertype('Any');
} }
}, [filterValue, value, filtertype]); }, [filterValue, value, filtertype]);
anyOfFilter = filtertype; anyOfFilter = filtertype;
const options = React.useMemo(() => { const options = React.useMemo(() => {
let options = new Set(); let options = new Set();
preFilteredRows.forEach(row => { preFilteredRows.forEach(row => {
row.values[id].split(',').forEach( value => { row.values[id].split(',').forEach(value => {
if ( value !== '') { if (value !== '') {
let hasValue = false; let hasValue = false;
options.forEach( option => { options.forEach(option => {
if(option.name === value){ if (option.name === value) {
hasValue = true; hasValue = true;
}
});
if(!hasValue) {
let option = { 'name': value, 'value':value};
options.add(option);
}
} }
}); });
}); if (!hasValue) {
let option = { 'name': value, 'value': value };
options.add(option);
}
}
});
});
return [...options.values()] return [...options.values()]
}, [id, preFilteredRows]); }, [id, preFilteredRows]);
// Render a multi-select box // Render a multi-select box
return ( return (
<div onClick={e => { e.stopPropagation() }} > <div onClick={e => { e.stopPropagation() }} >
<div className="p-field-radiobutton"> <div className="p-field-radiobutton">
<RadioButton inputId="filtertype1" name="filtertype" value="Any" onChange={(e) => setSelectTypeOption(e.value)} checked={filtertype === 'Any'} /> <RadioButton inputId="filtertype1" name="filtertype" value="Any" onChange={(e) => setSelectTypeOption(e.value)} checked={filtertype === 'Any'} />
<label htmlFor="filtertype1">Any</label> <label htmlFor="filtertype1">Any</label>
</div> </div>
<div className="p-field-radiobutton"> <div className="p-field-radiobutton">
<RadioButton inputId="filtertype2" name="filtertype" value="All" onChange={(e) => setSelectTypeOption(e.value)} checked={filtertype === 'All'} /> <RadioButton inputId="filtertype2" name="filtertype" value="All" onChange={(e) => setSelectTypeOption(e.value)} checked={filtertype === 'All'} />
<label htmlFor="filtertype2">All</label> <label htmlFor="filtertype2">All</label>
</div> </div>
<div style={{position: 'relative'}} > <div style={{ position: 'relative' }} >
<MultiSelect data-testid="multi-select" id="multi-select" optionLabel="value" optionValue="value" filter={true} <MultiSelect data-testid="multi-select" id="multi-select" optionLabel="value" optionValue="value" filter={true}
value={value} value={value}
options={options} options={options}
onChange={e => { setValue(e.target.value); onChange={e => {
setFilter(e.target.value|| undefined, filtertype) setValue(e.target.value);
}} setFilter(e.target.value || undefined, filtertype)
className="multi-select" }}
className="multi-select"
/> />
</div> </div>
</div> </div>
) )
} }
...@@ -238,7 +240,7 @@ function SliderColumnFilter({ ...@@ -238,7 +240,7 @@ function SliderColumnFilter({
return ( return (
<div onClick={e => { e.stopPropagation() }} className="table-slider"> <div onClick={e => { e.stopPropagation() }} className="table-slider">
<Slider value={value} onChange={(e) => { setFilter(e.value);setValue(e.value)}} /> <Slider value={value} onChange={(e) => { setFilter(e.value); setValue(e.value) }} />
</div> </div>
) )
} }
...@@ -246,7 +248,7 @@ function SliderColumnFilter({ ...@@ -246,7 +248,7 @@ function SliderColumnFilter({
// This is a custom filter UI that uses a // This is a custom filter UI that uses a
// switch to set the value // switch to set the value
function BooleanColumnFilter({ function BooleanColumnFilter({
column: { setFilter, filterValue}, column: { setFilter, filterValue },
}) { }) {
// Calculate the min and max // Calculate the min and max
// using the preFilteredRows // using the preFilteredRows
...@@ -258,7 +260,7 @@ function BooleanColumnFilter({ ...@@ -258,7 +260,7 @@ function BooleanColumnFilter({
}, [filterValue, value]); }, [filterValue, value]);
return ( return (
<div onClick={e => { e.stopPropagation() }}> <div onClick={e => { e.stopPropagation() }}>
<TriStateCheckbox value={value} style={{'width':'15px','height':'24.2014px'}} onChange={(e) => { setValue(e.value); setFilter(e.value === null ? undefined : e.value); }} /> <TriStateCheckbox value={value} style={{ 'width': '15px', 'height': '24.2014px' }} onChange={(e) => { setValue(e.value); setFilter(e.value === null ? undefined : e.value); }} />
</div> </div>
) )
} }
...@@ -266,7 +268,7 @@ function BooleanColumnFilter({ ...@@ -266,7 +268,7 @@ function BooleanColumnFilter({
// This is a custom filter UI that uses a // This is a custom filter UI that uses a
// calendar to set the value // calendar to set the value
function CalendarColumnFilter({ function CalendarColumnFilter({
column: { setFilter, filterValue}, column: { setFilter, filterValue },
}) { }) {
// Calculate the min and max // Calculate the min and max
// using the preFilteredRows // using the preFilteredRows
...@@ -277,21 +279,21 @@ function CalendarColumnFilter({ ...@@ -277,21 +279,21 @@ function CalendarColumnFilter({
} }
}, [filterValue, value]); }, [filterValue, value]);
return ( return (
<div className="table-filter" onClick={e => { e.stopPropagation() }}> <div className="table-filter" onClick={e => { e.stopPropagation() }}>
<Calendar value={value} appendTo={document.body} onChange={(e) => { <Calendar value={value} appendTo={document.body} onChange={(e) => {
const value = moment(e.value, moment.ISO_8601).format("YYYY-MMM-DD") const value = moment(e.value, moment.ISO_8601).format("YYYY-MMM-DD")
setValue(value); setFilter(value); setValue(value); setFilter(value);
}} showIcon></Calendar> }} showIcon></Calendar>
{value && <i onClick={() => {setFilter(undefined); setValue('') }} className="tb-cal-reset fa fa-times" />} {value && <i onClick={() => { setFilter(undefined); setValue('') }} className="tb-cal-reset fa fa-times" />}
</div> </div>
) )
} }
// This is a custom filter UI that uses a // This is a custom filter UI that uses a
// calendar to set the value // calendar to set the value
function DateTimeColumnFilter({ function DateTimeColumnFilter({
column: { setFilter, filterValue}, column: { setFilter, filterValue },
}) { }) {
const [value, setValue] = useState(''); const [value, setValue] = useState('');
React.useEffect(() => { React.useEffect(() => {
...@@ -300,18 +302,18 @@ function DateTimeColumnFilter({ ...@@ -300,18 +302,18 @@ function DateTimeColumnFilter({
} }
}, [filterValue, value]); }, [filterValue, value]);
return ( return (
<div className="table-filter" onClick={e => { e.stopPropagation() }}> <div className="table-filter" onClick={e => { e.stopPropagation() }}>
<Calendar value={value} appendTo={document.body} onChange={(e) => { <Calendar value={value} appendTo={document.body} onChange={(e) => {
const value = moment(e.value, moment.ISO_8601).format("YYYY-MMM-DD HH:mm:SS") const value = moment(e.value, moment.ISO_8601).format("YYYY-MMM-DD HH:mm:SS")
setValue(value); setFilter(value); setValue(value); setFilter(value);
}} showIcon }} showIcon
// showTime= {true} // showTime= {true}
//showSeconds= {true} //showSeconds= {true}
// hourFormat= "24" // hourFormat= "24"
></Calendar> ></Calendar>
{value && <i onClick={() => {setFilter(undefined); setValue('') }} className="tb-cal-reset fa fa-times" />} {value && <i onClick={() => { setFilter(undefined); setValue('') }} className="tb-cal-reset fa fa-times" />}
</div> </div>
) )
} }
...@@ -322,21 +324,21 @@ function DateTimeColumnFilter({ ...@@ -322,21 +324,21 @@ function DateTimeColumnFilter({
* @param {String} filterValue * @param {String} filterValue
*/ */
function fromDatetimeFilterFn(rows, id, filterValue) { function fromDatetimeFilterFn(rows, id, filterValue) {
const filteredRows = _.filter(rows, function(row) { const filteredRows = _.filter(rows, function (row) {
// If cell value is null or empty // If cell value is null or empty
if (!row.values[id]) { if (!row.values[id]) {
return false; return false;
} }
//Remove microsecond if value passed is UTC string in format "YYYY-MM-DDTHH:mm:ss.sssss" //Remove microsecond if value passed is UTC string in format "YYYY-MM-DDTHH:mm:ss.sssss"
let rowValue = moment.utc(row.values[id].split('.')[0]); let rowValue = moment.utc(row.values[id].split('.')[0]);
if (!rowValue.isValid()) { if (!rowValue.isValid()) {
// For cell data in format 'YYYY-MMM-DD' // For cell data in format 'YYYY-MMM-DD'
rowValue = moment.utc(moment(row.values[id], 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS")); rowValue = moment.utc(moment(row.values[id], 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS"));
} }
const start = moment.utc(moment(filterValue, 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS")); const start = moment.utc(moment(filterValue, 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS"));
return (start.isSameOrBefore(rowValue)); return (start.isSameOrBefore(rowValue));
} ); });
return filteredRows; return filteredRows;
} }
...@@ -348,36 +350,36 @@ function fromDatetimeFilterFn(rows, id, filterValue) { ...@@ -348,36 +350,36 @@ function fromDatetimeFilterFn(rows, id, filterValue) {
*/ */
function multiSelectFilterFn(rows, id, filterValue) { function multiSelectFilterFn(rows, id, filterValue) {
if (filterValue) { if (filterValue) {
const filteredRows = _.filter(rows, function(row) { const filteredRows = _.filter(rows, function (row) {
if ( filterValue.length === 0){ if (filterValue.length === 0) {
return true; return true;
} }
// If cell value is null or empty // If cell value is null or empty
if (!row.values[id]) { if (!row.values[id]) {
return false; return false;
} }
let rowValue = row.values[id]; let rowValue = row.values[id];
let hasData = false; let hasData = false;
if ( anyOfFilter === 'Any' ) { if (anyOfFilter === 'Any') {
hasData = false; hasData = false;
filterValue.forEach(filter => { filterValue.forEach(filter => {
if( rowValue.includes( filter )) { if (rowValue.includes(filter)) {
hasData = true; hasData = true;
}
});
} }
else { });
hasData = true; }
filterValue.forEach(filter => { else {
if( !rowValue.includes( filter )) { hasData = true;
hasData = false; filterValue.forEach(filter => {
} if (!rowValue.includes(filter)) {
}); hasData = false;
} }
return hasData; });
} ); }
return filteredRows; return hasData;
} });
return filteredRows;
}
} }
/** /**
...@@ -388,20 +390,20 @@ function multiSelectFilterFn(rows, id, filterValue) { ...@@ -388,20 +390,20 @@ function multiSelectFilterFn(rows, id, filterValue) {
*/ */
function toDatetimeFilterFn(rows, id, filterValue) { function toDatetimeFilterFn(rows, id, filterValue) {
let end = moment.utc(moment(filterValue, 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS")); let end = moment.utc(moment(filterValue, 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS"));
end = moment(end, "DD-MM-YYYY").add(1, 'days'); end = moment(end, "DD-MM-YYYY").add(1, 'days');
const filteredRows = _.filter(rows, function(row) { const filteredRows = _.filter(rows, function (row) {
// If cell value is null or empty // If cell value is null or empty
if (!row.values[id]) { if (!row.values[id]) {
return false; return false;
} }
//Remove microsecond if value passed is UTC string in format "YYYY-MM-DDTHH:mm:ss.sssss" //Remove microsecond if value passed is UTC string in format "YYYY-MM-DDTHH:mm:ss.sssss"
let rowValue = moment.utc(row.values[id].split('.')[0]); let rowValue = moment.utc(row.values[id].split('.')[0]);
if (!rowValue.isValid()) { if (!rowValue.isValid()) {
// For cell data in format 'YYYY-MMM-DD' // For cell data in format 'YYYY-MMM-DD'
rowValue = moment.utc(moment(row.values[id], 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS")); rowValue = moment.utc(moment(row.values[id], 'YYYY-MMM-DDTHH:mm:SS').format("YYYY-MM-DDTHH:mm:SS"));
} }
return (end.isSameOrAfter(rowValue)); return (end.isSameOrAfter(rowValue));
} ); });
return filteredRows; return filteredRows;
} }
...@@ -412,28 +414,28 @@ function toDatetimeFilterFn(rows, id, filterValue) { ...@@ -412,28 +414,28 @@ function toDatetimeFilterFn(rows, id, filterValue) {
* @param {String} filterValue * @param {String} filterValue
*/ */
function dateFilterFn(rows, id, filterValue) { function dateFilterFn(rows, id, filterValue) {
const filteredRows = _.filter(rows, function(row) { const filteredRows = _.filter(rows, function (row) {
// If cell value is null or empty // If cell value is null or empty
if (!row.values[id]) { if (!row.values[id]) {
return false; return false;
} }
//Remove microsecond if value passed is UTC string in format "YYYY-MM-DDTHH:mm:ss.sssss" //Remove microsecond if value passed is UTC string in format "YYYY-MM-DDTHH:mm:ss.sssss"
let rowValue = moment.utc(row.values[id].split('.')[0]); let rowValue = moment.utc(row.values[id].split('.')[0]);
if (!rowValue.isValid()) { if (!rowValue.isValid()) {
// For cell data in format 'YYYY-MMM-DD' // For cell data in format 'YYYY-MMM-DD'
rowValue = moment.utc(moment(row.values[id], 'YYYY-MMM-DD').format("YYYY-MM-DDT00:00:00")); rowValue = moment.utc(moment(row.values[id], 'YYYY-MMM-DD').format("YYYY-MM-DDT00:00:00"));
} }
const start = moment.utc(moment(filterValue, 'YYYY-MMM-DD').format("YYYY-MM-DDT00:00:00")); const start = moment.utc(moment(filterValue, 'YYYY-MMM-DD').format("YYYY-MM-DDT00:00:00"));
const end = moment.utc(moment(filterValue, 'YYYY-MMM-DD').format("YYYY-MM-DDT23:59:59")); const end = moment.utc(moment(filterValue, 'YYYY-MMM-DD').format("YYYY-MM-DDT23:59:59"));
return (start.isSameOrBefore(rowValue) && end.isSameOrAfter(rowValue)); return (start.isSameOrBefore(rowValue) && end.isSameOrAfter(rowValue));
} ); });
return filteredRows; return filteredRows;
} }
// This is a custom UI for our 'between' or number range // This is a custom UI for our 'between' or number range
// filter. It uses slider to filter between min and max values. // filter. It uses slider to filter between min and max values.
function RangeColumnFilter({ function RangeColumnFilter({
column: { filterValue = [], preFilteredRows, setFilter, id}, column: { filterValue = [], preFilteredRows, setFilter, id },
}) { }) {
const [min, max] = React.useMemo(() => { const [min, max] = React.useMemo(() => {
let min = 0; let min = 0;
...@@ -442,8 +444,8 @@ function RangeColumnFilter({ ...@@ -442,8 +444,8 @@ function RangeColumnFilter({
min = preFilteredRows[0].values[id]; min = preFilteredRows[0].values[id];
} }
preFilteredRows.forEach(row => { preFilteredRows.forEach(row => {
min = Math.min(row.values[id]?row.values[id]:0, min); min = Math.min(row.values[id] ? row.values[id] : 0, min);
max = Math.max(row.values[id]?row.values[id]:0, max); max = Math.max(row.values[id] ? row.values[id] : 0, max);
}); });
return [min, max]; return [min, max];
}, [id, preFilteredRows]); }, [id, preFilteredRows]);
...@@ -454,12 +456,12 @@ function RangeColumnFilter({ ...@@ -454,12 +456,12 @@ function RangeColumnFilter({
return ( return (
<> <>
<div className="filter-slider-label"> <div className="filter-slider-label">
<span style={{float: "left"}}>{filterValue[0]}</span> <span style={{ float: "left" }}>{filterValue[0]}</span>
<span style={{float: "right"}}>{min!==max?filterValue[1]:""}</span> <span style={{ float: "right" }}>{min !== max ? filterValue[1] : ""}</span>
</div> </div>
<Slider value={filterValue} min={min} max={max} className="filter-slider" <Slider value={filterValue} min={min} max={max} className="filter-slider"
style={{}} style={{}}
onChange={(e) => { setFilter(e.value); }} range /> onChange={(e) => { setFilter(e.value); }} range />
</> </>
); );
} }
...@@ -470,9 +472,9 @@ function RangeColumnFilter({ ...@@ -470,9 +472,9 @@ function RangeColumnFilter({
function NumberRangeColumnFilter({ function NumberRangeColumnFilter({
column: { filterValue = [], preFilteredRows, setFilter, id }, column: { filterValue = [], preFilteredRows, setFilter, id },
}) { }) {
const [errorProps, setErrorProps] = useState({}); const [errorProps, setErrorProps] = useState({});
const [maxErr, setMaxErr] = useState(false); const [maxErr, setMaxErr] = useState(false);
const [min, max] = React.useMemo(() => { const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0 let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0 let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => { preFilteredRows.forEach(row => {
...@@ -485,8 +487,8 @@ function NumberRangeColumnFilter({ ...@@ -485,8 +487,8 @@ function NumberRangeColumnFilter({
return ( return (
<div <div
style={{ style={{
// display: 'flex', // display: 'flex',
// flexdirection:'column', // flexdirection:'column',
alignItems: 'center' alignItems: 'center'
}} }}
> >
...@@ -495,16 +497,16 @@ function NumberRangeColumnFilter({ ...@@ -495,16 +497,16 @@ function NumberRangeColumnFilter({
type="number" type="number"
onChange={e => { onChange={e => {
const val = e.target.value; const val = e.target.value;
setFilter((old = []) => [val ? parseFloat (val, 10) : undefined, old[1]]); setFilter((old = []) => [val ? parseFloat(val, 10) : undefined, old[1]]);
}} }}
placeholder={`Min (${min})`} placeholder={`Min (${min})`}
style={{ style={{
width: '55px', width: '55px',
height:'25px' height: '25px'
// marginRight: '0.5rem', // marginRight: '0.5rem',
}} }}
/> />
<InputText <InputText
value={filterValue[1] || ''} value={filterValue[1] || ''}
type="number" type="number"
{...errorProps} {...errorProps}
...@@ -516,19 +518,19 @@ function NumberRangeColumnFilter({ ...@@ -516,19 +518,19 @@ function NumberRangeColumnFilter({
setMaxErr(true); setMaxErr(true);
setErrorProps({ setErrorProps({
tooltip: "Max value should be greater than Min", tooltip: "Max value should be greater than Min",
tooltipOptions: { event: 'hover'} tooltipOptions: { event: 'hover' }
}); });
} else { } else {
setMaxErr(false); setMaxErr(false);
setErrorProps({}); setErrorProps({});
} }
setFilter((old = []) => [old[0], val ? parseFloat (val, 10) : undefined]) setFilter((old = []) => [old[0], val ? parseFloat(val, 10) : undefined])
}} }}
placeholder={`Max (${max})`} placeholder={`Max (${max})`}
style={{ style={{
width: '55px', width: '55px',
height:'25px' height: '25px'
// marginLeft: '0.5rem', // marginLeft: '0.5rem',
}} }}
/> />
</div> </div>
...@@ -541,12 +543,12 @@ function fuzzyTextFilterFn(rows, id, filterValue) { ...@@ -541,12 +543,12 @@ function fuzzyTextFilterFn(rows, id, filterValue) {
} }
const filterTypes = { const filterTypes = {
'select': { 'select': {
fn: SelectColumnFilter, fn: SelectColumnFilter,
}, },
'multiselect': { 'multiselect': {
fn: MultiSelectColumnFilter, fn: MultiSelectColumnFilter,
type: multiSelectFilterFn type: multiSelectFilterFn
}, },
'switch': { 'switch': {
fn: BooleanColumnFilter fn: BooleanColumnFilter
...@@ -570,7 +572,7 @@ const filterTypes = { ...@@ -570,7 +572,7 @@ const filterTypes = {
fn: RangeColumnFilter, fn: RangeColumnFilter,
type: 'between' type: 'between'
}, },
'minMax': { 'minMax': {
fn: NumberRangeColumnFilter, fn: NumberRangeColumnFilter,
type: 'between' type: 'between'
} }
...@@ -590,8 +592,8 @@ const IndeterminateCheckbox = React.forwardRef( ...@@ -590,8 +592,8 @@ const IndeterminateCheckbox = React.forwardRef(
) )
// Our table component // Our table component
function Table({ columns, data, defaultheader, optionalheader, tablename, defaultSortColumn,defaultpagesize }) { function Table({ columns, data, defaultheader, optionalheader, tablename, defaultSortColumn, defaultpagesize, columnOrders, showAction }) {
const filterTypes = React.useMemo( const filterTypes = React.useMemo(
() => ({ () => ({
// Add a new fuzzyTextFilterFn filter type. // Add a new fuzzyTextFilterFn filter type.
...@@ -603,8 +605,8 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul ...@@ -603,8 +605,8 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul
const rowValue = row.values[id] const rowValue = row.values[id]
return rowValue !== undefined return rowValue !== undefined
? String(rowValue) ? String(rowValue)
.toLowerCase() .toLowerCase()
.startsWith(String(filterValue).toLowerCase()) .startsWith(String(filterValue).toLowerCase())
: true : true
}) })
}, },
...@@ -613,73 +615,86 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul ...@@ -613,73 +615,86 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul
) )
const defaultColumn = React.useMemo( const defaultColumn = React.useMemo(
() => ({ () => ({
// Let's set up our default Filter UI // Let's set up our default Filter UI
Filter: DefaultColumnFilter, Filter: DefaultColumnFilter,
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
setAllFilters,
allColumns,
getToggleHideAllColumnsProps,
state,
page,
preGlobalFilteredRows,
setGlobalFilter,
setHiddenColumns,
gotoPage,
setPageSize,
selectedFlatRows,
exportData,
} = useTable(
{
columns,
data,
defaultColumn,
filterTypes,
initialState: { pageIndex: 0,
pageSize: (defaultpagesize && defaultpagesize>0)?defaultpagesize:10,
sortBy: defaultSortColumn },
getExportFileBlob,
},
useFilters,
useGlobalFilter,
useSortBy,
usePagination,
useRowSelect,
useExportData
);
React.useEffect(() => {
setHiddenColumns(
columns.filter(column => !column.isVisible).map(column => column.accessor)
);
}, [setHiddenColumns, columns]);
let op = useRef(null); }),
[]
)
const [currentpage, setcurrentPage] = React.useState(0); const {
const [currentrows, setcurrentRows] = React.useState(defaultpagesize); getTableProps,
const [custompagevalue,setcustompagevalue] = React.useState(); getTableBodyProps,
headerGroups,
rows,
prepareRow,
setAllFilters,
allColumns,
getToggleHideAllColumnsProps,
state,
page,
preGlobalFilteredRows,
setGlobalFilter,
setHiddenColumns,
gotoPage,
setPageSize,
selectedFlatRows,
setColumnOrder,
exportData,
} = useTable(
{
columns,
data,
defaultColumn,
filterTypes,
initialState: {
pageIndex: 0,
pageSize: (defaultpagesize && defaultpagesize > 0) ? defaultpagesize : 10,
sortBy: defaultSortColumn
},
getExportFileBlob,
},
useFilters,
useGlobalFilter,
useSortBy,
usePagination,
useRowSelect,
useColumnOrder,
useExportData
);
React.useEffect(() => {
setHiddenColumns(
columns.filter(column => column.isVisible).map(column => column.accessor)
);
// console.log('columns List', visibleColumns.map((d) => d.id));
if (columnOrders && columnOrders.length) {
if (showAction === 'true') {
setColumnOrder(['Select', 'Action', ...columnOrders]);
} else {
setColumnOrder(['Select', ...columnOrders]);
}
}
}, [setHiddenColumns, columns]);
let op = useRef(null);
const [currentpage, setcurrentPage] = React.useState(0);
const [currentrows, setcurrentRows] = React.useState(defaultpagesize);
const [custompagevalue, setcustompagevalue] = React.useState();
const onPagination = (e) => { const onPagination = (e) => {
gotoPage(e.page); gotoPage(e.page);
setcurrentPage(e.first); setcurrentPage(e.first);
setcurrentRows(e.rows); setcurrentRows(e.rows);
setPageSize(e.rows) setPageSize(e.rows)
if([10,25,50,100].includes(e.rows)){ if ([10, 25, 50, 100].includes(e.rows)) {
setcustompagevalue(); setcustompagevalue();
} }
}; };
const onCustomPage = (e) => { const onCustomPage = (e) => {
if(typeof custompagevalue === 'undefined' || custompagevalue == null) return; if (typeof custompagevalue === 'undefined' || custompagevalue == null) return;
gotoPage(0); gotoPage(0);
setcurrentPage(0); setcurrentPage(0);
setcurrentRows(custompagevalue); setcurrentRows(custompagevalue);
...@@ -689,7 +704,7 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul ...@@ -689,7 +704,7 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul
const onChangeCustompagevalue = (e) => { const onChangeCustompagevalue = (e) => {
setcustompagevalue(e.target.value); setcustompagevalue(e.target.value);
} }
const onShowAllPage = (e) => { const onShowAllPage = (e) => {
gotoPage(e.page); gotoPage(e.page);
setcurrentPage(e.first); setcurrentPage(e.first);
...@@ -698,16 +713,16 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul ...@@ -698,16 +713,16 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul
setcustompagevalue(); setcustompagevalue();
}; };
const onToggleChange = (e) =>{ const onToggleChange = (e) => {
let lsToggleColumns = []; let lsToggleColumns = [];
allColumns.forEach( acolumn =>{ allColumns.forEach(acolumn => {
let jsonobj = {}; let jsonobj = {};
let visible = (acolumn.Header === e.target.id) ? ((acolumn.isVisible)?false:true) :acolumn.isVisible let visible = (acolumn.Header === e.target.id) ? ((acolumn.isVisible) ? false : true) : acolumn.isVisible
jsonobj['Header'] = acolumn.Header; jsonobj['Header'] = acolumn.Header;
jsonobj['isVisible'] = visible; jsonobj['isVisible'] = visible;
lsToggleColumns.push(jsonobj) lsToggleColumns.push(jsonobj)
}) })
localStorage.setItem(tablename,JSON.stringify(lsToggleColumns)) localStorage.setItem(tablename, JSON.stringify(lsToggleColumns))
} }
filteredData = _.map(rows, 'values'); filteredData = _.map(rows, 'values');
...@@ -716,75 +731,75 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul ...@@ -716,75 +731,75 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul
} }
/* Select only rows than can be selected. This is required when ALL is selected */ /* Select only rows than can be selected. This is required when ALL is selected */
selectedRows = _.filter(selectedFlatRows, selectedRow => { return (selectedRow.original.canSelect===undefined || selectedRow.original.canSelect)}); selectedRows = _.filter(selectedFlatRows, selectedRow => { return (selectedRow.original.canSelect === undefined || selectedRow.original.canSelect) });
/* Take only the original values passed to the component */ /* Take only the original values passed to the component */
selectedRows = _.map(selectedRows, 'original'); selectedRows = _.map(selectedRows, 'original');
/* Callback the parent function if available to pass the selected records on selection */ /* Callback the parent function if available to pass the selected records on selection */
if (parentCBonSelection) { if (parentCBonSelection) {
parentCBonSelection(selectedRows) parentCBonSelection(selectedRows)
} }
return ( return (
<> <>
<div style={{display: 'flex', justifyContent: 'space-between'}}> <div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div id="block_container" > <div id="block_container" >
{ allowColumnSelection && {allowColumnSelection &&
<div style={{textAlign:'left', marginRight:'30px'}}> <div style={{ textAlign: 'left', marginRight: '30px' }}>
<i className="fa fa-columns col-filter-btn" label="Toggle Columns" onClick={(e) => op.current.toggle(e)} /> <i className="fa fa-columns col-filter-btn" label="Toggle Columns" onClick={(e) => op.current.toggle(e)} />
{showColumnFilter && {showColumnFilter &&
<div style={{position:"relative",top: "-25px",marginLeft: "50px",color: "#005b9f"}} onClick={() => setAllFilters([])} > <div style={{ position: "relative", top: "-25px", marginLeft: "50px", color: "#005b9f" }} onClick={() => setAllFilters([])} >
<i class="fas fa-sync-alt" title="Clear All Filters"></i></div>} <i class="fas fa-sync-alt" title="Clear All Filters"></i></div>}
<OverlayPanel ref={op} id="overlay_panel" showCloseIcon={false} > <OverlayPanel ref={op} id="overlay_panel" showCloseIcon={false} >
<div> <div>
<div style={{textAlign: 'center'}}> <div style={{ textAlign: 'center' }}>
<label>Select column(s) to view</label> <label>Select column(s) to view</label>
</div> </div>
<div style={{float: 'left', backgroundColor: '#d1cdd936', width: '250px', height: '400px', overflow: 'auto', marginBottom:'10px', padding:'5px'}}> <div style={{ float: 'left', backgroundColor: '#d1cdd936', width: '250px', height: '400px', overflow: 'auto', marginBottom: '10px', padding: '5px' }}>
<div id="tagleid" > <div id="tagleid" >
<div > <div >
<div style={{marginBottom:'5px'}}> <div style={{ marginBottom: '5px' }}>
<IndeterminateCheckbox {...getToggleHideAllColumnsProps()} /> Select All <IndeterminateCheckbox {...getToggleHideAllColumnsProps()} /> Select All
</div> </div>
{allColumns.map(column => ( {allColumns.map(column => (
<div key={column.id} style={{'display':column.id !== 'actionpath'?'block':'none'}}> <div key={column.id} style={{ 'display': column.id !== 'actionpath' ? 'block' : 'none' }}>
<input type="checkbox" {...column.getToggleHiddenProps()} <input type="checkbox" {...column.getToggleHiddenProps()}
id={(defaultheader[column.id])?defaultheader[column.id]:(optionalheader[column.id]?optionalheader[column.id]:column.id)} id={(defaultheader[column.id]) ? defaultheader[column.id] : (optionalheader[column.id] ? optionalheader[column.id] : column.id)}
onClick={onToggleChange} onClick={onToggleChange}
/> { /> {
(defaultheader[column.id]) ? defaultheader[column.id] : (optionalheader[column.id] ? optionalheader[column.id] : column.id)} (defaultheader[column.id]) ? defaultheader[column.id] : (optionalheader[column.id] ? optionalheader[column.id] : column.id)}
</div>
))}
<br />
</div> </div>
</div> ))}
<br />
</div> </div>
</div> </div>
</OverlayPanel> </div>
</div> </div>
} </OverlayPanel>
<div style={{textAlign:'right'}}> </div>
{tbldata.length>0 && !isunittest && showGlobalFilter && }
<div style={{ textAlign: 'right' }}>
{tbldata.length > 0 && !isunittest && showGlobalFilter &&
<GlobalFilter <GlobalFilter
preGlobalFilteredRows={preGlobalFilteredRows} preGlobalFilteredRows={preGlobalFilteredRows}
globalFilter={state.globalFilter} globalFilter={state.globalFilter}
setGlobalFilter={setGlobalFilter} setGlobalFilter={setGlobalFilter}
/> />
} }
</div> </div>
{ showTopTotal && filteredData.length === data.length && {showTopTotal && filteredData.length === data.length &&
<div className="total_records_top_label"> <label >Total records ({data.length})</label></div> <div className="total_records_top_label"> <label >Total records ({data.length})</label></div>
} }
{ showTopTotal && filteredData.length < data.length && {showTopTotal && filteredData.length < data.length &&
<div className="total_records_top_label" ><label >Filtered {filteredData.length} from {data.length}</label></div>} <div className="total_records_top_label" ><label >Filtered {filteredData.length} from {data.length}</label></div>}
</div> </div>
{showCSV && {showCSV &&
<div className="total_records_top_label" style={{marginTop: '20px'}} > <div className="total_records_top_label" style={{ marginTop: '20px' }} >
<a href="#" onClick={() => {exportData("csv", false);}} title="Download CSV" style={{verticalAlign: 'middle'}}> <a href="#" onClick={() => { exportData("csv", false); }} title="Download CSV" style={{ verticalAlign: 'middle' }}>
<i class="fas fa-file-csv" style={{color: 'green', fontSize: '20px'}} ></i> <i class="fas fa-file-csv" style={{ color: 'green', fontSize: '20px' }} ></i>
</a> </a>
</div> </div>
/* /*
...@@ -794,80 +809,80 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul ...@@ -794,80 +809,80 @@ function Table({ columns, data, defaultheader, optionalheader, tablename, defaul
</a> </a>
</div> */ </div> */
} }
</div> </div>
<div className="tmss-table table_container"> <div className="tmss-table table_container">
<table {...getTableProps()} data-testid="viewtable" className="viewtable" > <table {...getTableProps()} data-testid="viewtable" className="viewtable" >
<thead> <thead>
{headerGroups.map(headerGroup => ( {headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}> <tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => ( {headerGroup.headers.map(column => (
<th> <th>
<div {...column.getHeaderProps(column.getSortByToggleProps())}> <div {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.Header !== 'actionpath' && column.render('Header')} {column.Header !== 'actionpath' && column.render('Header')}
{column.Header !== 'Action'? {column.Header !== 'Action' ?
column.isSorted ? (column.isSortedDesc ? <i className="pi pi-sort-down" aria-hidden="true"></i> : <i className="pi pi-sort-up" aria-hidden="true"></i>) : "" column.isSorted ? (column.isSortedDesc ? <i className="pi pi-sort-down" aria-hidden="true"></i> : <i className="pi pi-sort-up" aria-hidden="true"></i>) : ""
: "" : ""
} }
</div> </div>
{/* Render the columns filter UI */} {/* Render the columns filter UI */}
{column.Header !== 'actionpath' && {column.Header !== 'actionpath' &&
<div className={columnclassname[0][column.Header]} > <div className={columnclassname[0][column.Header]} >
{column.canFilter && column.Header !== 'Action' ? column.render('Filter') : null} {column.canFilter && column.Header !== 'Action' ? column.render('Filter') : null}
</div> </div>
} }
</th> </th>
))} ))}
</tr> </tr>
))} ))}
</thead> </thead>
<tbody {...getTableBodyProps()}> <tbody {...getTableBodyProps()}>
{page.map((row, i) => { {page.map((row, i) => {
prepareRow(row) prepareRow(row)
return ( return (
<tr {...row.getRowProps()}> <tr {...row.getRowProps()}>
{row.cells.map(cell => { {row.cells.map(cell => {
if(cell.column.id !== 'actionpath'){ if (cell.column.id !== 'actionpath') {
return <td {...cell.getCellProps()}> return <td {...cell.getCellProps()}>
{(cell.row.original.links || []).includes(cell.column.id) ? <Link to={cell.row.original.linksURL[cell.column.id]}>{cell.render('Cell')}</Link> : cell.render('Cell')} {(cell.row.original.links || []).includes(cell.column.id) ? <Link to={cell.row.original.linksURL[cell.column.id]}>{cell.render('Cell')}</Link> : cell.render('Cell')}
</td> </td>
} }
else { else {
return ""; return "";
} }
} }
)} )}
</tr> </tr>
); );
})} })}
</tbody> </tbody>
</table> </table>
</div>
<div className="pagination p-grid" >
{filteredData.length === data.length &&
<div className="total_records_bottom_label" ><label >Total records ({data.length})</label></div>
}
{filteredData.length < data.length &&
<div className="total_records_bottom_label" ><label >Filtered {filteredData.length} from {data.length}</label></div>
}
<div>
<Paginator rowsPerPageOptions={[10, 25, 50, 100]} first={currentpage} rows={currentrows} totalRecords={rows.length} onPageChange={onPagination}></Paginator>
</div>
<div>
<InputNumber id="custompage" value={custompagevalue} onChange={onChangeCustompagevalue}
min={0} style={{ width: '100px' }} />
<label >Records/Page</label>
<Button onClick={onCustomPage}> Show </Button>
<Button onClick={onShowAllPage} style={{ marginLeft: "1em" }}> Show All </Button>
</div> </div>
<div className="pagination p-grid" >
{filteredData.length === data.length &&
<div className="total_records_bottom_label" ><label >Total records ({data.length})</label></div>
}
{filteredData.length < data.length &&
<div className="total_records_bottom_label" ><label >Filtered {filteredData.length} from {data.length}</label></div>
}
<div>
<Paginator rowsPerPageOptions={[10,25,50,100]} first={currentpage} rows={currentrows} totalRecords={rows.length} onPageChange={onPagination}></Paginator>
</div>
<div>
<InputNumber id="custompage" value={custompagevalue} onChange ={onChangeCustompagevalue}
min={0} style={{width:'100px'}} />
<label >Records/Page</label>
<Button onClick={onCustomPage}> Show </Button>
<Button onClick={onShowAllPage} style={{marginLeft: "1em"}}> Show All </Button>
</div>
</div> </div>
</> </>
) )
} }
// Define a custom filter filter function! // Define a custom filter filter function!
function filterGreaterThan(rows, id, filterValue) { function filterGreaterThan(rows, id, filterValue) {
...@@ -884,90 +899,94 @@ function filterGreaterThan(rows, id, filterValue) { ...@@ -884,90 +899,94 @@ function filterGreaterThan(rows, id, filterValue) {
filterGreaterThan.autoRemove = val => typeof val !== 'number' filterGreaterThan.autoRemove = val => typeof val !== 'number'
function ViewTable(props) { function ViewTable(props) {
const history = useHistory(); const history = useHistory();
// Data to show in table // Data to show in table
tbldata = props.data; tbldata = props.data;
showCSV= (props.showCSV)?props.showCSV:false; showCSV = (props.showCSV) ? props.showCSV : false;
parentCallbackFunction = props.filterCallback; parentCallbackFunction = props.filterCallback;
parentCBonSelection = props.onRowSelection; parentCBonSelection = props.onRowSelection;
isunittest = props.unittest; isunittest = props.unittest;
columnclassname = props.columnclassname; columnclassname = props.columnclassname;
showTopTotal = props.showTopTotal===undefined?true:props.showTopTotal; showTopTotal = props.showTopTotal === undefined ? true : props.showTopTotal;
showGlobalFilter = props.showGlobalFilter===undefined?true:props.showGlobalFilter; showGlobalFilter = props.showGlobalFilter === undefined ? true : props.showGlobalFilter;
showColumnFilter = props.showColumnFilter===undefined?true:props.showColumnFilter; showColumnFilter = props.showColumnFilter === undefined ? true : props.showColumnFilter;
allowColumnSelection = props.allowColumnSelection===undefined?true:props.allowColumnSelection; allowColumnSelection = props.allowColumnSelection === undefined ? true : props.allowColumnSelection;
allowRowSelection = props.allowRowSelection===undefined?false:props.allowRowSelection; allowRowSelection = props.allowRowSelection === undefined ? false : props.allowRowSelection;
// Default Header to show in table and other columns header will not show until user action on UI // Default Header to show in table and other columns header will not show until user action on UI
let defaultheader = props.defaultcolumns; let defaultheader = props.defaultcolumns;
let optionalheader = props.optionalcolumns; let optionalheader = props.optionalcolumns;
let defaultSortColumn = props.defaultSortColumn; let defaultSortColumn = props.defaultSortColumn;
let tablename = (props.tablename)?props.tablename:window.location.pathname; let tablename = (props.tablename) ? props.tablename : window.location.pathname;
if(!defaultSortColumn){ if (!defaultSortColumn) {
defaultSortColumn =[{}]; defaultSortColumn = [{}];
} }
let defaultpagesize = (typeof props.defaultpagesize === 'undefined' || props.defaultpagesize == null)?10:props.defaultpagesize; let defaultpagesize = (typeof props.defaultpagesize === 'undefined' || props.defaultpagesize == null) ? 10 : props.defaultpagesize;
let columns = []; let columns = [];
let defaultdataheader = Object.keys(defaultheader[0]); let defaultdataheader = Object.keys(defaultheader[0]);
let optionaldataheader = Object.keys(optionalheader[0]); let optionaldataheader = Object.keys(optionalheader[0]);
/* If allowRowSelection property is true for the component, add checkbox column as 1st column. /* If allowRowSelection property is true for the component, add checkbox column as 1st column.
If the record has property to select, enable the checkbox */ If the record has property to select, enable the checkbox */
if (allowRowSelection) { if (allowRowSelection) {
columns.push({ columns.push({
Header: ({ getToggleAllRowsSelectedProps }) => { return ( Header: ({ getToggleAllRowsSelectedProps }) => {
return (
<div> <div>
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} style={{width:'15px', height:'15px'}}/> <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} style={{ width: '15px', height: '15px' }} />
</div> </div>
)}, )
id:'Select', },
accessor: props.keyaccessor, id: 'Select',
Cell: ({ row }) => { return ( accessor: props.keyaccessor,
Cell: ({ row }) => {
return (
<div> <div>
{(row.original.canSelect===undefined || row.original.canSelect) && {(row.original.canSelect === undefined || row.original.canSelect) &&
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} style={{width:'15px', height:'15px'}}/> <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} style={{ width: '15px', height: '15px' }} />
} }
{row.original.canSelect===false && {row.original.canSelect === false &&
<input type="checkbox" checked={false} disabled style={{width:'15px', height:'15px'}}></input> <input type="checkbox" checked={false} disabled style={{ width: '15px', height: '15px' }}></input>
} }
</div> </div>
)}, )
disableFilters: true, },
disableSortBy: true, disableFilters: true,
isVisible: defaultdataheader.includes(props.keyaccessor), disableSortBy: true,
}); isVisible: defaultdataheader.includes(props.keyaccessor),
} });
}
if(props.showaction === 'true') {
columns.push({ if (props.showaction === 'true') {
Header: 'Action', columns.push({
id:'Action', Header: 'Action',
accessor: props.keyaccessor, id: 'Action',
Cell: props => <button className='p-link' onClick={navigateTo(props)} ><i className="fa fa-eye" style={{cursor: 'pointer'}}></i></button>, accessor: props.keyaccessor,
disableFilters: true, Cell: props => <button className='p-link' onClick={navigateTo(props)} ><i className="fa fa-eye" style={{ cursor: 'pointer' }}></i></button>,
disableSortBy: true, disableFilters: true,
isVisible: defaultdataheader.includes(props.keyaccessor), disableSortBy: true,
}) isVisible: defaultdataheader.includes(props.keyaccessor),
} })
}
const navigateTo = (props) => () => {
if(props.cell.row.values['actionpath']){ const navigateTo = (props) => () => {
return history.push({ if (props.cell.row.values['actionpath']) {
pathname: props.cell.row.values['actionpath'], return history.push({
state: { pathname: props.cell.row.values['actionpath'],
"id": props.value, state: {
} "id": props.value,
}) }
} })
// Object.entries(props.paths[0]).map(([key,value]) =>{})
} }
// Object.entries(props.paths[0]).map(([key,value]) =>{})
}
//Default Columns //Default Columns
defaultdataheader.forEach(header => { defaultdataheader.forEach(header => {
const isString = typeof defaultheader[0][header] === 'string'; const isString = typeof defaultheader[0][header] === 'string';
const filterFn = (showColumnFilter?(isString ? DefaultColumnFilter : (filterTypes[defaultheader[0][header].filter].fn ? filterTypes[defaultheader[0][header].filter].fn : DefaultColumnFilter)):""); const filterFn = (showColumnFilter ? (isString ? DefaultColumnFilter : (filterTypes[defaultheader[0][header].filter].fn ? filterTypes[defaultheader[0][header].filter].fn : DefaultColumnFilter)) : "");
const filtertype = (showColumnFilter?(!isString && filterTypes[defaultheader[0][header].filter].type) ? filterTypes[defaultheader[0][header].filter].type : 'fuzzyText':""); const filtertype = (showColumnFilter ? (!isString && filterTypes[defaultheader[0][header].filter].type) ? filterTypes[defaultheader[0][header].filter].type : 'fuzzyText' : "");
columns.push({ columns.push({
Header: isString ? defaultheader[0][header] : defaultheader[0][header].name, Header: isString ? defaultheader[0][header] : defaultheader[0][header].name,
id: isString ? defaultheader[0][header] : defaultheader[0][header].name, id: isString ? defaultheader[0][header] : defaultheader[0][header].name,
...@@ -979,72 +998,72 @@ function ViewTable(props) { ...@@ -979,72 +998,72 @@ function ViewTable(props) {
// Filter: (showColumnFilter?(isString ? DefaultColumnFilter : (filterTypes[defaultheader[0][header].filter] ? filterTypes[defaultheader[0][header].filter] : DefaultColumnFilter)):""), // Filter: (showColumnFilter?(isString ? DefaultColumnFilter : (filterTypes[defaultheader[0][header].filter] ? filterTypes[defaultheader[0][header].filter] : DefaultColumnFilter)):""),
isVisible: true, isVisible: true,
Cell: props => <div> {updatedCellvalue(header, props.value)} </div>, Cell: props => <div> {updatedCellvalue(header, props.value)} </div>,
}) })
}) })
//Optional Columns //Optional Columns
optionaldataheader.forEach(header => { optionaldataheader.forEach(header => {
const isString = typeof optionalheader[0][header] === 'string'; const isString = typeof optionalheader[0][header] === 'string';
const filterFn = (showColumnFilter?(isString ? DefaultColumnFilter : (filterTypes[optionalheader[0][header].filter].fn ? filterTypes[optionalheader[0][header].filter].fn : DefaultColumnFilter)):""); const filterFn = (showColumnFilter ? (isString ? DefaultColumnFilter : (filterTypes[optionalheader[0][header].filter].fn ? filterTypes[optionalheader[0][header].filter].fn : DefaultColumnFilter)) : "");
const filtertype = (showColumnFilter?(!isString && filterTypes[optionalheader[0][header].filter].type) ? filterTypes[optionalheader[0][header].filter].type : 'fuzzyText':""); const filtertype = (showColumnFilter ? (!isString && filterTypes[optionalheader[0][header].filter].type) ? filterTypes[optionalheader[0][header].filter].type : 'fuzzyText' : "");
columns.push({ columns.push({
Header: isString ? optionalheader[0][header] : optionalheader[0][header].name, Header: isString ? optionalheader[0][header] : optionalheader[0][header].name,
id: isString ? header : optionalheader[0][header].name, id: isString ? header : optionalheader[0][header].name,
accessor: isString ? header : optionalheader[0][header].name, accessor: isString ? header : optionalheader[0][header].name,
filter: filtertype, filter: filtertype,
Filter: filterFn, Filter: filterFn,
isVisible: false, isVisible: false,
Cell: props => <div> {updatedCellvalue(header, props.value)} </div>, Cell: props => <div> {updatedCellvalue(header, props.value)} </div>,
})
});
let togglecolumns = localStorage.getItem(tablename);
if (togglecolumns) {
togglecolumns = JSON.parse(togglecolumns)
columns.forEach(column => {
togglecolumns.filter(tcol => {
column.isVisible = (tcol.Header === column.Header) ? tcol.isVisible : column.isVisible;
return tcol;
}) })
}); })
}
let togglecolumns = localStorage.getItem(tablename);
if(togglecolumns){
togglecolumns = JSON.parse(togglecolumns)
columns.forEach(column =>{
togglecolumns.filter(tcol => {
column.isVisible = (tcol.Header === column.Header)?tcol.isVisible:column.isVisible;
return tcol;
})
})
}
function updatedCellvalue(key, value){ function updatedCellvalue(key, value) {
try{ try {
if(key === 'blueprint_draft' && _.includes(value,'/task_draft/')){ if (key === 'blueprint_draft' && _.includes(value, '/task_draft/')) {
// 'task_draft/' -> len = 12 // 'task_draft/' -> len = 12
var taskid = _.replace(value.substring((value.indexOf('/task_draft/')+12), value.length),'/',''); var taskid = _.replace(value.substring((value.indexOf('/task_draft/') + 12), value.length), '/', '');
return <a href={'/task/view/draft/'+taskid}>{' '+taskid+' '}</a> return <a href={'/task/view/draft/' + taskid}>{' ' + taskid + ' '}</a>
}else if(key === 'blueprint_draft'){ } else if (key === 'blueprint_draft') {
var retval= []; var retval = [];
value.forEach((link, index) =>{ value.forEach((link, index) => {
// 'task_blueprint/' -> len = 16 // 'task_blueprint/' -> len = 16
if(_.includes(link,'/task_blueprint/')){ if (_.includes(link, '/task_blueprint/')) {
var bpid = _.replace(link.substring((link.indexOf('/task_blueprint/')+16), link.length),'/',''); var bpid = _.replace(link.substring((link.indexOf('/task_blueprint/') + 16), link.length), '/', '');
retval.push( <a href={'/task/view/blueprint/'+bpid} key={bpid+index} >{' '+bpid+' '}</a> ) retval.push(<a href={'/task/view/blueprint/' + bpid} key={bpid + index} >{' ' + bpid + ' '}</a>)
} }
}) })
return retval; return retval;
}else if(typeof value == "boolean"){ } else if (typeof value == "boolean") {
return value.toString(); return value.toString();
} else if(typeof value == "string"){ } else if (typeof value == "string") {
const dateval = moment(value, moment.ISO_8601).format("YYYY-MMM-DD HH:mm:ss"); const dateval = moment(value, moment.ISO_8601).format("YYYY-MMM-DD HH:mm:ss");
if(dateval !== 'Invalid date'){ if (dateval !== 'Invalid date') {
return dateval; return dateval;
} }
}
}catch(err){
console.error('Error',err)
} }
return value; } catch (err) {
console.error('Error', err)
} }
return value;
}
return ( return (
<div> <div>
<Table columns={columns} data={tbldata} defaultheader={defaultheader[0]} optionalheader={optionalheader[0]} <Table columns={columns} data={tbldata} defaultheader={defaultheader[0]} optionalheader={optionalheader[0]} showAction={props.showaction}
defaultSortColumn={defaultSortColumn} tablename={tablename} defaultpagesize={defaultpagesize}/> defaultSortColumn={defaultSortColumn} tablename={tablename} defaultpagesize={defaultpagesize} columnOrders={props.columnOrders} />
</div> </div>
) )
} }
export default ViewTable export default ViewTable
\ No newline at end of file
...@@ -8,7 +8,6 @@ import _ from 'lodash'; ...@@ -8,7 +8,6 @@ import _ from 'lodash';
import ScheduleService from '../../services/schedule.service'; import ScheduleService from '../../services/schedule.service';
class SchedulingUnitList extends Component{ class SchedulingUnitList extends Component{
constructor(props){ constructor(props){
super(props); super(props);
this.defaultcolumns = { this.defaultcolumns = {
...@@ -34,6 +33,32 @@ class SchedulingUnitList extends Component{ ...@@ -34,6 +33,32 @@ class SchedulingUnitList extends Component{
this.STATUS_BEFORE_SCHEDULED = ['defining', 'defined', 'schedulable']; // Statuses before scheduled to get station_group this.STATUS_BEFORE_SCHEDULED = ['defining', 'defined', 'schedulable']; // Statuses before scheduled to get station_group
this.mainStationGroups = {}; this.mainStationGroups = {};
this.state = { this.state = {
columnOrders: [
"Status",
"Type",
"id",
"Template ID",
"template_description",
"priority",
"Project",
"suSet",
"Name",
"description",
"Start Time",
"End time",
"Duration (HH:mm:ss)",
"station_group",
"task_content",
"target_observation_sap",
"target0angle1",
"target0angle2",
"Target 1 - Reference Frame",
"target1angle1",
"target1angle2",
"Target 2 - Reference Frame",
"created_at",
"updated_at",
],
scheduleunit: [], scheduleunit: [],
paths: [{ paths: [{
"View": "/schedulingunit/view", "View": "/schedulingunit/view",
...@@ -42,7 +67,7 @@ class SchedulingUnitList extends Component{ ...@@ -42,7 +67,7 @@ class SchedulingUnitList extends Component{
defaultcolumns: [this.defaultcolumns], defaultcolumns: [this.defaultcolumns],
optionalcolumns: [{ optionalcolumns: [{
actionpath:"actionpath", actionpath:"actionpath",
id:"Scheduling unit ID", id:"Linked Blueprint/Draft ID",
template_description: "Template Description", template_description: "Template Description",
priority:"Priority", priority:"Priority",
suSet:"Scheduling set", suSet:"Scheduling set",
...@@ -58,6 +83,7 @@ class SchedulingUnitList extends Component{ ...@@ -58,6 +83,7 @@ class SchedulingUnitList extends Component{
"Project":"filter-input-50", "Project":"filter-input-50",
"Priority":"filter-input-50", "Priority":"filter-input-50",
"Duration (HH:mm:ss)":"filter-input-75", "Duration (HH:mm:ss)":"filter-input-75",
"Linked Blueprint/Draft ID":"filter-input-50",
"Type": "filter-input-75", "Type": "filter-input-75",
"Status":"filter-input-100", "Status":"filter-input-100",
"Scheduling unit ID":"filter-input-50", "Scheduling unit ID":"filter-input-50",
...@@ -67,6 +93,7 @@ class SchedulingUnitList extends Component{ ...@@ -67,6 +93,7 @@ class SchedulingUnitList extends Component{
}], }],
defaultSortColumn: [{id: "Name", desc: false}], defaultSortColumn: [{id: "Name", desc: false}],
} }
this.onRowSelection = this.onRowSelection.bind(this); this.onRowSelection = this.onRowSelection.bind(this);
this.reloadData = this.reloadData.bind(this); this.reloadData = this.reloadData.bind(this);
} }
...@@ -190,6 +217,11 @@ class SchedulingUnitList extends Component{ ...@@ -190,6 +217,11 @@ class SchedulingUnitList extends Component{
// blueP.linksURL = { // blueP.linksURL = {
// 'Project': `/project/view/${project.name}` // 'Project': `/project/view/${project.name}`
// } // }
blueP.links = ['Project', 'id'];
blueP.linksURL = {
'Project': `/project/view/${project.name}`,
'id': `/schedulingunit/view/blueprint/${blueP.id}`
}
return blueP; return blueP;
}); });
output.push(...blueprintdata); output.push(...blueprintdata);
...@@ -205,6 +237,11 @@ class SchedulingUnitList extends Component{ ...@@ -205,6 +237,11 @@ class SchedulingUnitList extends Component{
// scheduleunit.linksURL = { // scheduleunit.linksURL = {
// 'Project': `/project/view/${project.name}` // 'Project': `/project/view/${project.name}`
// } // }
scheduleunit.links = ['Project', 'id'];
scheduleunit.linksURL = {
'Project': `/project/view/${project.name}`,
'id': `/schedulingunit/view/draft/${scheduleunit.id}`
}
output.push(scheduleunit); output.push(scheduleunit);
} }
// const defaultColumns = this.defaultcolumns; // const defaultColumns = this.defaultcolumns;
...@@ -298,6 +335,7 @@ class SchedulingUnitList extends Component{ ...@@ -298,6 +335,7 @@ class SchedulingUnitList extends Component{
tablename="scheduleunit_list" tablename="scheduleunit_list"
allowRowSelection={this.props.allowRowSelection} allowRowSelection={this.props.allowRowSelection}
onRowSelection = {this.onRowSelection} onRowSelection = {this.onRowSelection}
columnOrders={this.state.columnOrders}
/> />
:<div>No scheduling unit found </div> :<div>No scheduling unit found </div>
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment