Skip to content

Commit

Permalink
Refactored code to fix lint,prettier and test script issues
Browse files Browse the repository at this point in the history
  • Loading branch information
del22123 committed Dec 19, 2024
1 parent 5aa7ef9 commit a52f259
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Object {
"availableSortMethods": null,
"categoryDescription": "Jewelry category",
"categoryName": "Jewelry",
"filterOptions": undefined,
"filters": null,
"items": Array [
null,
Expand All @@ -17,6 +18,7 @@ Object {
null,
null,
],
"setFilterOptions": [Function],
"totalCount": null,
"totalPagesFromData": null,
}
Expand All @@ -32,6 +34,7 @@ Object {
],
"categoryDescription": "Jewelry category",
"categoryName": "Jewelry",
"filterOptions": undefined,
"filters": Array [
Object {
"label": "Label",
Expand All @@ -47,6 +50,7 @@ Object {
"name": "Necklace",
},
],
"setFilterOptions": [Function],
"totalCount": 2,
"totalPagesFromData": 1,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ jest.mock('@apollo/client', () => {
};
});

const mockGetFiltersAttributeCode = {
data: {
products: {
aggregations: [
{
label: 'Label'
}
]
}
}
};

const mockProductFiltersByCategoryData = {
data: {
products: {
Expand Down Expand Up @@ -91,21 +103,22 @@ const mockCategoryData = {

const mockGetSortMethods = jest.fn();
const mockGetFilters = jest.fn();
const mockfilterData = jest.fn();

jest.mock('@magento/peregrine/lib/context/eventing', () => ({
useEventingContext: jest.fn().mockReturnValue([{}, { dispatch: jest.fn() }])
}));

const Component = props => {
const talonprops = useCategoryContent(props);

return <i {...talonprops} />;
};

useQuery.mockReturnValue({ data: mockCategoryData });
describe('useCategoryContent tests', () => {
it('returns the proper shape', () => {
useLazyQuery
.mockReturnValueOnce([mockfilterData, mockGetFiltersAttributeCode])
.mockReturnValueOnce([
mockGetFilters,
mockProductFiltersByCategoryData
Expand All @@ -124,6 +137,7 @@ describe('useCategoryContent tests', () => {

it('handles default category id', () => {
useLazyQuery
.mockReturnValueOnce([mockfilterData, mockGetFiltersAttributeCode])
.mockReturnValueOnce([
mockGetFilters,
mockProductFiltersByCategoryData
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { gql } from '@apollo/client';

export const GET_PRODUCT_FILTERS_BY_CATEGORY = gql`
query getProductFiltersByCategory(
$filters: ProductAttributeFilterInput!
) {
query getProductFiltersByCategory($filters: ProductAttributeFilterInput!) {
products(filter: $filters) {
aggregations {
label
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, useMemo } from 'react';
import { useLazyQuery, useQuery } from '@apollo/client';

import mergeOperations from '../../../util/shallowMerge';
Expand Down Expand Up @@ -29,39 +29,101 @@ export const useCategoryContent = props => {
getCategoryAvailableSortMethodsQuery
} = operations;

const placeholderItems = Array.from({ length: pageSize }).fill(null);
const [
getFiltersAttributeCode,
{ data: filterAttributeData }
] = useLazyQuery(getProductFiltersByCategoryQuery, {
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first'
});

const [getFilters, { data: filterData }] = useLazyQuery(
getProductFiltersByCategoryQuery,
{
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first'
useEffect(() => {
if (categoryId) {
getFiltersAttributeCode({
variables: {
filters: {
category_uid: { eq: categoryId }
}
}
});
}
);
}, [categoryId, getFiltersAttributeCode]);

const [filterOptions, setFilterOptions] = useState();

const availableFilterData = filterData
? filterData.products?.aggregations
const availableFilterData = filterAttributeData
? filterAttributeData.products?.aggregations
: null;
const availableFilters = availableFilterData
?.map(eachitem => eachitem.attribute_code)
?.sort();
const selectedFilters = {};

if (filterOptions) {
for (const [group, items] of filterOptions) {
availableFilters?.map(eachitem => {
if (eachitem === group) {
const sampleArray = [];
for (const item of items) {
sampleArray.push(item.value);

const handlePriceFilter = priceFilter => {
if (priceFilter && priceFilter.size > 0) {
for (const price of priceFilter) {
const [from, to] = price.value.split('_');
return { price: { from, to } };
}
}
return {};
};

const [filterOptions, setFilterOptions] = useState();

const selectedFilters = useMemo(() => {
const filters = {};
if (filterOptions) {
for (const [group, items] of filterOptions.entries()) {
availableFilters?.map(eachitem => {
if (eachitem === group && group !== 'price') {
const sampleArray = [];
for (const item of items) {
sampleArray.push(item.value);
}
filters[group] = sampleArray;
}
selectedFilters[group] = sampleArray;
});
}
}

if (filterOptions && filterOptions.has('price')) {
const priceFilter = filterOptions.get('price');
const priceRange = handlePriceFilter(priceFilter);
if (priceRange.price) {
filters.price = priceRange.price;
}
}

return filters;
}, [filterOptions, availableFilters]);

const dynamicQueryVariables = useMemo(() => {
const generateDynamicFiltersQuery = filterParams => {
let filterConditions = {
category_uid: { eq: categoryId }
};

Object.keys(filterParams).forEach(key => {
let filter = {};
if (key !== 'price') {
filter = { [key]: { in: filterParams[key] } };
}
filterConditions = { ...filterConditions, ...filter };
});

return filterConditions;
};

return generateDynamicFiltersQuery(selectedFilters);
}, [selectedFilters, categoryId]);

const placeholderItems = Array.from({ length: pageSize }).fill(null);

const [getFilters, { data: filterData }] = useLazyQuery(
getProductFiltersByCategoryQuery,
{
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first'
}
}
);

const [getSortMethods, { data: sortData }] = useLazyQuery(
getCategoryAvailableSortMethodsQuery,
Expand All @@ -84,29 +146,26 @@ export const useCategoryContent = props => {
);

const [, { dispatch }] = useEventingContext();

const [previousFilters, setPreviousFilters] = useState(null);
useEffect(() => {
if (categoryId) {
let dynamicFilters = {
category_uid: { eq: categoryId }
};
Object.keys(selectedFilters).forEach(key => {
let filter = {};
if (key === 'price') {
let [from, to] = selectedFilters[key][0].split('_');
filter = { [key]: { from: from, to: to }};
} else {
filter = { [key]: { in: selectedFilters[key]}};
}
dynamicFilters = { ...dynamicFilters, ...filter };
});
if (
categoryId &&
JSON.stringify(selectedFilters) !== JSON.stringify(previousFilters)
) {
getFilters({
variables: {
filters: dynamicFilters
filters: dynamicQueryVariables
}
});
setPreviousFilters(selectedFilters);
}
}, [categoryId, getFilters]);
}, [
categoryId,
selectedFilters,
dynamicQueryVariables,
previousFilters,
getFilters
]);

useEffect(() => {
if (categoryId) {
Expand All @@ -120,7 +179,7 @@ export const useCategoryContent = props => {
}
}, [categoryId, getSortMethods]);

const filters = filterData ? filterData.products.aggregations : null;
const filters = filterData ? filterData.products?.aggregations : null;
const items = data ? data.products.items : placeholderItems;
const totalPagesFromData = data
? data.products.page_info.total_pages
Expand All @@ -139,7 +198,7 @@ export const useCategoryContent = props => {
: null;

useEffect(() => {
if (!categoryLoading && categoryData.categories.items.length > 0) {
if (!categoryLoading && categoryData?.categories.items.length > 0) {
dispatch({
type: 'CATEGORY_PAGE_VIEW',
payload: {
Expand All @@ -157,6 +216,7 @@ export const useCategoryContent = props => {
categoryName,
categoryDescription,
filters,
filterOptions,
setFilterOptions,
items,
totalCount,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ const mockHandleApply = jest.fn();

const mockScrollTo = jest.fn();

const mockFilterOptions = jest.fn();

const mockGetBoundingClientRect = jest.fn();

let mockFilterState;
Expand Down Expand Up @@ -125,21 +127,24 @@ const Component = () => {

const givenDefaultValues = () => {
inputProps = {
filters: []
filters: [],
setFilterOptions: mockFilterOptions
};

mockFilterState = new Map();
};

const givenFilters = () => {
inputProps = {
filters: mockFilters
filters: mockFilters,
setFilterOptions: mockFilterOptions
};
};

const givenSelectedFilters = () => {
inputProps = {
filters: mockFilters
filters: mockFilters,
setFilterOptions: mockFilterOptions
};

mockFilterState = new Map([['group', 'item']]);
Expand All @@ -148,7 +153,8 @@ const givenSelectedFilters = () => {
const givenFiltersAndAmountToShow = () => {
inputProps = {
filters: mockFilters,
filterCountToOpen: mockFiltersOpenCount
filterCountToOpen: mockFiltersOpenCount,
setFilterOptions: mockFilterOptions
};
};

Expand Down

0 comments on commit a52f259

Please sign in to comment.