Skip to content

ITEP-28186 Filter jobs by date #150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright (C) 2022-2025 Intel Corporation
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should put this component close to jobs-actions because it's needed only there. If we need this component later in other places, we will move it to @geti/ui :).

// LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE

import { FC, ReactNode, useState } from 'react';

import {
Content,
DateField,
Dialog,
DialogTrigger,
Flex,
Heading,
RangeCalendar,
Tooltip,
TooltipTrigger,
useDateFormatter,
} from '@adobe/react-spectrum';
import { DateValue, getLocalTimeZone } from '@internationalized/date';
import Calendar from '@spectrum-icons/workflow/Calendar';
import isEmpty from 'lodash/isEmpty';
import { RangeCalendarProps } from 'react-aria-components';

import { QuietActionButton } from '../quiet-button/quiet-action-button.component';

interface DateRangePickerSmall extends RangeCalendarProps<DateValue> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We allow consumer to pass focusedValue and onFocusChange which will never be used because we use internal state for this. We should do Omit<RangeCalendarProps<DateValue>, 'focusedValue' | 'onFocusChange>;`

hasManualEdition?: boolean;
headerContent?: ReactNode;
}

export const DateRangePickerSmall: FC<DateRangePickerSmall> = ({
hasManualEdition,
headerContent,
value: range,
onChange,
...props
}) => {
const formatter = useDateFormatter({ dateStyle: 'long' });
const [focusedDate, setFocusedDate] = useState<DateValue | undefined>();

const rangeText = isEmpty(range)
? ''
: formatter.formatRange(range.start.toDate(getLocalTimeZone()), range.end.toDate(getLocalTimeZone()));

const handleOnChange = (attribute: 'start' | 'end', value: DateValue | null | undefined) => {
if (isEmpty(value) || isEmpty(range)) {
return;
}

onChange && onChange({ ...range, [attribute]: value });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
onChange && onChange({ ...range, [attribute]: value });
isFunction(onChange) && onChange({ ...range, [attribute]: value });

setFocusedDate(value);
};

const rangeFields = (
<Flex gap={'size-50'}>
<DateField
isQuiet={false}
label='From'
value={range?.start}
onChange={(value) => handleOnChange('start', value)}
/>
<DateField
isQuiet={false}
label='To'
value={range?.end}
onChange={(value) => handleOnChange('end', value)}
/>
</Flex>
);

return (
<DialogTrigger type='popover'>
<TooltipTrigger placement={'bottom'}>
<QuietActionButton aria-label='Select date range'>
<Calendar />
</QuietActionButton>
<Tooltip>{rangeText}</Tooltip>
</TooltipTrigger>
<Dialog>
{headerContent ? <Heading>{headerContent}</Heading> : <></>}
<Content>
<RangeCalendar
{...props}
value={range}
onChange={onChange}
focusedValue={focusedDate}
onFocusChange={setFocusedDate}
/>
{hasManualEdition ? rangeFields : <p>{rangeText}</p>}
</Content>
</Dialog>
</DialogTrigger>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright (C) 2022-2025 Intel Corporation
// LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE

import { CalendarDate } from '@internationalized/date';
import { RangeValue } from '@react-types/shared';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { providersRender as render } from '../../../test-utils/required-providers-render';
import { DateRangePickerSmall } from './date-range-picker-small.component';

describe('DateRangePickerSmall Component', () => {
const MOCKED_TODAY = new CalendarDate(2025, 4, 30);

const INITIAL_DATES: RangeValue<CalendarDate> = {
start: MOCKED_TODAY.subtract({ months: 1 }),
end: MOCKED_TODAY,
};

const mockOnChange = jest.fn();

const renderComponent = (props = {}) =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

np. props can be removed, we don't use them.

render(
<DateRangePickerSmall
value={INITIAL_DATES}
onChange={mockOnChange}
hasManualEdition={true}
headerContent='Select Date Range'
{...props}
/>
);

afterEach(() => {
userEvent.keyboard('{escape}');
});

it('should open the date range dialog when the button is clicked', async () => {
renderComponent();

expect(screen.getByRole('button', { name: 'Select date range' })).toBeInTheDocument();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

np. TBH we don't need to check if the button is in the document because if it is not then userEvent.click in line 41 will break.

await userEvent.click(screen.getByRole('button', { name: 'Select date range' }));
expect(await screen.findByRole('dialog')).toBeVisible();

expect(screen.getByText('Select Date Range')).toBeInTheDocument();
expect(await screen.findByRole('dialog')).toBeVisible();
});

it('should allow manual editing of the date range', async () => {
renderComponent();

const button = screen.getByRole('button', { name: 'Select date range' });
expect(button).toBeInTheDocument();

await userEvent.click(button);
expect(await screen.findByRole('dialog')).toBeVisible();

const march3rdButton = screen.getByRole('button', { name: 'Monday, March 3, 2025' });
const march8thButton = screen.getByRole('button', { name: 'Saturday, March 8, 2025' });

await userEvent.click(march3rdButton);
await userEvent.click(march8thButton);

expect(mockOnChange).toHaveBeenCalledWith(
expect.objectContaining({
end: expect.objectContaining({ day: 8, month: 3, year: 2025 }),
start: expect.objectContaining({ day: 3, month: 3, year: 2025 }),
})
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (C) 2022-2025 Intel Corporation
// LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE

import { JobType } from '../../../../../core/jobs/jobs.const';

export interface FiltersType {
projectId: string | undefined;
userId: string | undefined;
jobTypes: JobType[];
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (C) 2022-2025 Intel Corporation
// LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE

import { Key, useCallback, useEffect, useMemo, useState } from 'react';
import { Key, useCallback, useMemo, useState } from 'react';

import { InfiniteQueryObserverResult } from '@tanstack/react-query';
import { isEmpty } from 'lodash-es';
Expand All @@ -13,29 +13,26 @@ import { ProjectSortingOptions } from '../../../../../core/projects/services/pro
import { useUsers } from '../../../../../core/users/hook/use-users.hook';
import { RESOURCE_TYPE, User } from '../../../../../core/users/users.interface';
import { useWorkspaceIdentifier } from '../../../../../providers/workspaces-provider/use-workspace-identifier.hook';
import { hasEqualId, isNonEmptyArray } from '../../../../utils';
import { isNonEmptyArray } from '../../../../utils';
import { JobsFilterField } from '../jobs-filter-field.component';
import { JobsTypeFilterField } from './job-types-filter-field.component';

interface JobsFilteringDefaultValuesProps {
projectIdFilter: string | undefined;
userIdFilter: string | undefined;
jobTypeFilter: JobType[];
}
import { FiltersType } from './jobs-dialog.interface';

interface JobsFilteringProps {
defaultValues: JobsFilteringDefaultValuesProps;
onChange: (projectId: string | undefined, userId: string | undefined, type: JobType[]) => void;
values: FiltersType;
onChange: (newFilters: FiltersType) => void;
}

export const JobsFiltering = ({ defaultValues, onChange }: JobsFilteringProps): JSX.Element => {
export const JobsFiltering = ({ values, onChange }: JobsFilteringProps): JSX.Element => {
const { organizationId, workspaceId } = useWorkspaceIdentifier();

const { projectIdFilter, userIdFilter, jobTypeFilter } = defaultValues;
const [jobFilters, setJobFilters] = useState<FiltersType>(values);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this state here? I see we define state in the jobs-dialog and we have access to that state here. IMO we could remove the jobFilters from this component.

const { projectId, userId, jobTypes } = jobFilters;

const [selectedProject, setSelectedProject] = useState<string | undefined>(projectIdFilter);
const [selectedUser, setSelectedUser] = useState<string | undefined>(userIdFilter);
const [selectedJobTypes, setSelectedJobTypes] = useState<JobType[]>(jobTypeFilter);
const updateJobsFilters = (newFilters: FiltersType): void => {
onChange(newFilters);
setJobFilters(newFilters);
};

const { useGetProjects } = useProjectActions();
const {
Expand All @@ -55,9 +52,9 @@ export const JobsFiltering = ({ defaultValues, onChange }: JobsFilteringProps):
const { useGetUsersQuery } = useUsers();
const { users, isLoading: isLoadingUsers } = useGetUsersQuery(
organizationId,
selectedProject
projectId
? {
resourceId: selectedProject,
resourceId: projectId,
resourceType: RESOURCE_TYPE.PROJECT,
}
: undefined
Expand Down Expand Up @@ -95,29 +92,18 @@ export const JobsFiltering = ({ defaultValues, onChange }: JobsFilteringProps):
const setSelectedProjectHandler = (key: Key | null): void => {
const newFilterValue: undefined | string = isEmpty(key) ? undefined : (key as string);

setSelectedProject(newFilterValue);
updateJobsFilters({ ...jobFilters, projectId: newFilterValue });
};

const setSelectedUserHandler = (key: Key | null): void => {
const newFilterValue: undefined | string = isEmpty(key) ? undefined : (key as string);

setSelectedUser(newFilterValue);
updateJobsFilters({ ...jobFilters, userId: newFilterValue });
};

useEffect(() => {
if (isLoadingUsers) return;

const isSelectedUserInProject: boolean | undefined = users?.some(hasEqualId(selectedUser));

if (!!isSelectedUserInProject) return;

setSelectedUser(undefined);
onChange(selectedProject, undefined, selectedJobTypes);
}, [isLoadingUsers, onChange, selectedJobTypes, selectedProject, selectedUser, users]);

useEffect(() => {
onChange(selectedProject, selectedUser, selectedJobTypes);
}, [selectedProject, selectedUser, selectedJobTypes, onChange]);
Comment on lines -107 to -120
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❀️

const setSelectedJobTypesHandler = (newJobTypes: JobType[]): void => {
updateJobsFilters({ ...jobFilters, jobTypes: newJobTypes });
};

return (
<>
Expand All @@ -126,7 +112,7 @@ export const JobsFiltering = ({ defaultValues, onChange }: JobsFilteringProps):
ariaLabel={'Job scheduler filter project'}
dataTestId={'job-scheduler-filter-project'}
options={[allProjectOption, ...projectOptions]}
value={selectedProject ?? allProjectOption.key}
value={projectId ?? allProjectOption.key}
onSelectionChange={setSelectedProjectHandler}
isLoading={isLoadingProjects || isFetchingNextPage}
loadMore={loadMoreProjects}
Expand All @@ -136,11 +122,11 @@ export const JobsFiltering = ({ defaultValues, onChange }: JobsFilteringProps):
ariaLabel={'Job scheduler filter user'}
dataTestId={'job-scheduler-filter-user'}
options={[allUsersOption, ...usersOptions]}
value={selectedUser ?? allUsersOption.key}
value={userId ?? allUsersOption.key}
onSelectionChange={setSelectedUserHandler}
isLoading={isLoadingUsers}
/>
<JobsTypeFilterField selectedJobTypes={selectedJobTypes} setSelectedJobTypes={setSelectedJobTypes} />
<JobsTypeFilterField selectedJobTypes={jobTypes} setSelectedJobTypes={setSelectedJobTypesHandler} />
</>
);
};
Loading
Loading