From bd597e7e0b5909160bc6d87336362007ccc5a9b0 Mon Sep 17 00:00:00 2001 From: MVarshini Date: Fri, 29 Nov 2024 11:07:27 +0530 Subject: [PATCH] Sorting --- backend/app/api/v1/commons/ocp.py | 10 +- backend/app/api/v1/commons/quay.py | 16 +- backend/app/api/v1/commons/telco.py | 2 + backend/app/api/v1/endpoints/ocp/ocpJobs.py | 71 +++++--- backend/app/api/v1/endpoints/quay/quayJobs.py | 71 +++++--- backend/app/services/search.py | 157 +++++++++++++----- backend/app/services/splunk.py | 2 + frontend/src/actions/commonActions.js | 67 +------- frontend/src/actions/homeActions.js | 2 - frontend/src/actions/ocpActions.js | 2 - frontend/src/actions/sortingActions.js | 71 +++++++- frontend/src/actions/types.js | 2 + .../organisms/TableLayout/index.jsx | 11 +- .../src/components/templates/Home/index.jsx | 1 + .../src/components/templates/OCP/index.jsx | 1 + .../src/components/templates/Quay/index.jsx | 1 + .../src/components/templates/Telco/index.jsx | 1 + frontend/src/reducers/homeReducer.js | 1 + frontend/src/reducers/ocpReducer.js | 3 + frontend/src/reducers/quayReducer.js | 3 + frontend/src/reducers/telcoReducer.js | 1 + 21 files changed, 317 insertions(+), 179 deletions(-) diff --git a/backend/app/api/v1/commons/ocp.py b/backend/app/api/v1/commons/ocp.py index 651f9ff3..e7cb47c2 100644 --- a/backend/app/api/v1/commons/ocp.py +++ b/backend/app/api/v1/commons/ocp.py @@ -5,7 +5,12 @@ async def getData( - start_datetime: date, end_datetime: date, size: int, offset: int, configpath: str + start_datetime: date, + end_datetime: date, + size: int, + offset: int, + sort: str, + configpath: str, ): query = { "size": size, @@ -14,6 +19,9 @@ async def getData( "bool": {"filter": {"range": {"timestamp": {"format": "yyyy-MM-dd"}}}} }, } + if sort: + key, direction = sort.split(":") + query["sort"] = [{key: {"order": direction}}] es = ElasticService(configpath=configpath) response = await es.post( diff --git a/backend/app/api/v1/commons/quay.py b/backend/app/api/v1/commons/quay.py index 9ce874c4..03688a1e 100644 --- a/backend/app/api/v1/commons/quay.py +++ b/backend/app/api/v1/commons/quay.py @@ -4,15 +4,21 @@ from app.services.search import ElasticService -async def getData(start_datetime: date, end_datetime: date, size, offset, configpath: str): +async def getData( + start_datetime: date, end_datetime: date, size, offset, sort: str, configpath: str +): query = { "size": size, "from": offset, "query": { "bool": {"filter": {"range": {"timestamp": {"format": "yyyy-MM-dd"}}}} - } + }, } + if sort: + key, direction = sort.split(":") + query["sort"] = [{key: {"order": direction}}] + es = ElasticService(configpath=configpath) response = await es.post( query=query, @@ -21,7 +27,7 @@ async def getData(start_datetime: date, end_datetime: date, size, offset, config timestamp_field="timestamp", ) await es.close() - tasks = [item['_source'] for item in response['data']] + tasks = [item["_source"] for item in response["data"]] jobs = pd.json_normalize(tasks) if len(jobs) == 0: return jobs @@ -40,7 +46,7 @@ async def getData(start_datetime: date, end_datetime: date, size, offset, config jobs["build"] = jobs.apply(utils.getBuild, axis=1) jobs["shortVersion"] = jobs["ocpVersion"].str.slice(0, 4) - cleanJobs = jobs[jobs['platform'] != ""] + cleanJobs = jobs[jobs["platform"] != ""] jbs = cleanJobs - return ({'data':jbs, 'total': response['total']}) + return {"data": jbs, "total": response["total"]} diff --git a/backend/app/api/v1/commons/telco.py b/backend/app/api/v1/commons/telco.py index 77776c42..851a4a0e 100644 --- a/backend/app/api/v1/commons/telco.py +++ b/backend/app/api/v1/commons/telco.py @@ -38,6 +38,8 @@ async def getData( "earliest_time": "{}T00:00:00".format(start_datetime.strftime("%Y-%m-%d")), "latest_time": "{}T23:59:59".format(end_datetime.strftime("%Y-%m-%d")), "output_mode": "json", + "sort_dir": "asc", + "sort_key": "test_type", } searchList = " OR ".join( ['test_type="{}"'.format(test_type) for test_type in test_types] diff --git a/backend/app/api/v1/endpoints/ocp/ocpJobs.py b/backend/app/api/v1/endpoints/ocp/ocpJobs.py index 23d5d233..912b97a1 100644 --- a/backend/app/api/v1/endpoints/ocp/ocpJobs.py +++ b/backend/app/api/v1/endpoints/ocp/ocpJobs.py @@ -9,22 +9,34 @@ router = APIRouter() - -@router.get('/api/v1/ocp/jobs', - summary="Returns a job list", - description="Returns a list of jobs in the specified dates of requested size. \ +@router.get( + "/api/v1/ocp/jobs", + summary="Returns a job list", + description="Returns a list of jobs in the specified dates of requested size. \ If not dates are provided the API will default the values. \ `startDate`: will be set to the day of the request minus 5 days.\ `endDate`: will be set to the day of the request.", - responses={ - 200: ocp_200_response(), - 422: response_422(), - },) -async def jobs(start_date: date = Query(None, description="Start date for searching jobs, format: 'YYYY-MM-DD'", examples=["2020-11-10"]), - end_date: date = Query(None, description="End date for searching jobs, format: 'YYYY-MM-DD'", examples=["2020-11-15"]), - pretty: bool = Query(False, description="Output contet in pretty format."), - size: int = Query(None, description="Number of jobs to fetch"), - offset: int = Query(None, description="Offset Number to fetch jobs from")): + responses={ + 200: ocp_200_response(), + 422: response_422(), + }, +) +async def jobs( + start_date: date = Query( + None, + description="Start date for searching jobs, format: 'YYYY-MM-DD'", + examples=["2020-11-10"], + ), + end_date: date = Query( + None, + description="End date for searching jobs, format: 'YYYY-MM-DD'", + examples=["2020-11-15"], + ), + pretty: bool = Query(False, description="Output contet in pretty format."), + size: int = Query(None, description="Number of jobs to fetch"), + offset: int = Query(None, description="Offset Number to fetch jobs from"), + sort: str = Query(None, descption="To sort fields on specified direction"), +): if start_date is None: start_date = datetime.utcnow().date() start_date = start_date - timedelta(days=5) @@ -42,28 +54,33 @@ async def jobs(start_date: date = Query(None, description="Start date for search if not offset: offset = 0 - + if not size: size = 10000 offset = 0 - - results = await getData(start_date, end_date, size, offset, 'ocp.elasticsearch') - if 'data' in results and len(results['data']) >= 1: + if not sort: + sort = None + + results = await getData( + start_date, end_date, size, offset, sort, "ocp.elasticsearch" + ) + + if "data" in results and len(results["data"]) >= 1: response = { - 'startDate': start_date.__str__(), - 'endDate': end_date.__str__(), - 'results': results['data'].to_dict('records'), - 'total': results['total'], - 'offset': offset + size + "startDate": start_date.__str__(), + "endDate": end_date.__str__(), + "results": results["data"].to_dict("records"), + "total": results["total"], + "offset": offset + size, } else: response = { - 'startDate': start_date.__str__(), - 'endDate': end_date.__str__(), - 'results': [], - 'total': 0, - 'offset': 0 + "startDate": start_date.__str__(), + "endDate": end_date.__str__(), + "results": [], + "total": 0, + "offset": 0, } if pretty: diff --git a/backend/app/api/v1/endpoints/quay/quayJobs.py b/backend/app/api/v1/endpoints/quay/quayJobs.py index bded6d04..d0dd923f 100644 --- a/backend/app/api/v1/endpoints/quay/quayJobs.py +++ b/backend/app/api/v1/endpoints/quay/quayJobs.py @@ -9,22 +9,34 @@ router = APIRouter() - -@router.get('/api/v1/quay/jobs', - summary="Returns a job list", - description="Returns a list of jobs in the specified dates of requested size. \ +@router.get( + "/api/v1/quay/jobs", + summary="Returns a job list", + description="Returns a list of jobs in the specified dates of requested size. \ If not dates are provided the API will default the values. \ `startDate`: will be set to the day of the request minus 5 days.\ `endDate`: will be set to the day of the request.", - responses={ - 200: quay_200_response(), - 422: response_422(), - },) -async def jobs(start_date: date = Query(None, description="Start date for searching jobs, format: 'YYYY-MM-DD'", examples=["2020-11-10"]), - end_date: date = Query(None, description="End date for searching jobs, format: 'YYYY-MM-DD'", examples=["2020-11-15"]), - pretty: bool = Query(False, description="Output contet in pretty format."), - size: int = Query(None, description="Number of jobs to fetch"), - offset: int = Query(None, description="Offset Number to fetch jobs from")): + responses={ + 200: quay_200_response(), + 422: response_422(), + }, +) +async def jobs( + start_date: date = Query( + None, + description="Start date for searching jobs, format: 'YYYY-MM-DD'", + examples=["2020-11-10"], + ), + end_date: date = Query( + None, + description="End date for searching jobs, format: 'YYYY-MM-DD'", + examples=["2020-11-15"], + ), + pretty: bool = Query(False, description="Output contet in pretty format."), + size: int = Query(None, description="Number of jobs to fetch"), + offset: int = Query(None, description="Offset Number to fetch jobs from"), + sort: str = Query(None, descption="To sort fields on specified direction"), +): if start_date is None: start_date = datetime.utcnow().date() start_date = start_date - timedelta(days=5) @@ -42,28 +54,33 @@ async def jobs(start_date: date = Query(None, description="Start date for search if not offset: offset = 0 - + if not size: size = 10000 offset = 0 - - results = await getData(start_date, end_date, size, offset, 'quay.elasticsearch') - if 'data' in results and len(results['data']) >= 1: + if not sort: + sort = None + + results = await getData( + start_date, end_date, size, offset, sort, "quay.elasticsearch" + ) + + if "data" in results and len(results["data"]) >= 1: response = { - 'startDate': start_date.__str__(), - 'endDate': end_date.__str__(), - 'results': results['data'].to_dict('records'), - 'total': results['total'], - 'offset': offset + size + "startDate": start_date.__str__(), + "endDate": end_date.__str__(), + "results": results["data"].to_dict("records"), + "total": results["total"], + "offset": offset + size, } else: response = { - 'startDate': start_date.__str__(), - 'endDate': end_date.__str__(), - 'results': [], - 'total': 0, - 'offset': 0 + "startDate": start_date.__str__(), + "endDate": end_date.__str__(), + "results": [], + "total": 0, + "offset": 0, } if pretty: diff --git a/backend/app/services/search.py b/backend/app/services/search.py index 0541aa2a..71743259 100644 --- a/backend/app/services/search.py +++ b/backend/app/services/search.py @@ -9,6 +9,17 @@ class ElasticService: # todo add bulkhead pattern # todo add error message for unauthorized user + # Define the keywords for sorting. + DIRECTIONS = ("asc", "desc") + FIELDS = ( + "ciSystem", + "releaseStream", + "platform", + "workerNodesCount", + "masterNodesCount" "infraNodesCount", + "totalNodesCount", + ) + def __init__(self, configpath="", index=""): """Init method.""" cfg = config.get_config() @@ -43,7 +54,15 @@ def initialize_es(self, config, path, index): es = AsyncElasticsearch(url, verify_certs=False) return es, indice, index_prefix - async def post(self, query, indice=None, size=None, start_date=None, end_date=None, timestamp_field=None): + async def post( + self, + query, + indice=None, + size=None, + start_date=None, + end_date=None, + timestamp_field=None, + ): """Runs a query and returns the results""" if size == 0: """Handles aggregation queries logic""" @@ -72,7 +91,7 @@ async def post(self, query, indice=None, size=None, start_date=None, end_date=No today = datetime.today().date() seven_days_ago = today - timedelta(days=7) if start_date and start_date > seven_days_ago: - previous_results = {} + previous_results = {} else: new_end_date = ( min(end_date, seven_days_ago) @@ -90,14 +109,22 @@ async def post(self, query, indice=None, size=None, start_date=None, end_date=No response = await self.prev_es.search( index=self.prev_index + "*", body=jsonable_encoder(query), - size=size) - previous_results = {"data":response['hits']['hits'], "total":response['hits']["total"]["value"]} + size=size, + ) + previous_results = { + "data": response["hits"]["hits"], + "total": response["hits"]["total"]["value"], + } else: response = await self.prev_es.search( - index=self.prev_index+"*", + index=self.prev_index + "*", body=jsonable_encoder(query), - size=size) - previous_results = {"data":response['hits']['hits'], "total":response['hits']["total"]["value"]} + size=size, + ) + previous_results = { + "data": response["hits"]["hits"], + "total": response["hits"]["total"]["value"], + } # previous_results = await self.scan_indices(self.prev_es, self.prev_index, query, timestamp_field, start_date, new_end_date, size) if self.prev_es and self.new_es: self.new_index = self.new_index_prefix + ( @@ -124,29 +151,53 @@ async def post(self, query, indice=None, size=None, start_date=None, end_date=No response = await self.new_es.search( index=self.new_index + "*", body=jsonable_encoder(query), - size=size) - new_results = {"data":response['hits']['hits'],"total":response['hits']['total']['value']} + size=size, + ) + new_results = { + "data": response["hits"]["hits"], + "total": response["hits"]["total"]["value"], + } else: response = await self.new_es.search( - index=self.new_index+"*", + index=self.new_index + "*", body=jsonable_encoder(query), - size=size) - new_results = {"data":response['hits']['hits'],"total":response['hits']['total']['value']} + size=size, + ) + new_results = { + "data": response["hits"]["hits"], + "total": response["hits"]["total"]["value"], + } # new_results = await self.scan_indices(self.new_es, self.new_index, query, timestamp_field, new_start_date, end_date, size) - unique_data = await self.remove_duplicates(previous_results["data"] if("data" in previous_results) else [] + new_results["data"] if("data" in new_results) else[]) - totalVal = previous_results["total"] if("total" in previous_results) else 0 + new_results["total"] if("total" in new_results) else 0 - return ({"data":unique_data, "total": totalVal}) + unique_data = await self.remove_duplicates( + previous_results["data"] + if ("data" in previous_results) + else [] + new_results["data"] if ("data" in new_results) else [] + ) + totalVal = ( + previous_results["total"] + if ("total" in previous_results) + else 0 + new_results["total"] if ("total" in new_results) else 0 + ) + return {"data": unique_data, "total": totalVal} else: if start_date and end_date: - query['query']['bool']['filter']['range'][timestamp_field]['gte'] = str(start_date) - query['query']['bool']['filter']['range'][timestamp_field]['lte'] = str(end_date) + query["query"]["bool"]["filter"]["range"][timestamp_field][ + "gte" + ] = str(start_date) + query["query"]["bool"]["filter"]["range"][timestamp_field][ + "lte" + ] = str(end_date) # return await self.scan_indices(self.new_es, self.new_index, query, timestamp_field, start_date, end_date, size) - # else: + # else: response = await self.new_es.search( index=self.new_index + "*", body=jsonable_encoder(query), - size=size) - return {"data":response['hits']['hits'],"total":response['hits']["total"]["value"]} + size=size, + ) + return { + "data": response["hits"]["hits"], + "total": response["hits"]["total"]["value"], + } else: """Handles queries that do not have a timestamp field""" previous_results = [] @@ -157,19 +208,35 @@ async def post(self, query, indice=None, size=None, start_date=None, end_date=No response = await self.prev_es.search( index=self.prev_index + "*", body=jsonable_encoder(query), - size=size) - previous_results = {"data":response['hits']['hits'], "total":response['hits']["total"]["value"]} - self.new_index = self.new_index_prefix + (self.new_index if indice is None else indice) + size=size, + ) + previous_results = { + "data": response["hits"]["hits"], + "total": response["hits"]["total"]["value"], + } + self.new_index = self.new_index_prefix + ( + self.new_index if indice is None else indice + ) response = await self.new_es.search( - index=self.new_index+"*", - body=jsonable_encoder(query), - size=size) - new_results = {"data":response['hits']['hits'],"total":response['hits']["total"]["value"]} - - unique_data = await self.remove_duplicates(previous_results["data"] if("data" in previous_results) else [] + new_results["data"] if("data" in new_results) else []) - totalVal = previous_results["total"] if("total" in previous_results) else 0 + new_results["total"] if("total" in new_results) else 0 - - return ({"data":unique_data, "total": totalVal}) + index=self.new_index + "*", body=jsonable_encoder(query), size=size + ) + new_results = { + "data": response["hits"]["hits"], + "total": response["hits"]["total"]["value"], + } + + unique_data = await self.remove_duplicates( + previous_results["data"] + if ("data" in previous_results) + else [] + new_results["data"] if ("data" in new_results) else [] + ) + totalVal = ( + previous_results["total"] + if ("total" in previous_results) + else 0 + new_results["total"] if ("total" in new_results) else 0 + ) + + return {"data": unique_data, "total": totalVal} async def scan_indices( self, es_client, indice, query, timestamp_field, start_date, end_date, size @@ -180,8 +247,15 @@ async def scan_indices( indices = [indice] sorted_index_list = SortedIndexList() for index in indices: - sorted_index_list.insert(IndexTimestamp(index, await self.get_timestamps(es_client, index, timestamp_field, size))) - filtered_indices = sorted_index_list.get_indices_in_given_range(start_date, end_date) + sorted_index_list.insert( + IndexTimestamp( + index, + await self.get_timestamps(es_client, index, timestamp_field, size), + ) + ) + filtered_indices = sorted_index_list.get_indices_in_given_range( + start_date, end_date + ) results = [] for each_index in filtered_indices: query["query"]["bool"]["filter"]["range"][timestamp_field]["lte"] = str( @@ -191,14 +265,13 @@ async def scan_indices( max(start_date, each_index.timestamps[0]) ) response = await es_client.search( - index=each_index.index, - body=jsonable_encoder(query), - size=size) - results.extend(response['hits']['hits']) - total+=response['hits']['total']['value'] - - return({"data":await self.remove_duplicates(results) , "total":total}) - + index=each_index.index, body=jsonable_encoder(query), size=size + ) + results.extend(response["hits"]["hits"]) + total += response["hits"]["total"]["value"] + + return {"data": await self.remove_duplicates(results), "total": total} + async def remove_duplicates(self, all_results): seen = set() filtered_results = [] diff --git a/backend/app/services/splunk.py b/backend/app/services/splunk.py index 70b00263..d7cd8535 100644 --- a/backend/app/services/splunk.py +++ b/backend/app/services/splunk.py @@ -45,6 +45,8 @@ async def query( """ query["count"] = size query["offset"] = offset + query["sort_dir"] = "asc" + query["sort_key"] = "test_type" # If additional search parameters are provided, include those in searchindex searchindex = ( diff --git a/frontend/src/actions/commonActions.js b/frontend/src/actions/commonActions.js index 0551bd0f..2698a52c 100644 --- a/frontend/src/actions/commonActions.js +++ b/frontend/src/actions/commonActions.js @@ -6,69 +6,6 @@ import { setOCPCatFilters } from "./ocpActions"; import { setQuayCatFilters } from "./quayActions"; import { setTelcoCatFilters } from "./telcoActions"; -const getSortableRowValues = (result, tableColumns) => { - const tableKeys = tableColumns.map((item) => item.value); - return tableKeys.map((key) => result[key]); -}; - -export const sortTable = (currState) => (dispatch, getState) => { - const results = [...getState()[currState].filteredResults]; - const { activeSortDir, activeSortIndex, tableColumns } = - getState()[currState]; - try { - if (activeSortIndex !== null && typeof activeSortIndex !== "undefined") { - const sortedResults = results.sort((a, b) => { - const aValue = getSortableRowValues(a, tableColumns)[activeSortIndex]; - const bValue = getSortableRowValues(b, tableColumns)[activeSortIndex]; - if (typeof aValue === "number") { - if (activeSortDir === "asc") { - return aValue - bValue; - } - return bValue - aValue; - } else { - if (activeSortDir === "asc") { - return aValue.localeCompare(bValue); - } - return bValue.localeCompare(aValue); - } - }); - dispatch(sortedTableRows(currState, sortedResults)); - } - } catch (error) { - console.log(error); - } -}; - -const sortedTableRows = (currState, sortedResults) => (dispatch) => { - if (currState === "cpt") { - dispatch({ - type: TYPES.SET_FILTERED_DATA, - payload: sortedResults, - }); - return; - } - if (currState === "ocp") { - dispatch({ - type: TYPES.SET_OCP_FILTERED_DATA, - payload: sortedResults, - }); - return; - } - if (currState === "quay") { - dispatch({ - type: TYPES.SET_QUAY_FILTERED_DATA, - payload: sortedResults, - }); - return; - } - if (currState === "telco") { - dispatch({ - type: TYPES.SET_TELCO_FILTERED_DATA, - payload: sortedResults, - }); - } -}; - const findItemCount = (data, key, value) => { return data.reduce(function (n, item) { return n + (item[key].toLowerCase() === value); @@ -203,13 +140,15 @@ export const getSelectedFilter = }; export const getRequestParams = (type) => (dispatch, getState) => { - const { start_date, end_date, size, offset } = getState()[type]; + const { start_date, end_date, size, offset, sort } = getState()[type]; + // const sortParam = `${activeSortIndex}:${activeSortDir}`; const params = { pretty: true, ...(start_date && { start_date }), ...(end_date && { end_date }), size: size, offset: offset, + ...(sort && { sort }), }; return params; diff --git a/frontend/src/actions/homeActions.js b/frontend/src/actions/homeActions.js index ce51a2c0..260ef810 100644 --- a/frontend/src/actions/homeActions.js +++ b/frontend/src/actions/homeActions.js @@ -9,7 +9,6 @@ import { getFilteredData, getRequestParams, getSelectedFilter, - sortTable, } from "./commonActions"; import API from "@/utils/axiosInstance"; @@ -57,7 +56,6 @@ export const fetchOCPJobsData = }); dispatch(applyFilters()); - dispatch(sortTable("cpt")); dispatch(tableReCalcValues()); } } catch (error) { diff --git a/frontend/src/actions/ocpActions.js b/frontend/src/actions/ocpActions.js index 94657b15..c7634c84 100644 --- a/frontend/src/actions/ocpActions.js +++ b/frontend/src/actions/ocpActions.js @@ -9,7 +9,6 @@ import { getFilteredData, getRequestParams, getSelectedFilter, - sortTable, } from "./commonActions"; import API from "@/utils/axiosInstance"; @@ -52,7 +51,6 @@ export const fetchOCPJobs = () => async (dispatch) => { }); dispatch(applyFilters()); - dispatch(sortTable("ocp")); dispatch(tableReCalcValues()); } } catch (error) { diff --git a/frontend/src/actions/sortingActions.js b/frontend/src/actions/sortingActions.js index 742820b5..15e72cb8 100644 --- a/frontend/src/actions/sortingActions.js +++ b/frontend/src/actions/sortingActions.js @@ -1,9 +1,18 @@ +import * as TYPES from "@/actions/types.js"; + +import { fetchOCPJobs, setOCPSortDir, setOCPSortIndex } from "./ocpActions"; +import { + fetchQuayJobsData, + setQuaySortDir, + setQuaySortIndex, +} from "./quayActions"; +import { + fetchTelcoJobsData, + setTelcoSortDir, + setTelcoSortIndex, +} from "./telcoActions"; import { setCPTSortDir, setCPTSortIndex } from "./homeActions"; -import { setOCPSortDir, setOCPSortIndex } from "./ocpActions"; -import { setQuaySortDir, setQuaySortIndex } from "./quayActions"; -import { setTelcoSortDir, setTelcoSortIndex } from "./telcoActions"; -import { sortTable } from "./commonActions"; import store from "@/store/store"; const { dispatch } = store; @@ -29,6 +38,56 @@ export const setActiveSortIndex = (index, currType) => { dispatch(setTelcoSortIndex(index)); } }; -export const handleOnSort = (currType) => { - dispatch(sortTable(currType)); +export const handleOnSort = (colName, currType) => { + dispatch(sortTable(colName, currType)); +}; + +const offsetActions = { + cpt: TYPES.SET_CPT_OFFSET, + ocp: TYPES.SET_OCP_OFFSET, + quay: TYPES.SET_QUAY_OFFSET, + telco: TYPES.SET_TELCO_OFFSET, +}; +const fetchJobsMap = { + ocp: fetchOCPJobs, + quay: fetchQuayJobsData, + telco: fetchTelcoJobsData, +}; +const sortObjActions = { + ocp: TYPES.SET_OCP_SORT_OBJ, + quay: TYPES.SET_QUAY_SORT_OBJ, +}; +export const sortTable = (colName, currState) => (dispatch, getState) => { + const { activeSortDir, activeSortIndex } = getState()[currState]; + const countObj = [ + "masterNodesCount", + "workerNodesCount", + "infraNodesCount", + "totalNodesCount", + "startDate", + "endDate", + ]; + try { + if ( + typeof activeSortDir !== "undefined" && + typeof activeSortIndex !== "undefined" + ) { + dispatch({ type: offsetActions[currState], payload: 0 }); + let fieldName = countObj.includes(colName) + ? colName + : `${colName}.keyword`; + if (colName === "build") { + fieldName = "ocpVersion.keyword"; + } + + const sortParam = `${fieldName}:${activeSortDir}`; + dispatch({ type: sortObjActions[currState], payload: sortParam }); + console.log(sortParam); + const isFromSorting = true; + + dispatch(fetchJobsMap[currState](isFromSorting)); + } + } catch (error) { + console.log(error); + } }; diff --git a/frontend/src/actions/types.js b/frontend/src/actions/types.js index 734d6568..2677f164 100644 --- a/frontend/src/actions/types.js +++ b/frontend/src/actions/types.js @@ -33,6 +33,7 @@ export const SET_OCP_JOBS_DATA = "SET_OCP_JOBS_DATA"; export const SET_OCP_DATE_FILTER = "SET_OCP_DATE_FILTER"; export const SET_OCP_SORT_INDEX = "SET_OCP_SORT_INDEX"; export const SET_OCP_SORT_DIR = "SET_OCP_SORT_DIR"; +export const SET_OCP_SORT_OBJ = "SET_OCP_SORT_OBJ"; export const SET_OCP_PAGE = "SET_OCP_PAGE"; export const SET_OCP_PAGE_OPTIONS = "SET_OCP_PAGE_OPTIONS"; export const SET_OCP_INIT_JOBS = "SET_OCP_INIT_JOBS"; @@ -52,6 +53,7 @@ export const SET_QUAY_JOBS_DATA = "SET_QUAY_JOBS_DATA"; export const SET_QUAY_DATE_FILTER = "SET_QUAY_DATE_FILTER"; export const SET_QUAY_SORT_INDEX = "SET_QUAY_SORT_INDEX"; export const SET_QUAY_SORT_DIR = "SET_QUAY_SORT_DIR"; +export const SET_QUAY_SORT_OBJ = "SET_QUAY_SORT_OBJ"; export const SET_QUAY_PAGE = "SET_QUAY_PAGE"; export const SET_QUAY_PAGE_OPTIONS = "SET_QUAY_PAGE_OPTIONS"; export const SET_QUAY_INIT_JOBS = "SET_QUAY_INIT_JOBS"; diff --git a/frontend/src/components/organisms/TableLayout/index.jsx b/frontend/src/components/organisms/TableLayout/index.jsx index 500c1bc9..e24def32 100644 --- a/frontend/src/components/organisms/TableLayout/index.jsx +++ b/frontend/src/components/organisms/TableLayout/index.jsx @@ -21,9 +21,10 @@ const TableLayout = (props) => { totalItems, addExpansion, type, + shouldSort, } = props; - const getSortParams = (columnIndex) => ({ + const getSortParams = (columnIndex, colName) => ({ sortBy: { index: activeSortIndex, direction: activeSortDir, @@ -32,7 +33,7 @@ const TableLayout = (props) => { onSort: (_event, index, direction) => { setActiveSortIndex(index, type); setActiveSortDir(direction, type); - handleOnSort(type); + handleOnSort(colName, type); }, columnIndex, }); @@ -46,7 +47,10 @@ const TableLayout = (props) => { {tableColumns?.length > 0 && tableColumns.map((col, idx) => ( - + {col.name} ))} @@ -99,5 +103,6 @@ TableLayout.propTypes = { type: PropTypes.string, isRunExpanded: PropTypes.func, setRunExpanded: PropTypes.func, + shouldSort: PropTypes.bool, }; export default TableLayout; diff --git a/frontend/src/components/templates/Home/index.jsx b/frontend/src/components/templates/Home/index.jsx index 52b281b0..f18264b4 100644 --- a/frontend/src/components/templates/Home/index.jsx +++ b/frontend/src/components/templates/Home/index.jsx @@ -100,6 +100,7 @@ const Home = () => { totalItems={totalJobs} addExpansion={false} type={"cpt"} + shouldSort={false} /> ); diff --git a/frontend/src/components/templates/OCP/index.jsx b/frontend/src/components/templates/OCP/index.jsx index 74db5d00..1e21057f 100644 --- a/frontend/src/components/templates/OCP/index.jsx +++ b/frontend/src/components/templates/OCP/index.jsx @@ -135,6 +135,7 @@ const OCP = () => { setRunExpanded={setRunExpanded} graphData={graphData} type={"ocp"} + shouldSort={true} /> ); diff --git a/frontend/src/components/templates/Quay/index.jsx b/frontend/src/components/templates/Quay/index.jsx index 23e0ed40..bff5c2a4 100644 --- a/frontend/src/components/templates/Quay/index.jsx +++ b/frontend/src/components/templates/Quay/index.jsx @@ -134,6 +134,7 @@ const Quay = () => { isRunExpanded={isRunExpanded} setRunExpanded={setRunExpanded} graphData={graphData} + shouldSort={true} /> ); diff --git a/frontend/src/components/templates/Telco/index.jsx b/frontend/src/components/templates/Telco/index.jsx index 181b9923..110cf42d 100644 --- a/frontend/src/components/templates/Telco/index.jsx +++ b/frontend/src/components/templates/Telco/index.jsx @@ -133,6 +133,7 @@ const Telco = () => { isRunExpanded={isRunExpanded} setRunExpanded={setRunExpanded} graphData={graphData} + shouldSort={false} /> ); diff --git a/frontend/src/reducers/homeReducer.js b/frontend/src/reducers/homeReducer.js index a2f477e1..716c4d47 100644 --- a/frontend/src/reducers/homeReducer.js +++ b/frontend/src/reducers/homeReducer.js @@ -32,6 +32,7 @@ const initialState = { filterData: [], activeSortDir: null, activeSortIndex: null, + sort: "", categoryFilterValue: "", filterOptions: [], appliedFilters: {}, diff --git a/frontend/src/reducers/ocpReducer.js b/frontend/src/reducers/ocpReducer.js index 20232ad8..78f1df2e 100644 --- a/frontend/src/reducers/ocpReducer.js +++ b/frontend/src/reducers/ocpReducer.js @@ -42,6 +42,7 @@ const initialState = { ], activeSortDir: null, activeSortIndex: null, + sort: "", page: START_PAGE, perPage: DEFAULT_PER_PAGE, size: DEFAULT_PER_PAGE, @@ -133,6 +134,8 @@ const OCPReducer = (state = initialState, action = {}) => { return { ...state, activeSortIndex: payload }; case TYPES.SET_OCP_SORT_DIR: return { ...state, activeSortDir: payload }; + case TYPES.SET_OCP_SORT_OBJ: + return { ...state, sort: payload }; case TYPES.SET_OCP_PAGE: return { ...state, page: payload }; case TYPES.SET_OCP_PAGE_OPTIONS: diff --git a/frontend/src/reducers/quayReducer.js b/frontend/src/reducers/quayReducer.js index 9e33d160..db7f4551 100644 --- a/frontend/src/reducers/quayReducer.js +++ b/frontend/src/reducers/quayReducer.js @@ -61,6 +61,7 @@ const initialState = { appliedFilters: {}, activeSortDir: null, activeSortIndex: null, + sort: "", graphData: [], page: START_PAGE, perPage: DEFAULT_PER_PAGE, @@ -97,6 +98,8 @@ const QuayReducer = (state = initialState, action = {}) => { return { ...state, activeSortIndex: payload }; case TYPES.SET_QUAY_SORT_DIR: return { ...state, activeSortDir: payload }; + case TYPES.SET_QUAY_SORT_OBJ: + return { ...state, sort: payload }; case TYPES.SET_QUAY_PAGE: return { ...state, page: payload }; case TYPES.SET_QUAY_PAGE_OPTIONS: diff --git a/frontend/src/reducers/telcoReducer.js b/frontend/src/reducers/telcoReducer.js index 5dd1a140..1637f131 100644 --- a/frontend/src/reducers/telcoReducer.js +++ b/frontend/src/reducers/telcoReducer.js @@ -58,6 +58,7 @@ const initialState = { appliedFilters: {}, activeSortDir: null, activeSortIndex: null, + sort: "", graphData: [], page: START_PAGE, perPage: DEFAULT_PER_PAGE,