[APPS-2132] migrate components to date-fns (#9001)

* migrate edit process filter to date-fns

* refresh unit tests

* fix a11y for date-fns

* Revert "fix a11y for date-fns"

This reverts commit 2e706d4aed1b8a50d1de62fe11d9d528530d628c.

* update e2e

* start task fixes

* cleanup code

* remove fdescribe

* remove moment, improve unit testing

* remove dependency on date util

* cleanup search date range component

* cleanup code

* migrate search date range component

* revert e2e changes for now

* extra fixes and tests

* add missing functionality, extra tests

* increase time constraints

* improved code, disabled e2e

* move e2e to unit tests, extra rework for insights

* extra unit test for date range validation

* migrate date-range to date-fns
This commit is contained in:
Denys Vuika
2023-10-17 17:24:46 +01:00
committed by GitHub
parent f7b0544172
commit e6d625253c
21 changed files with 857 additions and 803 deletions

View File

@@ -17,7 +17,6 @@
import { createApiService, import { createApiService,
AppListCloudPage, AppListCloudPage,
DateUtil,
GroupIdentityService, GroupIdentityService,
IdentityService, IdentityService,
LocalStorageUtil, LocalStorageUtil,
@@ -67,17 +66,26 @@ describe('Process filters cloud', () => {
const queryService = new QueryService(apiService); const queryService = new QueryService(apiService);
const tasksService = new TasksService(apiService); const tasksService = new TasksService(apiService);
const beforeDate = format(subDays(new Date(), 1), 'dd/MM/yyyy'); const beforeDate = format(subDays(new Date(), 2), 'dd/MM/yyyy');
const currentDate = DateUtil.formatDate('DD/MM/YYYY'); const currentDate = format(new Date(), 'dd/MM/yyyy');
const afterDate = format(addDays(new Date(), 1), 'dd/MM/yyyy'); const afterDate = format(addDays(new Date(), 2), 'dd/MM/yyyy');
const processListCloudConfiguration = new ProcessListCloudConfiguration(); const processListCloudConfiguration = new ProcessListCloudConfiguration();
const editProcessFilterConfiguration = new EditProcessFilterConfiguration(); const editProcessFilterConfiguration = new EditProcessFilterConfiguration();
const processListCloudConfigFile = processListCloudConfiguration.getConfiguration(); const processListCloudConfigFile = processListCloudConfiguration.getConfiguration();
const editProcessFilterConfigFile = editProcessFilterConfiguration.getConfiguration(); const editProcessFilterConfigFile = editProcessFilterConfiguration.getConfiguration();
let completedProcess; let runningProcessInstance; let suspendProcessInstance; let testUser; let anotherUser; let groupInfo; let completedProcess: any;
let anotherProcessInstance; let processDefinition; let anotherProcessDefinition; let runningProcessInstance: any;
let differentAppUserProcessInstance; let simpleAppProcessDefinition; let suspendProcessInstance: any;
let testUser: any;
let anotherUser: any;
let groupInfo: any;
let anotherProcessInstance: any;
let processDefinition: any;
let anotherProcessDefinition: any;
let differentAppUserProcessInstance: any;
let simpleAppProcessDefinition: any;
const candidateBaseApp = browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.name; const candidateBaseApp = browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.name;
const simpleApp = browser.params.resources.ACTIVITI_CLOUD_APPS.SIMPLE_APP.name; const simpleApp = browser.params.resources.ACTIVITI_CLOUD_APPS.SIMPLE_APP.name;
@@ -252,7 +260,7 @@ describe('Process filters cloud', () => {
await processList.checkContentIsNotDisplayedByName(runningProcessInstance.entry.name); await processList.checkContentIsNotDisplayedByName(runningProcessInstance.entry.name);
}); });
it('[C306892] Should be able to filter by process status - Running', async () => { it('[C306892-1] Should be able to filter by process status - Running', async () => {
await editProcessFilter.openFilter(); await editProcessFilter.openFilter();
await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.RUNNING); await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.RUNNING);
await processList.getDataTable().waitTillContentLoaded(); await processList.getDataTable().waitTillContentLoaded();
@@ -269,7 +277,7 @@ describe('Process filters cloud', () => {
await processList.checkContentIsNotDisplayedByName(completedProcess.entry.name); await processList.checkContentIsNotDisplayedByName(completedProcess.entry.name);
}); });
it('[C306892] Should be able to filter by process status - Completed', async () => { it('[C306892-2] Should be able to filter by process status - Completed', async () => {
await editProcessFilter.openFilter(); await editProcessFilter.openFilter();
await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.COMPLETED); await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.COMPLETED);
await processList.getDataTable().waitTillContentLoaded(); await processList.getDataTable().waitTillContentLoaded();
@@ -286,7 +294,7 @@ describe('Process filters cloud', () => {
await processList.checkContentIsNotDisplayedByName(anotherProcessInstance.entry.name); await processList.checkContentIsNotDisplayedByName(anotherProcessInstance.entry.name);
}); });
it('[C306892] Should be able to filter by process status - Suspended', async () => { it('[C306892-3] Should be able to filter by process status - Suspended', async () => {
await editProcessFilter.openFilter(); await editProcessFilter.openFilter();
await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.SUSPENDED); await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.SUSPENDED);
await processList.getDataTable().waitTillContentLoaded(); await processList.getDataTable().waitTillContentLoaded();
@@ -303,7 +311,7 @@ describe('Process filters cloud', () => {
await processList.checkContentIsNotDisplayedByName(completedProcess.entry.name); await processList.checkContentIsNotDisplayedByName(completedProcess.entry.name);
}); });
it('[C306892] Should be able to filter by process status - All', async () => { it('[C306892-4] Should be able to filter by process status - All', async () => {
await processCloudDemoPage.processFilterCloudComponent.clickAllProcessesFilter(); await processCloudDemoPage.processFilterCloudComponent.clickAllProcessesFilter();
await editProcessFilter.openFilter(); await editProcessFilter.openFilter();
@@ -315,17 +323,17 @@ describe('Process filters cloud', () => {
await processList.checkContentIsDisplayedByName(completedProcess.entry.name); await processList.checkContentIsDisplayedByName(completedProcess.entry.name);
}); });
it('[C311318] Should be able to filter by lastModifiedFrom - displays record when date = currentDate', async () => { it('[C311318-1] Should be able to filter by lastModifiedFrom - displays record when date = currentDate', async () => {
await setProcessName(currentDate, 'lastModifiedFrom'); await setProcessName(currentDate, 'lastModifiedFrom');
await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name); await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name);
}); });
it('[C311318] Should be able to filter by lastModifiedFrom - displays record when date = beforeDate', async () => { it('[C311318-2] Should be able to filter by lastModifiedFrom - displays record when date = beforeDate', async () => {
await setProcessName(beforeDate, 'lastModifiedFrom'); await setProcessName(beforeDate, 'lastModifiedFrom');
await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name); await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name);
}); });
it('[C311318] Should be able to filter by lastModifiedFrom - does not display record when date = afterDate', async () => { it('[C311318-3] Should be able to filter by lastModifiedFrom - does not display record when date = afterDate', async () => {
await editProcessFilter.openFilter(); await editProcessFilter.openFilter();
await editProcessFilter.setProcessName(runningProcessInstance.entry.name); await editProcessFilter.setProcessName(runningProcessInstance.entry.name);
await processList.getDataTable().waitTillContentLoaded(); await processList.getDataTable().waitTillContentLoaded();
@@ -333,17 +341,17 @@ describe('Process filters cloud', () => {
await processList.checkContentIsNotDisplayedByName(runningProcessInstance.entry.name); await processList.checkContentIsNotDisplayedByName(runningProcessInstance.entry.name);
}); });
it('[C311319] Should be able to filter by lastModifiedTo - displays record when date = currentDate', async () => { it('[C311319-1] Should be able to filter by lastModifiedTo - displays record when date = currentDate', async () => {
await setProcessName(currentDate); await setProcessName(currentDate);
await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name); await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name);
}); });
it('[C311319] Should be able to filter by lastModifiedTo - does not display record when date = beforeDate', async () => { it('[C311319-2] Should be able to filter by lastModifiedTo - does not display record when date = beforeDate', async () => {
await setProcessName(beforeDate); await setProcessName(beforeDate);
await processList.checkContentIsNotDisplayedByName(runningProcessInstance.entry.name); await processList.checkContentIsNotDisplayedByName(runningProcessInstance.entry.name);
}); });
it('[C311319] Should be able to filter by lastModifiedTo - displays record when date = afterDate', async () => { it('[C311319-3] Should be able to filter by lastModifiedTo - displays record when date = afterDate', async () => {
await editProcessFilter.openFilter(); await editProcessFilter.openFilter();
await editProcessFilter.setProperty('lastModifiedTo', afterDate); await editProcessFilter.setProperty('lastModifiedTo', afterDate);
await processList.getDataTable().waitTillContentLoaded(); await processList.getDataTable().waitTillContentLoaded();
@@ -351,7 +359,7 @@ describe('Process filters cloud', () => {
await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name); await processList.checkContentIsDisplayedByName(runningProcessInstance.entry.name);
}); });
it('[C311319] Should not display any processes when the lastModifiedFrom and lastModifiedTo are set to a future date', async () => { it('[C311319-4] Should not display any processes when the lastModifiedFrom and lastModifiedTo are set to a future date', async () => {
await editProcessFilter.openFilter(); await editProcessFilter.openFilter();
await editProcessFilter.setProperty('lastModifiedFrom', afterDate); await editProcessFilter.setProperty('lastModifiedFrom', afterDate);
await processList.getDataTable().waitTillContentLoaded(); await processList.getDataTable().waitTillContentLoaded();

View File

@@ -20,7 +20,7 @@ import {
StringUtil, TasksService, StringUtil, TasksService,
ProcessDefinitionsService, ProcessInstancesService, ProcessDefinitionsService, ProcessInstancesService,
LoginPage, createApiService, LoginPage, createApiService,
AppListCloudPage, LocalStorageUtil, IdentityService, GroupIdentityService, DateUtil AppListCloudPage, LocalStorageUtil, IdentityService, GroupIdentityService
} from '@alfresco/adf-testing'; } from '@alfresco/adf-testing';
import { NavigationBarPage } from '../../core/pages/navigation-bar.page'; import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
import { TasksCloudDemoPage } from './../pages/tasks-cloud-demo.page'; import { TasksCloudDemoPage } from './../pages/tasks-cloud-demo.page';
@@ -50,12 +50,21 @@ describe('Edit task filters and task list properties', () => {
const processInstancesService = new ProcessInstancesService(apiService); const processInstancesService = new ProcessInstancesService(apiService);
const noTasksFoundMessage = 'No Tasks Found'; const noTasksFoundMessage = 'No Tasks Found';
let createdTask; let notAssigned; let notDisplayedTask; let processDefinition; let processInstance; let priorityTask; let subTask; let createdTask: any;
let otherOwnerTask; let testUser; let groupInfo; let simpleTask; let notAssigned: any;
let notDisplayedTask: any;
let processDefinition: any;
let processInstance: any;
let priorityTask: any;
let subTask: any;
let otherOwnerTask: any;
let testUser: any;
let groupInfo: any;
let simpleTask: any;
const priority = 1; const priority = 1;
const beforeDate = format(subDays(new Date(), 1), 'dd/MM/yyyy'); const beforeDate = format(subDays(new Date(), 1), 'dd/MM/yyyy');
const currentDate = DateUtil.formatDate('DD/MM/YYYY'); const currentDate = format(new Date(), 'dd/MM/yyyy');
const afterDate = format(addDays(new Date(), 1), 'dd/MM/yyyy'); const afterDate = format(addDays(new Date(), 1), 'dd/MM/yyyy');
beforeAll(async () => { beforeAll(async () => {

View File

@@ -23,7 +23,7 @@ import { ProcessServiceTabBarPage } from '../pages/process-service-tab-bar.page'
import { ProcessListPage } from '../pages/process-list.page'; import { ProcessListPage } from '../pages/process-list.page';
import { ProcessDetailsPage } from '../pages/process-details.page'; import { ProcessDetailsPage } from '../pages/process-details.page';
import { AppDefinitionRepresentation, ProcessInstanceRepresentation, ProcessInstancesApi } from '@alfresco/js-api'; import { AppDefinitionRepresentation, ProcessInstanceRepresentation, ProcessInstancesApi } from '@alfresco/js-api';
import { DateFnsUtils } from '../../../lib/core/src/lib/common/utils/date-fns-utils'; import { format } from 'date-fns';
describe('Process Instance Details', () => { describe('Process Instance Details', () => {
const app = browser.params.resources.Files.SIMPLE_APP_WITH_USER_FORM; const app = browser.params.resources.Files.SIMPLE_APP_WITH_USER_FORM;
@@ -45,8 +45,6 @@ describe('Process Instance Details', () => {
let process: ProcessInstanceRepresentation; let process: ProcessInstanceRepresentation;
let user: UserModel; let user: UserModel;
const PROCESS_DATE_FORMAT = 'll';
beforeAll(async () => { beforeAll(async () => {
await apiService.loginWithProfile('admin'); await apiService.loginWithProfile('admin');
@@ -76,6 +74,10 @@ describe('Process Instance Details', () => {
it('[C307031] Should display the created date in the default format', async () => { it('[C307031] Should display the created date in the default format', async () => {
await processDetailsPage.checkProcessHeaderDetailsAreVisible(); await processDetailsPage.checkProcessHeaderDetailsAreVisible();
await expect(await processDetailsPage.getCreated()).toEqual(DateFnsUtils.formatDate(process.started, PROCESS_DATE_FORMAT));
const created = await processDetailsPage.getCreated();
const expected = format(process.started, 'PP');
expect(created).toEqual(expected);
}); });
}); });

View File

@@ -7,5 +7,8 @@
"C216430": "https://alfresco.atlassian.net/browse/ACS-4595", "C216430": "https://alfresco.atlassian.net/browse/ACS-4595",
"C280063": "https://alfresco.atlassian.net/browse/ACS-4595", "C280063": "https://alfresco.atlassian.net/browse/ACS-4595",
"C280064": "https://alfresco.atlassian.net/browse/ACS-4595", "C280064": "https://alfresco.atlassian.net/browse/ACS-4595",
"C313200": "https://alfresco.atlassian.net/browse/APPS-2234" "C313200": "https://alfresco.atlassian.net/browse/APPS-2234",
"C311318-3": "https://alfresco.atlassian.net/browse/APPS-2254",
"C311319-2": "https://alfresco.atlassian.net/browse/APPS-2254",
"C311319-4": "https://alfresco.atlassian.net/browse/APPS-2254"
} }

View File

@@ -15,30 +15,18 @@
* limitations under the License. * limitations under the License.
*/ */
import { import { BrowserActions, DataTableComponentPage, DateUtil, LoginPage } from '@alfresco/adf-testing';
BrowserActions,
DataTableComponentPage,
DatePickerCalendarPage,
DateUtil,
LocalStorageUtil,
LoginPage
} from '@alfresco/adf-testing';
import { browser, ElementFinder } from 'protractor'; import { browser, ElementFinder } from 'protractor';
import { SearchBarPage } from '../pages/search-bar.page'; import { SearchBarPage } from '../pages/search-bar.page';
import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
import { SearchFiltersPage } from '../pages/search-filters.page'; import { SearchFiltersPage } from '../pages/search-filters.page';
import { SearchResultsPage } from '../pages/search-results.page'; import { SearchResultsPage } from '../pages/search-results.page';
import { SearchConfiguration } from '../search.config';
describe('Search Date Range Filter', () => { describe('Search Date Range Filter', () => {
const loginPage = new LoginPage(); const loginPage = new LoginPage();
const searchBarPage = new SearchBarPage(); const searchBarPage = new SearchBarPage();
const searchFilters = new SearchFiltersPage(); const searchFilters = new SearchFiltersPage();
const dateRangeFilter = searchFilters.createdDateRangeFilterPage(); const dateRangeFilter = searchFilters.createdDateRangeFilterPage();
const searchResults = new SearchResultsPage(); const searchResults = new SearchResultsPage();
const datePicker = new DatePickerCalendarPage();
const navigationBar = new NavigationBarPage();
const dataTable = new DataTableComponentPage(); const dataTable = new DataTableComponentPage();
beforeAll(async () => { beforeAll(async () => {
@@ -60,29 +48,6 @@ describe('Search Date Range Filter', () => {
await browser.refresh(); await browser.refresh();
}); });
it('[C277106] Should display default values for Date Range widget', async () => {
await dateRangeFilter.checkFromFieldIsDisplayed();
await dateRangeFilter.checkFromDateToggleIsDisplayed();
await dateRangeFilter.checkToFieldIsDisplayed();
await dateRangeFilter.checkToDateToggleIsDisplayed();
await dateRangeFilter.checkApplyButtonIsDisplayed();
await dateRangeFilter.checkApplyButtonIsDisabled();
await dateRangeFilter.checkClearButtonIsDisplayed();
});
it('[C277104] Should be able to set dates using date pickers', async () => {
await dateRangeFilter.checkFromDateToggleIsDisplayed();
const fromDatePicker = await dateRangeFilter.openFromDatePicker();
await fromDatePicker.selectTodayDate();
await expect(await dateRangeFilter.getFromDate()).toEqual(await dateRangeFilter.getFromCalendarSelectedDate());
});
it('[C277105] Should be able to type a date', async () => {
const date = '01-May-18';
await dateRangeFilter.putFromDate(date);
await expect(await dateRangeFilter.getFromCalendarSelectedDate()).toEqual(await dateRangeFilter.getFromDate());
});
it('[C277119] FROM and TO dates should depend on each other', async () => { it('[C277119] FROM and TO dates should depend on each other', async () => {
await dateRangeFilter.checkFromDateToggleIsDisplayed(); await dateRangeFilter.checkFromDateToggleIsDisplayed();
const fromDatePicker = await dateRangeFilter.openFromDatePicker(); const fromDatePicker = await dateRangeFilter.openFromDatePicker();
@@ -129,7 +94,7 @@ describe('Search Date Range Filter', () => {
await searchResults.sortByCreated('ASC'); await searchResults.sortByCreated('ASC');
const results = await dataTable.geCellElementDetail('Created') as ElementFinder[]; const results = (await dataTable.geCellElementDetail('Created')) as ElementFinder[];
for (const currentResult of results) { for (const currentResult of results) {
const currentDate = await BrowserActions.getAttribute(currentResult, 'title'); const currentDate = await BrowserActions.getAttribute(currentResult, 'title');
const currentDateFormatted = DateUtil.parse(currentDate, 'MMM DD, YYYY, h:mm:ss a'); const currentDateFormatted = DateUtil.parse(currentDate, 'MMM DD, YYYY, h:mm:ss a');
@@ -138,66 +103,4 @@ describe('Search Date Range Filter', () => {
await expect(currentDateFormatted >= DateUtil.parse(fromDate, 'DD-MM-YY')).toBe(true); await expect(currentDateFormatted >= DateUtil.parse(fromDate, 'DD-MM-YY')).toBe(true);
} }
}); });
it('[C277108] Should display a warning message when user doesn\'t set the date range at all', async () => {
await dateRangeFilter.checkFromFieldIsDisplayed();
await dateRangeFilter.clickFromField();
await dateRangeFilter.clickToField();
await dateRangeFilter.checkFromErrorMessageIsDisplayed('Required value');
await dateRangeFilter.clickFromField();
await dateRangeFilter.checkToErrorMessageIsDisplayed('Required value');
});
it('[C277114] Should display warning message if user doesn\'t set the date range properly', async () => {
const toDate = '01-May-18';
const fromDate = '16-May-18';
await dateRangeFilter.checkToFieldIsDisplayed();
await dateRangeFilter.putToDate(toDate);
await dateRangeFilter.checkFromFieldIsDisplayed();
await dateRangeFilter.putFromDate(fromDate);
await dateRangeFilter.clickFromField();
await dateRangeFilter.checkToErrorMessageIsDisplayed('No days selected.');
});
it('[C277115] Should display warning message if user types a date later than today\'s date', async () => {
await dateRangeFilter.checkFromFieldIsDisplayed();
await dateRangeFilter.putFromDate(DateUtil.formatDate('DD-MMM-YY', new Date(), 1));
await dateRangeFilter.checkFromErrorMessageIsDisplayed('The date is beyond the maximum date.');
});
it('[C277108] Should display a warning message when user doesn\'t set the date range at all', async () => {
await dateRangeFilter.checkFromFieldIsDisplayed();
await dateRangeFilter.putFromDate('Wrong Format');
await dateRangeFilter.clickToField();
await dateRangeFilter.checkFromErrorMessageIsDisplayed('Invalid date. The date must be in the format \'DD-MMM-YY\'');
await dateRangeFilter.putFromDate('01-May-18');
await dateRangeFilter.checkFromErrorMessageIsNotDisplayed();
});
describe('configuration change', () => {
it('[C277117] Should be able to change date format', async () => {
await navigationBar.navigateToContentServices();
const jsonFile= SearchConfiguration.getConfiguration();
jsonFile.categories[4].component.settings.dateFormat = 'MM-DD-YY';
await LocalStorageUtil.setConfigField('search', JSON.stringify(jsonFile));
await searchBarPage.clickOnSearchIcon();
await searchBarPage.enterTextAndPressEnter('*');
await searchResults.dataTable.waitTillContentLoaded();
await searchFilters.checkCreatedRangeFilterIsDisplayed();
await searchFilters.clickCreatedRangeFilterHeader();
await searchFilters.checkCreatedRangeFilterIsExpanded();
await dateRangeFilter.checkFromFieldIsDisplayed();
await dateRangeFilter.openFromDatePicker();
const todayDate = DateUtil.formatDate('MM-DD-YY');
await datePicker.selectTodayDate();
await expect(await dateRangeFilter.getFromDate()).toEqual(todayDate);
});
});
}); });

View File

@@ -16,22 +16,19 @@
*/ */
import { SearchDateRangeComponent } from './search-date-range.component'; import { SearchDateRangeComponent } from './search-date-range.component';
import { DateAdapter } from '@angular/material/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ContentTestingModule } from '../../../testing/content.testing.module'; import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { MomentDateAdapter } from '@angular/material-moment-adapter'; import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { startOfDay, endOfDay, isValid, addDays, format } from 'date-fns';
declare let moment: any;
describe('SearchDateRangeComponent', () => { describe('SearchDateRangeComponent', () => {
let fixture: ComponentFixture<SearchDateRangeComponent>; let fixture: ComponentFixture<SearchDateRangeComponent>;
let component: SearchDateRangeComponent; let component: SearchDateRangeComponent;
let adapter: MomentDateAdapter;
const fromDate = '2016-10-16'; const dateFormatFixture = 'dd-MMM-yy';
const toDate = '2017-10-16'; const fromDate = new Date('2016-10-16');
const maxDate = '10-Mar-20'; const toDate = new Date('2017-10-16');
const dateFormatFixture = 'DD-MMM-YY';
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
@@ -41,7 +38,6 @@ describe('SearchDateRangeComponent', () => {
] ]
}); });
fixture = TestBed.createComponent(SearchDateRangeComponent); fixture = TestBed.createComponent(SearchDateRangeComponent);
adapter = fixture.debugElement.injector.get(DateAdapter) as MomentDateAdapter;
component = fixture.componentInstance; component = fixture.componentInstance;
}); });
@@ -59,31 +55,26 @@ describe('SearchDateRangeComponent', () => {
component.settings = { field: 'cm:created', dateFormat: dateFormatFixture }; component.settings = { field: 'cm:created', dateFormat: dateFormatFixture };
fixture.detectChanges(); fixture.detectChanges();
const inputString = '20-feb-18'; const date = new Date('20-feb-18');
const momentFromInput = moment(inputString, dateFormatFixture); expect(isValid(date)).toBeTrue();
expect(momentFromInput.isValid()).toBeTruthy(); component.onChangedHandler({ value: date } as MatDatepickerInputEvent<Date>, component.from);
expect(component.from.value.toString()).toEqual(date.toString());
component.onChangedHandler({ value: inputString }, component.from);
expect(component.from.value.toString()).toEqual(momentFromInput.toString());
}); });
it('should NOT setup form control with invalid date on change', () => { it('should NOT setup form control with invalid date on change', () => {
component.settings = { field: 'cm:created', dateFormat: dateFormatFixture }; component.settings = { field: 'cm:created', dateFormat: dateFormatFixture };
fixture.detectChanges(); fixture.detectChanges();
const inputString = '20.f.18'; const date = new Date('20.f.18');
const momentFromInput = moment(inputString, dateFormatFixture); expect(isValid(date)).toBeFalse();
expect(momentFromInput.isValid()).toBeFalsy(); component.onChangedHandler({ value: date } as MatDatepickerInputEvent<Date>, component.from);
expect(component.from.value).not.toEqual(date);
component.onChangedHandler({ value: inputString }, component.from);
expect(component.from.value.toString()).not.toEqual(momentFromInput.toString());
}); });
it('should reset form', () => { it('should reset form', () => {
fixture.detectChanges(); fixture.detectChanges();
component.form.setValue({ from: fromDate, to: toDate }); component.form.setValue({ from: fromDate, to: toDate });
@@ -92,9 +83,9 @@ describe('SearchDateRangeComponent', () => {
component.reset(); component.reset();
expect(component.from.value).toEqual(''); expect(component.from.value).toBeNull();
expect(component.to.value).toEqual(''); expect(component.to.value).toBeNull();
expect(component.form.value).toEqual({ from: '', to: '' }); expect(component.form.value).toEqual({ from: null, to: null });
}); });
it('should reset fromMaxDate on reset', () => { it('should reset fromMaxDate on reset', () => {
@@ -143,8 +134,8 @@ describe('SearchDateRangeComponent', () => {
to: toDate to: toDate
}, true); }, true);
const startDate = moment(fromDate).startOf('day').format(); const startDate = startOfDay(fromDate).toISOString();
const endDate = moment(toDate).endOf('day').format(); const endDate = endOfDay(toDate).toISOString();
const expectedQuery = `cm:created:['${startDate}' TO '${endDate}']`; const expectedQuery = `cm:created:['${startDate}' TO '${endDate}']`;
@@ -156,7 +147,7 @@ describe('SearchDateRangeComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const input = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]'); const input = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]');
input.value = '10-05-18'; input.value = '10-f-18';
input.dispatchEvent(new Event('input')); input.dispatchEvent(new Event('input'));
fixture.detectChanges(); fixture.detectChanges();
@@ -165,11 +156,82 @@ describe('SearchDateRangeComponent', () => {
expect(component.getFromValidationMessage()).toEqual('SEARCH.FILTER.VALIDATION.INVALID-DATE'); expect(component.getFromValidationMessage()).toEqual('SEARCH.FILTER.VALIDATION.INVALID-DATE');
}); });
it('should hide date-format error when correcting input', async () => {
fixture.detectChanges();
const input = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]');
input.value = '10-f-18';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
expect(component.getFromValidationMessage()).toEqual('SEARCH.FILTER.VALIDATION.INVALID-DATE');
input.value = '10-10-2018';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
expect(component.getFromValidationMessage()).toEqual('');
});
it('should show error for max date constraint', async () => {
component.settings = { field: 'cm:created', maxDate: 'today' };
fixture.detectChanges();
const input = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]');
input.value = format(addDays(new Date(), 1), 'dd-MM-yyyy');
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
expect(component.getFromValidationMessage()).toEqual('SEARCH.FILTER.VALIDATION.BEYOND-MAX-DATE');
});
it('should show error for required constraint', async () => {
fixture.detectChanges();
const fromInput = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]');
fromInput.value = '';
fromInput.dispatchEvent(new Event('input'));
const toInput = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-to-input"]');
toInput.value = '';
toInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
expect(component.getFromValidationMessage()).toEqual('SEARCH.FILTER.VALIDATION.REQUIRED-VALUE');
expect(component.getToValidationMessage()).toEqual('SEARCH.FILTER.VALIDATION.REQUIRED-VALUE');
});
it('should show error for incorrect date range', async () => {
fixture.detectChanges();
const fromInput = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]');
fromInput.value = '11-10-2018';
fromInput.dispatchEvent(new Event('input'));
const toInput = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-to-input"]');
toInput.value = '10-10-2018';
toInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
expect(component.getFromValidationMessage()).toEqual('');
expect(component.getToValidationMessage()).toEqual('SEARCH.FILTER.VALIDATION.NO-DAYS');
});
it('should not show date-format error when valid found', async () => { it('should not show date-format error when valid found', async () => {
fixture.detectChanges(); fixture.detectChanges();
const input = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]'); const input = fixture.debugElement.nativeElement.querySelector('[data-automation-id="date-range-from-input"]');
input.value = '10/10/2018'; input.value = '10-10-2018';
input.dispatchEvent(new Event('input')); input.dispatchEvent(new Event('input'));
fixture.detectChanges(); fixture.detectChanges();
@@ -182,31 +244,22 @@ describe('SearchDateRangeComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
expect(fixture.debugElement.nativeElement.querySelector('input[ng-reflect-max]')).toBeNull(); expect(component.maxDate).toBeUndefined();
}); });
it('should be able to set a fixed maximum date', async () => { it('should be able to set a fixed maximum date', async () => {
component.settings = { field: 'cm:created', dateFormat: dateFormatFixture, maxDate }; component.settings = { field: 'cm:created', dateFormat: dateFormatFixture, maxDate: '10-Mar-20' };
fixture.detectChanges(); fixture.detectChanges();
const inputs = fixture.debugElement.nativeElement.querySelectorAll('input[ng-reflect-max="Tue Mar 10 2020 23:59:59 GMT+0"]'); const expected = endOfDay(new Date(2020, 2, 10));
expect(component.maxDate).toEqual(expected);
expect(inputs[0]).toBeDefined();
expect(inputs[0]).not.toBeNull();
expect(inputs[1]).toBeDefined();
expect(inputs[1]).not.toBeNull();
}); });
it('should be able to set the maximum date to today', async () => { it('should be able to set the maximum date to today', async () => {
component.settings = { field: 'cm:created', dateFormat: dateFormatFixture, maxDate: 'today' }; component.settings = { field: 'cm:created', dateFormat: dateFormatFixture, maxDate: 'today' };
fixture.detectChanges(); fixture.detectChanges();
const today = adapter.today().endOf('day').toString().slice(0, -3); const today = endOfDay(new Date());
const inputs = fixture.debugElement.nativeElement.querySelectorAll('input[ng-reflect-max="' + today + '"]'); expect(component.maxDate).toEqual(today);
expect(inputs[0]).toBeDefined();
expect(inputs[0]).not.toBeNull();
expect(inputs[1]).toBeDefined();
expect(inputs[1]).not.toBeNull();
}); });
}); });

View File

@@ -15,60 +15,60 @@
* limitations under the License. * limitations under the License.
*/ */
import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms'; import { FormControl, FormGroup, Validators } from '@angular/forms';
import { DateAdapter } from '@angular/material/core'; import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import { MomentDateAdapter, UserPreferencesService, UserPreferenceValues } from '@alfresco/adf-core'; import { ADF_DATE_FORMATS, AdfDateFnsAdapter } from '@alfresco/adf-core';
import { SearchWidget } from '../../models/search-widget.interface'; import { SearchWidget } from '../../models/search-widget.interface';
import { SearchWidgetSettings } from '../../models/search-widget-settings.interface'; import { SearchWidgetSettings } from '../../models/search-widget-settings.interface';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service'; import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
import { LiveErrorStateMatcher } from '../../forms/live-error-state-matcher'; import { LiveErrorStateMatcher } from '../../forms/live-error-state-matcher';
import { Moment } from 'moment';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators'; import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter'; import { startOfDay, endOfDay, isBefore, isValid as isValidDate } from 'date-fns';
export interface DateRangeValue { export interface DateRangeValue {
from: string; from: string;
to: string; to: string;
} }
declare let moment: any;
const DEFAULT_FORMAT_DATE: string = 'DD/MM/YYYY'; const DEFAULT_FORMAT_DATE: string = 'DD/MM/YYYY';
interface DateRangeForm {
from: FormControl<Date>;
to: FormControl<Date>;
}
@Component({ @Component({
selector: 'adf-search-date-range', selector: 'adf-search-date-range',
templateUrl: './search-date-range.component.html', templateUrl: './search-date-range.component.html',
styleUrls: ['./search-date-range.component.scss'], styleUrls: ['./search-date-range.component.scss'],
providers: [ providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter }, { provide: MAT_DATE_FORMATS, useValue: ADF_DATE_FORMATS },
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { strict: true } } { provide: DateAdapter, useClass: AdfDateFnsAdapter }
], ],
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,
host: { class: 'adf-search-date-range' } host: { class: 'adf-search-date-range' }
}) })
export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy { export class SearchDateRangeComponent implements SearchWidget, OnInit {
from: FormControl; from: FormControl<Date>;
to: FormControl; to: FormControl<Date>;
form: FormGroup; form: FormGroup<DateRangeForm>;
matcher = new LiveErrorStateMatcher(); matcher = new LiveErrorStateMatcher();
id: string; id: string;
settings?: SearchWidgetSettings; settings?: SearchWidgetSettings;
context?: SearchQueryBuilderService; context?: SearchQueryBuilderService;
datePickerFormat: string; datePickerFormat: string;
maxDate: any; maxDate: Date;
fromMaxDate: any; fromMaxDate: Date;
isActive = false; isActive = false;
startValue: any; startValue: any;
enableChangeUpdate: boolean; enableChangeUpdate: boolean;
displayValue$: Subject<string> = new Subject<string>(); displayValue$ = new Subject<string>();
private onDestroy$ = new Subject<boolean>(); constructor(private dateAdapter: DateAdapter<Date>) {}
constructor(private dateAdapter: DateAdapter<Moment>, private userPreferencesService: UserPreferencesService) {}
getFromValidationMessage(): string { getFromValidationMessage(): string {
return this.from.hasError('invalidOnChange') || this.hasParseError(this.from) return this.from.hasError('invalidOnChange') || this.hasParseError(this.from)
@@ -95,21 +95,16 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
ngOnInit() { ngOnInit() {
this.datePickerFormat = this.settings?.dateFormat ? this.settings.dateFormat : DEFAULT_FORMAT_DATE; this.datePickerFormat = this.settings?.dateFormat ? this.settings.dateFormat : DEFAULT_FORMAT_DATE;
this.userPreferencesService const customDateAdapter = this.dateAdapter as AdfDateFnsAdapter;
.select<string>(UserPreferenceValues.Locale) customDateAdapter.displayFormat = this.datePickerFormat;
.pipe(takeUntil(this.onDestroy$))
.subscribe((locale) => this.setLocale(locale));
const customDateAdapter = this.dateAdapter as MomentDateAdapter;
customDateAdapter.overrideDisplayFormat = this.datePickerFormat;
const validators = Validators.compose([Validators.required]); const validators = Validators.compose([Validators.required]);
if (this.settings?.maxDate) { if (this.settings?.maxDate) {
if (this.settings.maxDate === 'today') { if (this.settings.maxDate === 'today') {
this.maxDate = this.dateAdapter.today().endOf('day'); this.maxDate = endOfDay(this.dateAdapter.today());
} else { } else {
this.maxDate = moment(this.settings.maxDate).endOf('day'); this.maxDate = endOfDay(this.dateAdapter.parse(this.settings.maxDate, this.datePickerFormat));
} }
} }
@@ -120,8 +115,8 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
this.from = new FormControl(fromValue, validators); this.from = new FormControl(fromValue, validators);
this.to = new FormControl(toValue, validators); this.to = new FormControl(toValue, validators);
} else { } else {
this.from = new FormControl('', validators); this.from = new FormControl(null, validators);
this.to = new FormControl('', validators); this.to = new FormControl(null, validators);
} }
this.form = new FormGroup({ this.form = new FormGroup({
@@ -133,17 +128,12 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
this.enableChangeUpdate = this.settings?.allowUpdateOnChange ?? true; this.enableChangeUpdate = this.settings?.allowUpdateOnChange ?? true;
} }
ngOnDestroy() { apply(model: Partial<{ from: Date; to: Date }>, isValid: boolean) {
this.onDestroy$.next(true);
this.onDestroy$.complete();
}
apply(model: { from: string; to: string }, isValid: boolean) {
if (isValid && this.id && this.context && this.settings && this.settings.field) { if (isValid && this.id && this.context && this.settings && this.settings.field) {
this.isActive = true; this.isActive = true;
const start = moment(model.from).startOf('day').format(); const start = startOfDay(model.from).toISOString();
const end = moment(model.to).endOf('day').format(); const end = endOfDay(model.to).toISOString();
this.context.queryFragments[this.id] = `${this.settings.field}:['${start}' TO '${end}']`; this.context.queryFragments[this.id] = `${this.settings.field}:['${start}' TO '${end}']`;
@@ -192,11 +182,12 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
this.to.markAsTouched(); this.to.markAsTouched();
this.submitValues(); this.submitValues();
} }
clear() { clear() {
this.isActive = false; this.isActive = false;
this.form.reset({ this.form.reset({
from: '', from: null,
to: '' to: null
}); });
if (this.id && this.context) { if (this.id && this.context) {
@@ -205,6 +196,7 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
this.updateQuery(); this.updateQuery();
} }
} }
this.setFromMaxDate(); this.setFromMaxDate();
} }
@@ -220,12 +212,12 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
} }
} }
onChangedHandler(event: any, formControl: FormControl) { onChangedHandler(event: MatDatepickerInputEvent<Date>, formControl: FormControl) {
const inputValue = event.value; const inputValue = event.value;
const formatDate = this.dateAdapter.parse(inputValue, this.datePickerFormat);
if (formatDate?.isValid()) { if (isValidDate(inputValue)) {
formControl.setValue(formatDate); formControl.setValue(inputValue);
} else if (formatDate) { } else if (inputValue) {
formControl.setErrors({ formControl.setErrors({
invalidOnChange: true invalidOnChange: true
}); });
@@ -234,11 +226,6 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
this.setFromMaxDate(); this.setFromMaxDate();
} }
setLocale(locale: string) {
this.dateAdapter.setLocale(locale);
moment.locale(locale);
}
hasParseError(formControl: FormControl): boolean { hasParseError(formControl: FormControl): boolean {
return formControl.hasError('matDatepickerParse') && formControl.getError('matDatepickerParse').text; return formControl.hasError('matDatepickerParse') && formControl.getError('matDatepickerParse').text;
} }
@@ -248,6 +235,6 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
} }
setFromMaxDate() { setFromMaxDate() {
this.fromMaxDate = !this.to.value || (this.maxDate && moment(this.maxDate).isBefore(this.to.value)) ? this.maxDate : moment(this.to.value); this.fromMaxDate = !this.to.value || (this.maxDate && isBefore(this.maxDate, this.to.value)) ? this.maxDate : this.to.value;
} }
} }

View File

@@ -1,4 +1,4 @@
<label for="adf-dateRange" >{{field.nameKey | translate}}</label><br> <label for="adf-dateRange">{{field.nameKey | translate}}</label><br />
<div id="adf-dateRange" [formGroup]="dateRange"> <div id="adf-dateRange" [formGroup]="dateRange">
<small *ngIf="isStartDateGreaterThanEndDate()" class="adf-date-range-analytics-text-danger"> <small *ngIf="isStartDateGreaterThanEndDate()" class="adf-date-range-analytics-text-danger">
{{'DATE-WIDGET.MESSAGES.START-LESS-THAN-END-DATE' | translate}} {{'DATE-WIDGET.MESSAGES.START-LESS-THAN-END-DATE' | translate}}
@@ -16,18 +16,16 @@
[max]="maxDate" [max]="maxDate"
formControlName="startDate" formControlName="startDate"
[matDatepicker]="startDate" [matDatepicker]="startDate"
[value]="startDatePicker" [value]="startDateValue"
(keydown)="true" (keydown)="true"
(dateChange)="onGroupValueChanged()" (dateChange)="onGroupValueChanged()"
placeholder="{{'DATE-WIDGET.START-DATE' | translate}}" placeholder="{{'DATE-WIDGET.START-DATE' | translate}}"
id="startDate_id" id="startDate_id"
required> required
/>
<mat-datepicker-toggle matSuffix [for]="startDate"></mat-datepicker-toggle> <mat-datepicker-toggle matSuffix [for]="startDate"></mat-datepicker-toggle>
</mat-form-field> </mat-form-field>
<mat-datepicker <mat-datepicker #startDate [touchUi]="true"></mat-datepicker>
#startDate
[touchUi]="true">
</mat-datepicker>
</mat-grid-tile> </mat-grid-tile>
<mat-grid-tile> <mat-grid-tile>
<mat-form-field> <mat-form-field>
@@ -37,18 +35,16 @@
[max]="maxDate" [max]="maxDate"
formControlName="endDate" formControlName="endDate"
[matDatepicker]="endDate" [matDatepicker]="endDate"
[value]="endDatePicker" [value]="endDateValue"
(keydown)="true" (keydown)="true"
(dateChange)="onGroupValueChanged()" (dateChange)="onGroupValueChanged()"
placeholder="{{'DATE-WIDGET.END-DATE' | translate}}" placeholder="{{'DATE-WIDGET.END-DATE' | translate}}"
id="endDate_id" id="endDate_id"
required> required
/>
<mat-datepicker-toggle matSuffix [for]="endDate"></mat-datepicker-toggle> <mat-datepicker-toggle matSuffix [for]="endDate"></mat-datepicker-toggle>
</mat-form-field> </mat-form-field>
<mat-datepicker <mat-datepicker #endDate [touchUi]="true"></mat-datepicker>
#endDate
[touchUi]="true">
</mat-datepicker>
</mat-grid-tile> </mat-grid-tile>
</mat-grid-list> </mat-grid-list>
</div> </div>

View File

@@ -0,0 +1,97 @@
/*!
* @license
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DateRangeWidgetComponent } from './date-range.widget';
import { TranslateModule } from '@ngx-translate/core';
import { InsightsTestingModule } from '../../../../testing/insights.testing.module';
import { ReportParameterDetailsModel } from '../../../../diagram/models/report/report-parameter-details.model';
import { format } from 'date-fns';
describe('DateRangeWidgetComponent', () => {
let fixture: ComponentFixture<DateRangeWidgetComponent>;
let widget: DateRangeWidgetComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
InsightsTestingModule
]
});
fixture = TestBed.createComponent(DateRangeWidgetComponent);
widget = fixture.componentInstance;
});
it('should init the start date and end date from the field model', async () => {
const field = new ReportParameterDetailsModel({
value: {
startDate: '2023-03-13',
endDate: '2023-04-14'
}
});
widget.field = field;
fixture.detectChanges();
await fixture.whenStable();
expect(format(widget.startDateValue, 'yyyy-MM-dd')).toEqual('2023-03-13');
expect(format(widget.endDateValue, 'yyyy-MM-dd')).toEqual('2023-04-14');
});
it('should emit dateRangeChanged with empty time/zone', async () => {
const field = new ReportParameterDetailsModel({
value: {
startDate: '2023-03-13',
endDate: '2023-04-14'
}
});
widget.field = field;
fixture.detectChanges();
await fixture.whenStable();
expect(widget.dateRange.valid).toBeTrue();
let emitted: { startDate: string; endDate: string };
widget.dateRangeChanged.subscribe((value) => emitted = value);
widget.onGroupValueChanged();
expect(emitted.startDate).toBe('2023-03-13T00:00:00.000Z');
expect(emitted.endDate).toBe('2023-04-14T00:00:00.000Z');
});
it('should validate date range', async () => {
const field = new ReportParameterDetailsModel({
value: {
startDate: '2023-03-13',
endDate: '2023-01-14'
}
});
widget.field = field;
fixture.detectChanges();
await fixture.whenStable();
expect(widget.dateRange.valid).toBeFalse();
});
});

View File

@@ -17,70 +17,71 @@
/* eslint-disable @angular-eslint/no-input-rename */ /* eslint-disable @angular-eslint/no-input-rename */
import { MOMENT_DATE_FORMATS, MomentDateAdapter, UserPreferencesService, UserPreferenceValues } from '@alfresco/adf-core'; import { ADF_DATE_FORMATS, AdfDateFnsAdapter } from '@alfresco/adf-core';
import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation, OnDestroy } from '@angular/core'; import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core';
import { AbstractControl, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { FormControl, FormGroup, Validators } from '@angular/forms';
import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core'; import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import moment, { Moment } from 'moment'; import { ReportParameterDetailsModel } from '../../../../diagram/models/report/report-parameter-details.model';
import { Subject } from 'rxjs'; import { isAfter } from 'date-fns';
import { takeUntil } from 'rxjs/operators';
const FORMAT_DATE_ACTIVITI = 'YYYY-MM-DD'; const FORMAT_DATE_ACTIVITI = 'yyyy-MM-dd';
const SHOW_FORMAT = 'DD/MM/YYYY'; const DISPLAY_FORMAT = 'dd/MM/yyyy';
interface DateRangeProps {
startDate: FormControl<Date>;
endDate: FormControl<Date>;
}
@Component({ @Component({
selector: 'adf-date-range-widget', selector: 'adf-date-range-widget',
templateUrl: './date-range.widget.html', templateUrl: './date-range.widget.html',
styleUrls: ['./date-range.widget.scss'], styleUrls: ['./date-range.widget.scss'],
providers: [ providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter }, { provide: DateAdapter, useClass: AdfDateFnsAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MOMENT_DATE_FORMATS } { provide: MAT_DATE_FORMATS, useValue: ADF_DATE_FORMATS }
], ],
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None
}) })
export class DateRangeWidgetComponent implements OnInit, OnDestroy { export class DateRangeWidgetComponent implements OnInit {
@Input('group') @Input('group')
dateRange: UntypedFormGroup; dateRange: FormGroup<DateRangeProps>;
@Input() @Input()
field: any; field: ReportParameterDetailsModel;
@Output() @Output()
dateRangeChanged = new EventEmitter<any>(); dateRangeChanged = new EventEmitter<{ startDate: string; endDate: string }>();
minDate: Moment; minDate: Date;
maxDate: Moment; maxDate: Date;
startDatePicker: Moment = moment(); startDateValue = new Date();
endDatePicker: Moment = moment(); endDateValue = new Date();
private onDestroy$ = new Subject<boolean>(); constructor(private dateAdapter: DateAdapter<Date>) {}
constructor(private dateAdapter: DateAdapter<Moment>, private userPreferencesService: UserPreferencesService) {}
ngOnInit() { ngOnInit() {
this.userPreferencesService const momentDateAdapter = this.dateAdapter as AdfDateFnsAdapter;
.select(UserPreferenceValues.Locale) momentDateAdapter.displayFormat = DISPLAY_FORMAT;
.pipe(takeUntil(this.onDestroy$))
.subscribe((locale) => this.dateAdapter.setLocale(locale));
const momentDateAdapter = this.dateAdapter as MomentDateAdapter;
momentDateAdapter.overrideDisplayFormat = SHOW_FORMAT;
if (this.field) { if (this.field) {
if (this.field.value?.startDate) { if (this.field.value?.startDate) {
this.startDatePicker = moment(this.field.value.startDate, FORMAT_DATE_ACTIVITI); this.startDateValue = this.dateAdapter.parse(this.field.value.startDate, FORMAT_DATE_ACTIVITI);
} }
if (this.field.value?.endDate) { if (this.field.value?.endDate) {
this.endDatePicker = moment(this.field.value.endDate, FORMAT_DATE_ACTIVITI); this.endDateValue = this.dateAdapter.parse(this.field.value.endDate, FORMAT_DATE_ACTIVITI);
} }
} }
const startDateControl = new UntypedFormControl(this.startDatePicker); if (!this.dateRange) {
this.dateRange = new FormGroup({} as any);
}
const startDateControl = new FormControl<Date>(this.startDateValue);
startDateControl.setValidators(Validators.required); startDateControl.setValidators(Validators.required);
this.dateRange.addControl('startDate', startDateControl); this.dateRange.addControl('startDate', startDateControl);
const endDateControl = new UntypedFormControl(this.endDatePicker); const endDateControl = new FormControl<Date>(this.endDateValue);
endDateControl.setValidators(Validators.required); endDateControl.setValidators(Validators.required);
this.dateRange.addControl('endDate', endDateControl); this.dateRange.addControl('endDate', endDateControl);
@@ -88,27 +89,24 @@ export class DateRangeWidgetComponent implements OnInit, OnDestroy {
this.dateRange.valueChanges.subscribe(() => this.onGroupValueChanged()); this.dateRange.valueChanges.subscribe(() => this.onGroupValueChanged());
} }
ngOnDestroy() {
this.onDestroy$.next(true);
this.onDestroy$.complete();
}
onGroupValueChanged() { onGroupValueChanged() {
if (this.dateRange.valid) { if (this.dateRange.valid) {
const dateStart = this.convertToMomentDateWithTime(this.dateRange.controls.startDate.value); const dateStart = this.formatDateTime(this.dateRange.controls.startDate.value);
const endStart = this.convertToMomentDateWithTime(this.dateRange.controls.endDate.value); const endStart = this.formatDateTime(this.dateRange.controls.endDate.value);
this.dateRangeChanged.emit({ startDate: dateStart, endDate: endStart }); this.dateRangeChanged.emit({ startDate: dateStart, endDate: endStart });
} }
} }
convertToMomentDateWithTime(date: string) { private formatDateTime(date: Date) {
return moment(date, FORMAT_DATE_ACTIVITI, true).format(FORMAT_DATE_ACTIVITI) + 'T00:00:00.000Z'; const datePart = this.dateAdapter.format(date, FORMAT_DATE_ACTIVITI);
return `${datePart}T00:00:00.000Z`;
} }
dateCheck(formControl: AbstractControl) { dateCheck(formControl: FormGroup<DateRangeProps>) {
const startDate = moment(formControl.get('startDate').value); const startDate = formControl.get('startDate').value;
const endDate = moment(formControl.get('endDate').value); const endDate = formControl.get('endDate').value;
const isAfterCheck = startDate.isAfter(endDate); const isAfterCheck = isAfter(startDate, endDate);
return isAfterCheck ? { greaterThan: true } : null; return isAfterCheck ? { greaterThan: true } : null;
} }

View File

@@ -26,7 +26,7 @@ export class ReportParameterDetailsModel {
options: ParameterValueModel[]; options: ParameterValueModel[];
dependsOn: string; dependsOn: string;
constructor(obj?: any) { constructor(obj?: Partial<ReportParameterDetailsModel>) {
this.id = obj?.id; this.id = obj?.id;
this.name = obj?.name; this.name = obj?.name;
this.nameKey = obj?.nameKey; this.nameKey = obj?.nameKey;

View File

@@ -18,9 +18,14 @@
import { Component, Input, EventEmitter, Output, OnInit } from '@angular/core'; import { Component, Input, EventEmitter, Output, OnInit } from '@angular/core';
import { MatSelectChange } from '@angular/material/select'; import { MatSelectChange } from '@angular/material/select';
import { ProcessFilterProperties, ProcessFilterOptions } from '../../process/process-filters/models/process-filter-cloud.model'; import { ProcessFilterProperties, ProcessFilterOptions } from '../../process/process-filters/models/process-filter-cloud.model';
import { UntypedFormGroup, UntypedFormControl } from '@angular/forms'; import { FormGroup, FormControl } from '@angular/forms';
import { DateRangeFilter, DateCloudFilterType } from '../../models/date-cloud-filter.model'; import { DateRangeFilter, DateCloudFilterType } from '../../models/date-cloud-filter.model';
import { endOfDay, startOfDay } from 'date-fns'; import { endOfDay, isValid, startOfDay } from 'date-fns';
interface DateRangeFormProps {
from: FormControl<Date>;
to: FormControl<Date>;
}
@Component({ @Component({
selector: 'adf-cloud-date-range-filter', selector: 'adf-cloud-date-range-filter',
@@ -28,7 +33,6 @@ import { endOfDay, startOfDay } from 'date-fns';
templateUrl: './date-range-filter.component.html' templateUrl: './date-range-filter.component.html'
}) })
export class DateRangeFilterComponent implements OnInit { export class DateRangeFilterComponent implements OnInit {
@Input() @Input()
processFilterProperty: ProcessFilterProperties; processFilterProperty: ProcessFilterProperties;
@@ -43,9 +47,9 @@ import { endOfDay, startOfDay } from 'date-fns';
type: DateCloudFilterType; type: DateCloudFilterType;
filteredProperties: ProcessFilterOptions[] = []; filteredProperties: ProcessFilterOptions[] = [];
dateRangeForm = new UntypedFormGroup({ dateRangeForm = new FormGroup<DateRangeFormProps>({
from: new UntypedFormControl(), from: new FormControl(),
to: new UntypedFormControl() to: new FormControl()
}); });
ngOnInit() { ngOnInit() {
@@ -69,14 +73,17 @@ import { endOfDay, startOfDay } from 'date-fns';
} }
onDateRangeClosed() { onDateRangeClosed() {
const startDate = isValid(this.dateRangeForm.controls.from.value) ? startOfDay(this.dateRangeForm.controls.from.value).toISOString() : null;
const endDate = isValid(this.dateRangeForm.controls.to.value) ? endOfDay(this.dateRangeForm.controls.to.value).toISOString() : null;
const dateRange = { const dateRange = {
startDate: startOfDay(new Date(this.dateRangeForm.controls.from.value)).toISOString(), startDate,
endDate: endOfDay(new Date(this.dateRangeForm.controls.to.value)).toISOString() endDate
}; };
this.dateChanged.emit(dateRange); this.dateChanged.emit(dateRange);
} }
private hasPreselectedValues() { private hasPreselectedValues(): boolean {
return !!this.processFilterProperty?.attributes && !!this.processFilterProperty?.value; return !!this.processFilterProperty?.attributes && !!this.processFilterProperty?.value;
} }
@@ -94,7 +101,7 @@ import { endOfDay, startOfDay } from 'date-fns';
return this.processFilterProperty.attributes[key]; return this.processFilterProperty.attributes[key];
} }
private getFilterValue(attribute: string) { private getFilterValue<T = any>(attribute: string): T {
return this.processFilterProperty.value[attribute]; return this.processFilterProperty.value[attribute];
} }

View File

@@ -67,7 +67,7 @@
<input <input
matInput matInput
[formControlName]="processFilterProperty.key" [formControlName]="processFilterProperty.key"
(keyup)="onDateChanged($any($event).srcElement.value, processFilterProperty)" (keyup)="onDateChanged($any($event).target.value, processFilterProperty)"
(dateChange)="onDateChanged($event.value, processFilterProperty)" (dateChange)="onDateChanged($event.value, processFilterProperty)"
[matDatepicker]="dateController" [matDatepicker]="dateController"
placeholder="{{processFilterProperty.label | translate}}" placeholder="{{processFilterProperty.label | translate}}"

View File

@@ -30,7 +30,6 @@ import { ProcessFilterCloudModel } from '../models/process-filter-cloud.model';
import { ProcessFilterCloudService } from '../services/process-filter-cloud.service'; import { ProcessFilterCloudService } from '../services/process-filter-cloud.service';
import { AppsProcessCloudService } from '../../../app/services/apps-process-cloud.service'; import { AppsProcessCloudService } from '../../../app/services/apps-process-cloud.service';
import { fakeApplicationInstance, fakeApplicationInstanceWithEnvironment } from './../../../app/mock/app-model.mock'; import { fakeApplicationInstance, fakeApplicationInstanceWithEnvironment } from './../../../app/mock/app-model.mock';
import moment from 'moment';
import { PROCESS_FILTERS_SERVICE_TOKEN } from '../../../services/cloud-token.service'; import { PROCESS_FILTERS_SERVICE_TOKEN } from '../../../services/cloud-token.service';
import { LocalPreferenceCloudService } from '../../../services/local-preference-cloud.service'; import { LocalPreferenceCloudService } from '../../../services/local-preference-cloud.service';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
@@ -40,12 +39,13 @@ import { MatIconTestingModule } from '@angular/material/icon/testing';
import { ProcessDefinitionCloud } from '../../../models/process-definition-cloud.model'; import { ProcessDefinitionCloud } from '../../../models/process-definition-cloud.model';
import { mockAppVersions } from '../mock/process-filters-cloud.mock'; import { mockAppVersions } from '../mock/process-filters-cloud.mock';
import { fakeEnvironmentList } from '../../../common/mock/environment.mock'; import { fakeEnvironmentList } from '../../../common/mock/environment.mock';
import { endOfDay, format, startOfDay, subYears } from 'date-fns'; import { endOfDay, format, startOfDay, subYears, isValid } from 'date-fns';
describe('EditProcessFilterCloudComponent', () => { describe('EditProcessFilterCloudComponent', () => {
let component: EditProcessFilterCloudComponent; let component: EditProcessFilterCloudComponent;
let service: ProcessFilterCloudService; let service: ProcessFilterCloudService;
let fixture: ComponentFixture<EditProcessFilterCloudComponent>; let fixture: ComponentFixture<EditProcessFilterCloudComponent>;
let nativeElement: HTMLElement;
let dialog: MatDialog; let dialog: MatDialog;
let appsService: AppsProcessCloudService; let appsService: AppsProcessCloudService;
let processService: ProcessCloudService; let processService: ProcessCloudService;
@@ -89,6 +89,7 @@ describe('EditProcessFilterCloudComponent', () => {
}); });
fixture = TestBed.createComponent(EditProcessFilterCloudComponent); fixture = TestBed.createComponent(EditProcessFilterCloudComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
nativeElement = fixture.debugElement.nativeElement;
service = TestBed.inject(ProcessFilterCloudService); service = TestBed.inject(ProcessFilterCloudService);
appsService = TestBed.inject(AppsProcessCloudService); appsService = TestBed.inject(AppsProcessCloudService);
processService = TestBed.inject(ProcessCloudService); processService = TestBed.inject(ProcessCloudService);
@@ -111,6 +112,29 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.destroy(); fixture.destroy();
}); });
const clickExpansionPanel = async () => {
const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click();
fixture.detectChanges();
await fixture.whenStable();
};
const clickDeleteButton = async () => {
const deleteButton = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-filter-action-delete"]');
deleteButton.click();
fixture.detectChanges();
await fixture.whenStable();
};
const clickPropertyStatus = () => {
const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger');
stateElement.click();
fixture.detectChanges();
};
it('should not raise filter change events if filter remains the same', () => { it('should not raise filter change events if filter remains the same', () => {
let count = 0; let count = 0;
component.filterChange.subscribe(() => count++); component.filterChange.subscribe(() => count++);
@@ -145,8 +169,8 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const title = fixture.debugElement.nativeElement.querySelector('#adf-edit-process-filter-title-id'); const title = nativeElement.querySelector<HTMLElement>('#adf-edit-process-filter-title-id');
const subTitle = fixture.debugElement.nativeElement.querySelector('#adf-edit-process-filter-sub-title-id'); const subTitle = nativeElement.querySelector<HTMLElement>('#adf-edit-process-filter-sub-title-id');
expect(title).toBeDefined(); expect(title).toBeDefined();
expect(subTitle).toBeDefined(); expect(subTitle).toBeDefined();
@@ -162,7 +186,7 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const title = fixture.debugElement.nativeElement.querySelector('#adf-edit-process-filter-title-id'); const title = nativeElement.querySelector('#adf-edit-process-filter-title-id');
expect(title).toBeNull(); expect(title).toBeNull();
}); });
@@ -173,9 +197,9 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const title = fixture.debugElement.nativeElement.querySelector('#adf-edit-process-filter-title-id'); const title = nativeElement.querySelector<HTMLElement>('#adf-edit-process-filter-title-id');
const subTitle = fixture.debugElement.nativeElement.querySelector('#adf-edit-process-filter-sub-title-id'); const subTitle = nativeElement.querySelector<HTMLElement>('#adf-edit-process-filter-sub-title-id');
const matSpinnerElement = fixture.debugElement.nativeElement.querySelector('.adf-cloud-edit-process-filter-loading-margin'); const matSpinnerElement = nativeElement.querySelector('.adf-cloud-edit-process-filter-loading-margin');
expect(matSpinnerElement).toBeNull(); expect(matSpinnerElement).toBeNull();
expect(title).toBeDefined(); expect(title).toBeDefined();
@@ -192,7 +216,7 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const matSpinnerElement = fixture.debugElement.nativeElement.querySelector('.adf-cloud-edit-process-filter-loading-margin'); const matSpinnerElement = nativeElement.querySelector('.adf-cloud-edit-process-filter-loading-margin');
expect(matSpinnerElement).toBeDefined(); expect(matSpinnerElement).toBeDefined();
}); });
@@ -225,34 +249,28 @@ describe('EditProcessFilterCloudComponent', () => {
describe('Save & Delete buttons', () => { describe('Save & Delete buttons', () => {
it('should enable delete button for custom process filters', async () => { it('should enable delete button for custom process filters', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
await fixture.whenStable();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
expect(deleteButton.disabled).toEqual(false); expect(deleteButton.disabled).toEqual(false);
}); });
it('should enable save button if the filter is changed for custom process filters', (done) => { it('should enable save button if the filter is changed for custom process filters', (done) => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editProcessFilterForm.valueChanges component.editProcessFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toBe(false); expect(saveButton.disabled).toBe(false);
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); clickPropertyStatus();
stateElement.click();
fixture.detectChanges();
const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text')); const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
stateOptions[2].nativeElement.click(); stateOptions[2].nativeElement.click();
@@ -261,13 +279,9 @@ describe('EditProcessFilterCloudComponent', () => {
it('should disable save button if the filter is not changed for custom filter', async () => { it('should disable save button if the filter is not changed for custom filter', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
expect(saveButton.disabled).toBe(true); expect(saveButton.disabled).toBe(true);
}); });
}); });
@@ -288,25 +302,17 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]');
expect(saveButton.disabled).toEqual(true); expect(saveButton.disabled).toEqual(true);
}); });
it('should disable saveAs button if the process filter is not changed for custom filter', async () => { it('should disable saveAs button if the process filter is not changed for custom filter', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]');
expect(saveButton.disabled).toEqual(true); expect(saveButton.disabled).toEqual(true);
}); });
@@ -324,22 +330,20 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editProcessFilterForm.valueChanges component.editProcessFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toEqual(false); expect(saveButton.disabled).toEqual(false);
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); clickPropertyStatus();
stateElement.click();
fixture.detectChanges();
const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text')); const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
stateOptions[2].nativeElement.click(); stateOptions[2].nativeElement.click();
@@ -348,22 +352,20 @@ describe('EditProcessFilterCloudComponent', () => {
it('should enable saveAs button if the filter values are changed for custom filter', (done) => { it('should enable saveAs button if the filter values are changed for custom filter', (done) => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editProcessFilterForm.valueChanges component.editProcessFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toEqual(false); expect(saveButton.disabled).toEqual(false);
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); clickPropertyStatus();
stateElement.click();
fixture.detectChanges();
const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text')); const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
stateOptions[2].nativeElement.click(); stateOptions[2].nativeElement.click();
@@ -374,16 +376,11 @@ describe('EditProcessFilterCloudComponent', () => {
it('should display current process filter details', async () => { it('should display current process filter details', async () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
await clickExpansionPanel();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-status"]');
expansionPanel.click(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-sort"]');
const orderElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-order"]');
fixture.detectChanges();
await fixture.whenStable();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"]');
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-sort"]');
const orderElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-order"]');
expect(stateElement).toBeDefined(); expect(stateElement).toBeDefined();
expect(sortElement).toBeDefined(); expect(sortElement).toBeDefined();
expect(orderElement).toBeDefined(); expect(orderElement).toBeDefined();
@@ -395,12 +392,9 @@ describe('EditProcessFilterCloudComponent', () => {
it('should display state drop down', async () => { it('should display state drop down', async () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
await clickExpansionPanel();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); clickPropertyStatus();
expansionPanel.click();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger');
stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
@@ -412,10 +406,9 @@ describe('EditProcessFilterCloudComponent', () => {
it('should display sort drop down', async () => { it('should display sort drop down', async () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
await clickExpansionPanel();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-sort"] .mat-select-trigger');
expansionPanel.click();
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-sort"] .mat-select-trigger');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -428,10 +421,9 @@ describe('EditProcessFilterCloudComponent', () => {
it('should display order drop down', async () => { it('should display order drop down', async () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
await clickExpansionPanel();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const orderElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-order"] .mat-select-trigger');
expansionPanel.click();
const orderElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-order"] .mat-select-trigger');
orderElement.click(); orderElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -604,7 +596,7 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const controller = component.editProcessFilterForm.get('appVersionMultiple'); const controller = component.editProcessFilterForm.get('appVersionMultiple');
const appVersionMultiple = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-appVersionMultiple"]'); const appVersionMultiple = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-appVersionMultiple"]');
appVersionMultiple.click(); appVersionMultiple.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -633,7 +625,7 @@ describe('EditProcessFilterCloudComponent', () => {
await fixture.whenStable(); await fixture.whenStable();
const controller = component.editProcessFilterForm.get('processDefinitionName'); const controller = component.editProcessFilterForm.get('processDefinitionName');
const processDefinitionNamesElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-processDefinitionName"]'); const processDefinitionNamesElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-processDefinitionName"]');
processDefinitionNamesElement.click(); processDefinitionNamesElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -653,13 +645,9 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-sort"]');
await fixture.whenStable();
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-sort"]');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -691,13 +679,9 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-sort"]');
await fixture.whenStable();
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-sort"]');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -727,13 +711,9 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-sort"]');
await fixture.whenStable();
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-sort"]');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -761,14 +741,14 @@ describe('EditProcessFilterCloudComponent', () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const saveFilterSpy = spyOn(service, 'updateFilter').and.returnValue(of([fakeFilter])); const saveFilterSpy = spyOn(service, 'updateFilter').and.returnValue(of([fakeFilter]));
const saveSpy: jasmine.Spy = spyOn(component.action, 'emit'); const saveSpy: jasmine.Spy = spyOn(component.action, 'emit');
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editProcessFilterForm.valueChanges component.editProcessFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toBe(false); expect(saveButton.disabled).toBe(false);
saveButton.click(); saveButton.click();
@@ -777,9 +757,7 @@ describe('EditProcessFilterCloudComponent', () => {
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); clickPropertyStatus();
stateElement.click();
fixture.detectChanges();
const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text')); const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
stateOptions[2].nativeElement.click(); stateOptions[2].nativeElement.click();
@@ -794,23 +772,13 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); clickPropertyStatus();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); await clickDeleteButton();
stateElement.click();
fixture.detectChanges();
await fixture.whenStable();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
deleteButton.click();
fixture.detectChanges();
await fixture.whenStable();
expect(deleteFilterSpy).toHaveBeenCalled(); expect(deleteFilterSpy).toHaveBeenCalled();
expect(deleteSpy).toHaveBeenCalled(); expect(deleteSpy).toHaveBeenCalled();
@@ -820,14 +788,14 @@ describe('EditProcessFilterCloudComponent', () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const saveAsFilterSpy = spyOn(service, 'addFilter').and.callThrough(); const saveAsFilterSpy = spyOn(service, 'addFilter').and.callThrough();
const saveAsSpy = spyOn(component.action, 'emit'); const saveAsSpy = spyOn(component.action, 'emit');
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editProcessFilterForm.valueChanges component.editProcessFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toBe(false); expect(saveButton.disabled).toBe(false);
saveButton.click(); saveButton.click();
@@ -837,9 +805,7 @@ describe('EditProcessFilterCloudComponent', () => {
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); clickPropertyStatus();
stateElement.click();
fixture.detectChanges();
const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text')); const stateOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
stateOptions[2].nativeElement.click(); stateOptions[2].nativeElement.click();
@@ -848,15 +814,11 @@ describe('EditProcessFilterCloudComponent', () => {
it('should display default filter actions', async () => { it('should display default filter actions', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveAsButton = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-filter-action-saveAs"]');
await fixture.whenStable(); const saveButton = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-filter-action-save"]');
const deleteButton = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-filter-action-delete"]');
const saveAsButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]');
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
expect(component.processFilterActions).toBeDefined(); expect(component.processFilterActions).toBeDefined();
expect(component.processFilterActions.length).toEqual(3); expect(component.processFilterActions.length).toEqual(3);
expect(saveButton).toBeDefined(); expect(saveButton).toBeDefined();
@@ -902,12 +864,10 @@ describe('EditProcessFilterCloudComponent', () => {
await fixture.whenStable(); await fixture.whenStable();
const saveDefaultFilterSpy = spyOn(service, 'updateFilter').and.returnValue(of([fakeFilter])); const saveDefaultFilterSpy = spyOn(service, 'updateFilter').and.returnValue(of([fakeFilter]));
const saveDefaultFilterEmitSpy: jasmine.Spy = spyOn(component.action, 'emit'); const saveDefaultFilterEmitSpy = spyOn(component.action, 'emit');
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges();
const saveDefaultFilterButton = fixture.debugElement.nativeElement.querySelector(`[data-automation-id="adf-filter-action-${PROCESS_FILTER_ACTION_SAVE_DEFAULT}"]`); const saveDefaultFilterButton = nativeElement.querySelector<HTMLButtonElement>(`[data-automation-id="adf-filter-action-${PROCESS_FILTER_ACTION_SAVE_DEFAULT}"]`);
fixture.detectChanges(); fixture.detectChanges();
expect(saveDefaultFilterButton.disabled).toBe(false); expect(saveDefaultFilterButton.disabled).toBe(false);
saveDefaultFilterButton.click(); saveDefaultFilterButton.click();
@@ -942,11 +902,9 @@ describe('EditProcessFilterCloudComponent', () => {
const restoreDefaultProcessFiltersSpy = spyOn(service, 'getProcessFilters').and.returnValue(of([fakeFilter])); const restoreDefaultProcessFiltersSpy = spyOn(service, 'getProcessFilters').and.returnValue(of([fakeFilter]));
const resetDefaultsFilterSpy = spyOn(service, 'resetProcessFilterToDefaults').and.returnValue(of([fakeFilter])); const resetDefaultsFilterSpy = spyOn(service, 'resetProcessFilterToDefaults').and.returnValue(of([fakeFilter]));
const resetDefaultsEmitSpy: jasmine.Spy = spyOn(component.action, 'emit'); const resetDefaultsEmitSpy: jasmine.Spy = spyOn(component.action, 'emit');
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges();
const resetButton = fixture.debugElement.nativeElement.querySelector(`[data-automation-id="adf-filter-action-${PROCESS_FILTER_ACTION_RESTORE}"]`); const resetButton = nativeElement.querySelector<HTMLButtonElement>(`[data-automation-id="adf-filter-action-${PROCESS_FILTER_ACTION_RESTORE}"]`);
fixture.detectChanges(); fixture.detectChanges();
expect(resetButton.disabled).toBe(false); expect(resetButton.disabled).toBe(false);
resetButton.click(); resetButton.click();
@@ -966,16 +924,11 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
await clickExpansionPanel();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const saveAsButton = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-filter-action-saveAs"]');
expansionPanel.click(); const saveButton = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-filter-action-save"]');
const deleteButton = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-filter-action-delete"]');
fixture.detectChanges();
await fixture.whenStable();
const saveAsButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]');
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
expect(component.processFilterActions).toBeDefined(); expect(component.processFilterActions).toBeDefined();
expect(component.processFilterActions.length).toEqual(3); expect(component.processFilterActions.length).toEqual(3);
expect(saveButton).toBeDefined(); expect(saveButton).toBeDefined();
@@ -990,20 +943,132 @@ describe('EditProcessFilterCloudComponent', () => {
component.ngOnChanges({ id: processFilterIdChange }); component.ngOnChanges({ id: processFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
const date = moment(); const date = endOfDay(new Date());
component.filterChange.subscribe(() => { component.filterChange.subscribe(() => {
expect(component.processFilter.lastModifiedTo.toISOString()).toEqual(date.toISOString()); expect(component.processFilter.lastModifiedTo.toISOString()).toEqual(date.toISOString());
done(); done();
}); });
const lastModifiedToControl = component.editProcessFilterForm.get('lastModifiedTo'); component.lastModifiedTo.clearValidators();
lastModifiedToControl.setValue(date); component.lastModifiedTo.setValue(new Date());
date.set({
hour: 23, expect(component.lastModifiedTo.valid).toBe(true);
minute: 59, expect(component.editProcessFilterForm.valid).toBe(true);
second: 59
}); });
it('should set the correct lastModifiedFrom date', (done) => {
component.appName = 'fake';
component.filterProperties = ['appName', 'processInstanceId', 'priority', 'lastModified'];
const processFilterIdChange = new SimpleChange(undefined, 'mock-process-filter-id', true);
component.ngOnChanges({ id: processFilterIdChange });
fixture.detectChanges();
const date = startOfDay(new Date());
component.filterChange.subscribe(() => {
expect(component.processFilter.lastModifiedFrom.toISOString()).toEqual(date.toISOString());
done();
});
component.lastModifiedFrom.clearValidators();
component.lastModifiedFrom.setValue(new Date());
expect(component.lastModifiedFrom.valid).toBe(true);
expect(component.editProcessFilterForm.valid).toBe(true);
});
it('should validate lastModifiedTo date input', async () => {
component.appName = 'fake';
component.filterProperties = ['appName', 'processInstanceId', 'priority', 'lastModified'];
const processFilterIdChange = new SimpleChange(undefined, 'mock-process-filter-id', true);
component.ngOnChanges({ id: processFilterIdChange });
fixture.detectChanges();
await fixture.whenStable();
component.onDateChanged('20/03/2023', { key: 'lastModifiedTo' } as any );
expect(component.lastModifiedTo.value).toEqual(new Date('2023-03-20'));
expect(component.lastModifiedTo.valid).toBeTrue();
component.onDateChanged('invalid date', { key: 'lastModifiedTo' } as any);
expect(isValid(component.lastModifiedTo.value)).toBeFalse();
expect(component.lastModifiedTo.valid).toBeFalse();
});
it('should validate lastModifiedFrom date input', async () => {
component.appName = 'fake';
component.filterProperties = ['appName', 'processInstanceId', 'priority', 'lastModified'];
const processFilterIdChange = new SimpleChange(undefined, 'mock-process-filter-id', true);
component.ngOnChanges({ id: processFilterIdChange });
fixture.detectChanges();
await fixture.whenStable();
component.onDateChanged('20/03/2023', { key: 'lastModifiedFrom' } as any );
expect(component.lastModifiedFrom.value).toEqual(new Date('2023-03-20'));
expect(component.lastModifiedFrom.valid).toBeTrue();
component.onDateChanged('invalid date', { key: 'lastModifiedFrom' } as any);
expect(isValid(component.lastModifiedFrom.value)).toBeFalse();
expect(component.lastModifiedFrom.valid).toBeFalse();
});
it('should update lastModifiedTo from input', async () => {
component.appName = 'fake';
component.filterProperties = ['appName', 'processInstanceId', 'priority', 'lastModified'];
const processFilterIdChange = new SimpleChange(undefined, 'mock-process-filter-id', true);
component.ngOnChanges({ id: processFilterIdChange });
fixture.detectChanges();
await fixture.whenStable();
const dateInput = nativeElement.querySelector<HTMLInputElement>(`[data-automation-id="adf-cloud-edit-process-property-lastModifiedTo"]`);
expect(dateInput).not.toBeNull();
dateInput.value = '20/03/2023';
dateInput.dispatchEvent(new Event('keyup'));
expect(component.lastModifiedTo.value).toEqual(new Date('2023-03-20'));
expect(component.lastModifiedTo.valid).toBeTrue();
});
it('should update lastModifiedFrom from input', async () => {
component.appName = 'fake';
component.filterProperties = ['appName', 'processInstanceId', 'priority', 'lastModified'];
const processFilterIdChange = new SimpleChange(undefined, 'mock-process-filter-id', true);
component.ngOnChanges({ id: processFilterIdChange });
fixture.detectChanges();
await fixture.whenStable();
const dateInput = nativeElement.querySelector<HTMLInputElement>(`[data-automation-id="adf-cloud-edit-process-property-lastModifiedFrom"]`);
expect(dateInput).not.toBeNull();
dateInput.value = '20/03/2023';
dateInput.dispatchEvent(new Event('keyup'));
expect(component.lastModifiedFrom.value).toEqual(new Date('2023-03-20'));
expect(component.lastModifiedFrom.valid).toBeTrue();
});
it('should fail validating lastModifiedFrom from input', async () => {
component.appName = 'fake';
component.filterProperties = ['appName', 'processInstanceId', 'priority', 'lastModified'];
const processFilterIdChange = new SimpleChange(undefined, 'mock-process-filter-id', true);
component.ngOnChanges({ id: processFilterIdChange });
fixture.detectChanges();
await fixture.whenStable();
const dateInput = nativeElement.querySelector<HTMLInputElement>(`[data-automation-id="adf-cloud-edit-process-property-lastModifiedFrom"]`);
expect(dateInput).not.toBeNull();
dateInput.value = 'invalid';
dateInput.dispatchEvent(new Event('keyup'));
expect(isValid(component.lastModifiedFrom.value)).toBeFalse();
expect(component.lastModifiedFrom.valid).toBeFalse();
}); });
it('should set date range filter type when range is selected', (done) => { it('should set date range filter type when range is selected', (done) => {
@@ -1014,8 +1079,7 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.filterChange.subscribe(() => { component.filterChange.subscribe(() => {
const completedDateTypeControl = component.editProcessFilterForm.get('completedDateType'); expect(component.completedDateType.value).toEqual(DateCloudFilterType.RANGE);
expect(completedDateTypeControl.value).toEqual(DateCloudFilterType.RANGE);
done(); done();
}); });
@@ -1023,8 +1087,8 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const dateFilter = { const dateFilter = {
startDate: moment().startOf('day').toISOString(true), startDate: startOfDay(new Date()).toISOString(),
endDate: moment().endOf('day').toISOString(true) endDate: endOfDay(new Date()).toISOString()
}; };
component.onDateRangeFilterChanged(dateFilter, { component.onDateRangeFilterChanged(dateFilter, {
@@ -1057,8 +1121,7 @@ describe('EditProcessFilterCloudComponent', () => {
done(); done();
}); });
const startedDateTypeControl = component.editProcessFilterForm.get('completedDateType'); component.completedDateType.setValue(DateCloudFilterType.TODAY);
startedDateTypeControl.setValue(DateCloudFilterType.TODAY);
}); });
it('should update form on date range value is updated', (done) => { it('should update form on date range value is updated', (done) => {
@@ -1069,8 +1132,8 @@ describe('EditProcessFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const dateFilter = { const dateFilter = {
startDate: moment().startOf('day').toISOString(true), startDate: startOfDay(new Date()).toISOString(),
endDate: moment().endOf('day').toISOString(true) endDate: endOfDay(new Date()).toISOString()
}; };
component.filterChange.subscribe(() => { component.filterChange.subscribe(() => {
@@ -1079,8 +1142,7 @@ describe('EditProcessFilterCloudComponent', () => {
done(); done();
}); });
const startedDateTypeControl = component.editProcessFilterForm.get('completedDateType'); component.completedDateType.setValue(DateCloudFilterType.RANGE);
startedDateTypeControl.setValue(DateCloudFilterType.RANGE);
component.onDateRangeFilterChanged(dateFilter, { component.onDateRangeFilterChanged(dateFilter, {
key: 'completedDateRange', key: 'completedDateRange',
@@ -1095,60 +1157,44 @@ describe('EditProcessFilterCloudComponent', () => {
}); });
}); });
it('should call restore default filters service on deletion of last filter', (done) => { it('should call restore default filters service on deletion of last filter', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of([])); const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of([]));
const restoreFiltersSpy = spyOn(component, 'restoreDefaultProcessFilters').and.returnValue(of([])); const restoreFiltersSpy = spyOn(component, 'restoreDefaultProcessFilters').and.returnValue(of([]));
const deleteSpy: jasmine.Spy = spyOn(component.action, 'emit'); const deleteSpy: jasmine.Spy = spyOn(component.action, 'emit');
fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); await clickExpansionPanel();
stateElement.click(); clickPropertyStatus();
fixture.detectChanges(); await clickDeleteButton();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
deleteButton.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(deleteFilterSpy).toHaveBeenCalled(); expect(deleteFilterSpy).toHaveBeenCalled();
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { await fixture.whenStable();
expect(deleteSpy).toHaveBeenCalled(); expect(deleteSpy).toHaveBeenCalled();
expect(restoreFiltersSpy).toHaveBeenCalled(); expect(restoreFiltersSpy).toHaveBeenCalled();
done();
}); });
}); it('should not call restore default filters service on deletion first filter', async () => {
});
it('should not call restore default filters service on deletion first filter', (done) => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of([new ProcessFilterCloudModel({ name: 'mock-filter-name' })])); const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of([new ProcessFilterCloudModel({ name: 'mock-filter-name' })]));
const restoreFiltersSpy = spyOn(component, 'restoreDefaultProcessFilters').and.returnValue(of([])); const restoreFiltersSpy = spyOn(component, 'restoreDefaultProcessFilters').and.returnValue(of([]));
const deleteSpy: jasmine.Spy = spyOn(component.action, 'emit'); const deleteSpy: jasmine.Spy = spyOn(component.action, 'emit');
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); clickPropertyStatus();
fixture.detectChanges(); fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); await clickDeleteButton();
stateElement.click();
fixture.detectChanges();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
deleteButton.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(deleteFilterSpy).toHaveBeenCalled(); expect(deleteFilterSpy).toHaveBeenCalled();
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { await fixture.whenStable();
expect(deleteSpy).toHaveBeenCalled(); expect(deleteSpy).toHaveBeenCalled();
expect(restoreFiltersSpy).not.toHaveBeenCalled(); expect(restoreFiltersSpy).not.toHaveBeenCalled();
done();
});
});
}); });
it('should build initiator as object array', () => { it('should build initiator as object array', () => {

View File

@@ -16,12 +16,11 @@
*/ */
import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges, OnDestroy, ViewEncapsulation } from '@angular/core';
import { UntypedFormGroup, UntypedFormBuilder, AbstractControl } from '@angular/forms'; import { FormBuilder, AbstractControl, FormGroup, FormControl } from '@angular/forms';
import { DateAdapter } from '@angular/material/core'; import { DateAdapter } from '@angular/material/core';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { debounceTime, filter, takeUntil, finalize, switchMap, tap } from 'rxjs/operators'; import { debounceTime, filter, takeUntil, finalize, switchMap, tap } from 'rxjs/operators';
import { Subject, Observable, Subscription } from 'rxjs'; import { Subject, Observable, Subscription } from 'rxjs';
import moment, { Moment } from 'moment';
import { AppsProcessCloudService } from '../../../app/services/apps-process-cloud.service'; import { AppsProcessCloudService } from '../../../app/services/apps-process-cloud.service';
import { import {
ProcessFilterCloudModel, ProcessFilterCloudModel,
@@ -30,13 +29,14 @@ import {
ProcessFilterOptions, ProcessFilterOptions,
ProcessSortFilterProperty ProcessSortFilterProperty
} from '../models/process-filter-cloud.model'; } from '../models/process-filter-cloud.model';
import { TranslationService, UserPreferencesService, UserPreferenceValues } from '@alfresco/adf-core'; import { DateFnsUtils, TranslationService, UserPreferencesService, UserPreferenceValues } from '@alfresco/adf-core';
import { ProcessFilterCloudService } from '../services/process-filter-cloud.service'; import { ProcessFilterCloudService } from '../services/process-filter-cloud.service';
import { ProcessFilterDialogCloudComponent } from './process-filter-dialog-cloud.component'; import { ProcessFilterDialogCloudComponent } from './process-filter-dialog-cloud.component';
import { ProcessCloudService } from '../../services/process-cloud.service'; import { ProcessCloudService } from '../../services/process-cloud.service';
import { DateCloudFilterType, DateRangeFilter } from '../../../models/date-cloud-filter.model'; import { DateCloudFilterType, DateRangeFilter } from '../../../models/date-cloud-filter.model';
import { IdentityUserModel } from '../../../people/models/identity-user.model'; import { IdentityUserModel } from '../../../people/models/identity-user.model';
import { Environment } from '../../../common/interface/environment.interface'; import { Environment } from '../../../common/interface/environment.interface';
import { endOfDay, isValid, startOfDay } from 'date-fns';
export const PROCESS_FILTER_ACTION_SAVE = 'save'; export const PROCESS_FILTER_ACTION_SAVE = 'save';
export const PROCESS_FILTER_ACTION_SAVE_AS = 'saveAs'; export const PROCESS_FILTER_ACTION_SAVE_AS = 'saveAs';
@@ -52,6 +52,19 @@ export interface DropdownOption {
label: string; label: string;
} }
interface ProcessFilterFormProps {
appName?: FormControl<string>;
appVersion?: FormControl<number | number[]>;
processDefinitionName?: FormControl<string>;
lastModifiedFrom?: FormControl<Date>;
lastModifiedTo?: FormControl<Date>;
status?: FormControl<string>;
order?: FormControl<string>;
sort?: FormControl<string>;
completedDateType?: FormControl<DateCloudFilterType>;
[x: string]: FormControl<unknown>;
}
@Component({ @Component({
selector: 'adf-cloud-edit-process-filter', selector: 'adf-cloud-edit-process-filter',
templateUrl: './edit-process-filter-cloud.component.html', templateUrl: './edit-process-filter-cloud.component.html',
@@ -165,7 +178,7 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
value: '' value: ''
}; };
processDefinitionNames: any[] = []; processDefinitionNames: any[] = [];
editProcessFilterForm: UntypedFormGroup; editProcessFilterForm: FormGroup<ProcessFilterFormProps>;
processFilterProperties: ProcessFilterProperties[] = []; processFilterProperties: ProcessFilterProperties[] = [];
processFilterActions: ProcessFilterAction[] = []; processFilterActions: ProcessFilterAction[] = [];
toggleFilterActions: boolean = false; toggleFilterActions: boolean = false;
@@ -177,9 +190,9 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
private filterChangeSub: Subscription; private filterChangeSub: Subscription;
constructor( constructor(
private formBuilder: UntypedFormBuilder, private formBuilder: FormBuilder,
public dialog: MatDialog, public dialog: MatDialog,
private dateAdapter: DateAdapter<Moment>, private dateAdapter: DateAdapter<Date>,
private userPreferencesService: UserPreferencesService, private userPreferencesService: UserPreferencesService,
private translateService: TranslationService, private translateService: TranslationService,
private processFilterCloudService: ProcessFilterCloudService, private processFilterCloudService: ProcessFilterCloudService,
@@ -222,6 +235,18 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
return properties.reduce((result, current) => Object.assign(result, current), {}); return properties.reduce((result, current) => Object.assign(result, current), {});
} }
get lastModifiedFrom(): AbstractControl<Date> {
return this.editProcessFilterForm.get('lastModifiedFrom');
}
get lastModifiedTo(): AbstractControl<Date> {
return this.editProcessFilterForm.get('lastModifiedTo');
}
get completedDateType(): AbstractControl<DateCloudFilterType> {
return this.editProcessFilterForm.get('completedDateType');
}
private getAttributesControlConfig(property: ProcessFilterProperties) { private getAttributesControlConfig(property: ProcessFilterProperties) {
return Object.values(property.attributes).reduce((result, key) => { return Object.values(property.attributes).reduce((result, key) => {
result[key] = property.value[key]; result[key] = property.value[key];
@@ -258,7 +283,8 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
filter(() => this.isFormValid()), filter(() => this.isFormValid()),
takeUntil(this.onDestroy$) takeUntil(this.onDestroy$)
) )
.subscribe((formValues: ProcessFilterCloudModel) => { .subscribe((formValues: Partial<ProcessFilterCloudModel>) => {
this.setLastModifiedFromFilter(formValues);
this.setLastModifiedToFilter(formValues); this.setLastModifiedToFilter(formValues);
const newValue = new ProcessFilterCloudModel(Object.assign({}, this.processFilter, formValues)); const newValue = new ProcessFilterCloudModel(Object.assign({}, this.processFilter, formValues));
@@ -363,14 +389,21 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
return this.editProcessFilterForm.get(property.key); return this.editProcessFilterForm.get(property.key);
} }
onDateChanged(newDateValue: Moment, dateProperty: ProcessFilterProperties) { onDateChanged(newDateValue: Date | string, dateProperty: ProcessFilterProperties) {
if (newDateValue) { if (newDateValue) {
const controller = this.getPropertyController(dateProperty); const controller = this.getPropertyController(dateProperty);
if (newDateValue.isValid()) { let date = newDateValue;
controller.setValue(newDateValue);
if (typeof newDateValue === 'string') {
date = DateFnsUtils.parseDate(newDateValue, 'dd/MM/yyyy');
}
if (isValid(date)) {
controller.setValue(date);
controller.setErrors(null); controller.setErrors(null);
} else { } else {
controller.setValue(date);
controller.setErrors({ invalid: true }); controller.setErrors({ invalid: true });
} }
} }
@@ -484,7 +517,7 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
}); });
dialogRef.afterClosed().subscribe((result) => { dialogRef.afterClosed().subscribe((result) => {
if (result && result.action === ProcessFilterDialogCloudComponent.ACTION_SAVE) { if (result && result.action === ProcessFilterDialogCloudComponent.ACTION_SAVE) {
const filterId = Math.random().toString(36).substr(2, 9); const filterId = Math.random().toString(36).substring(2, 9);
const filterKey = this.getSanitizeFilterName(result.name); const filterKey = this.getSanitizeFilterName(result.name);
const newFilter = { const newFilter = {
name: result.name, name: result.name,
@@ -561,15 +594,15 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
: false; : false;
} }
private setLastModifiedToFilter(formValues: ProcessFilterCloudModel) { private setLastModifiedToFilter(formValues: Partial<ProcessFilterCloudModel>) {
if (formValues.lastModifiedTo && Date.parse(formValues.lastModifiedTo.toString())) { if (isValid(formValues.lastModifiedTo)) {
const lastModifiedToFilterValue = moment(formValues.lastModifiedTo); formValues.lastModifiedTo = endOfDay(formValues.lastModifiedTo);
lastModifiedToFilterValue.set({ }
hour: 23, }
minute: 59,
second: 59 private setLastModifiedFromFilter(formValues: Partial<ProcessFilterCloudModel>) {
}); if (isValid(formValues.lastModifiedFrom)) {
formValues.lastModifiedTo = lastModifiedToFilterValue.toDate(); formValues.lastModifiedFrom = startOfDay(formValues.lastModifiedFrom);
} }
} }
@@ -604,29 +637,18 @@ export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDes
} }
private createLastModifiedProperty(filterModel: ProcessFilterCloudModel): ProcessFilterProperties[] { private createLastModifiedProperty(filterModel: ProcessFilterCloudModel): ProcessFilterProperties[] {
let lastModifiedFrom;
let lastModifiedTo;
if (filterModel.lastModifiedFrom) {
lastModifiedFrom = moment(filterModel.lastModifiedFrom);
}
if (filterModel.lastModifiedTo) {
lastModifiedTo = moment(filterModel.lastModifiedTo);
}
return [ return [
{ {
label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.LAST_MODIFIED_DATE_FORM', label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.LAST_MODIFIED_DATE_FORM',
type: 'date', type: 'date',
key: 'lastModifiedFrom', key: 'lastModifiedFrom',
value: lastModifiedFrom value: filterModel.lastModifiedFrom
}, },
{ {
label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.LAST_MODIFIED_TO', label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.LAST_MODIFIED_TO',
type: 'date', type: 'date',
key: 'lastModifiedTo', key: 'lastModifiedTo',
value: lastModifiedTo value: filterModel.lastModifiedTo
} }
]; ];
} }

View File

@@ -59,7 +59,7 @@
[attr.data-automation-id]="taskFilterProperty.key"> [attr.data-automation-id]="taskFilterProperty.key">
<mat-label>{{taskFilterProperty.label | translate}}</mat-label> <mat-label>{{taskFilterProperty.label | translate}}</mat-label>
<input matInput <input matInput
(keyup)="onDateChanged($any($event).srcElement.value, taskFilterProperty)" (keyup)="onDateChanged($any($event).target.value, taskFilterProperty)"
(dateChange)="onDateChanged($event.value, taskFilterProperty)" (dateChange)="onDateChanged($event.value, taskFilterProperty)"
[matDatepicker]="dateController" [matDatepicker]="dateController"
placeholder="{{taskFilterProperty.label | translate}}" placeholder="{{taskFilterProperty.label | translate}}"

View File

@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { OnChanges, SimpleChanges, OnInit, OnDestroy, Directive, Input, Output, EventEmitter } from '@angular/core'; import { OnChanges, SimpleChanges, OnInit, OnDestroy, Directive, Input, Output, EventEmitter, inject } from '@angular/core';
import { AssignmentType, FilterOptions, TaskFilterAction, TaskFilterProperties, TaskStatusFilter } from '../../models/filter-cloud.model'; import { AssignmentType, FilterOptions, TaskFilterAction, TaskFilterProperties, TaskStatusFilter } from '../../models/filter-cloud.model';
import { TaskCloudService } from './../../../services/task-cloud.service'; import { TaskCloudService } from './../../../services/task-cloud.service';
import { AppsProcessCloudService } from './../../../../app/services/apps-process-cloud.service'; import { AppsProcessCloudService } from './../../../../app/services/apps-process-cloud.service';
@@ -40,21 +40,22 @@ export interface DropdownOption {
label: string; label: string;
} }
const ACTION_SAVE = 'save';
const ACTION_SAVE_AS = 'saveAs';
const ACTION_DELETE = 'delete';
const APP_RUNNING_STATUS = 'RUNNING';
const APPLICATION_NAME = 'appName';
const PROCESS_DEFINITION_NAME = 'processDefinitionName';
const LAST_MODIFIED_PROPERTY = 'lastModified';
const DATE_FORMAT = 'DD/MM/YYYY';
const DEFAULT_ACTIONS = [ACTION_SAVE, ACTION_SAVE_AS, ACTION_DELETE];
const SORT_PROPERTY = 'sort';
const ORDER_PROPERTY = 'order';
@Directive() @Directive()
// eslint-disable-next-line @angular-eslint/directive-class-suffix // eslint-disable-next-line @angular-eslint/directive-class-suffix
export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnChanges, OnDestroy { export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnChanges, OnDestroy {
public static ACTION_SAVE = 'save'; public static ACTIONS_DISABLED_BY_DEFAULT = [ACTION_SAVE, ACTION_DELETE];
public static ACTION_SAVE_AS = 'saveAs';
public static ACTION_DELETE = 'delete';
public static APP_RUNNING_STATUS: string = 'RUNNING';
public static APPLICATION_NAME: string = 'appName';
public static PROCESS_DEFINITION_NAME: string = 'processDefinitionName';
public static LAST_MODIFIED: string = 'lastModified';
public static SORT: string = 'sort';
public static ORDER: string = 'order';
public static DEFAULT_ACTIONS = ['save', 'saveAs', 'delete'];
public static FORMAT_DATE: string = 'DD/MM/YYYY';
public static ACTIONS_DISABLED_BY_DEFAULT = [BaseEditTaskFilterCloudComponent.ACTION_SAVE, BaseEditTaskFilterCloudComponent.ACTION_DELETE];
/** (required) Name of the app. */ /** (required) Name of the app. */
@Input() @Input()
@@ -94,7 +95,7 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
/** List of task filter actions. */ /** List of task filter actions. */
@Input() @Input()
actions: string[] = BaseEditTaskFilterCloudComponent.DEFAULT_ACTIONS; actions: string[] = [...DEFAULT_ACTIONS];
/** List of sort properties to display. */ /** List of sort properties to display. */
@Input() @Input()
@@ -135,15 +136,13 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
protected onDestroy$ = new Subject<boolean>(); protected onDestroy$ = new Subject<boolean>();
isLoading: boolean = false; isLoading: boolean = false;
constructor( protected translateService = inject(TranslationService);
protected formBuilder: UntypedFormBuilder, protected taskCloudService = inject(TaskCloudService);
protected dateAdapter: DateAdapter<Moment>, protected userPreferencesService = inject(UserPreferencesService);
protected userPreferencesService: UserPreferencesService, protected appsProcessCloudService = inject(AppsProcessCloudService);
protected appsProcessCloudService: AppsProcessCloudService, protected dialog = inject(MatDialog);
protected taskCloudService: TaskCloudService, protected formBuilder = inject(UntypedFormBuilder);
protected dialog: MatDialog, protected dateAdapter = inject<DateAdapter<Moment>>(DateAdapter);
protected translateService: TranslationService
) {}
ngOnInit() { ngOnInit() {
this.userPreferencesService this.userPreferencesService
@@ -167,17 +166,17 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
createFilterActions(): TaskFilterAction[] { createFilterActions(): TaskFilterAction[] {
return [ return [
{ {
actionType: BaseEditTaskFilterCloudComponent.ACTION_SAVE, actionType: ACTION_SAVE,
icon: 'adf:save', icon: 'adf:save',
tooltip: 'ADF_CLOUD_EDIT_TASK_FILTER.TOOL_TIP.SAVE' tooltip: 'ADF_CLOUD_EDIT_TASK_FILTER.TOOL_TIP.SAVE'
}, },
{ {
actionType: BaseEditTaskFilterCloudComponent.ACTION_SAVE_AS, actionType: ACTION_SAVE_AS,
icon: 'adf:save-as', icon: 'adf:save-as',
tooltip: 'ADF_CLOUD_EDIT_TASK_FILTER.TOOL_TIP.SAVE_AS' tooltip: 'ADF_CLOUD_EDIT_TASK_FILTER.TOOL_TIP.SAVE_AS'
}, },
{ {
actionType: BaseEditTaskFilterCloudComponent.ACTION_DELETE, actionType: ACTION_DELETE,
icon: 'delete', icon: 'delete',
tooltip: 'ADF_CLOUD_EDIT_TASK_FILTER.TOOL_TIP.DELETE' tooltip: 'ADF_CLOUD_EDIT_TASK_FILTER.TOOL_TIP.DELETE'
} }
@@ -185,13 +184,13 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
} }
hasFormChanged(action: TaskFilterAction): boolean { hasFormChanged(action: TaskFilterAction): boolean {
if (action.actionType === BaseEditTaskFilterCloudComponent.ACTION_SAVE) { if (action.actionType === ACTION_SAVE) {
return !this.formHasBeenChanged; return !this.formHasBeenChanged;
} }
if (action.actionType === BaseEditTaskFilterCloudComponent.ACTION_SAVE_AS) { if (action.actionType === ACTION_SAVE_AS) {
return !this.formHasBeenChanged; return !this.formHasBeenChanged;
} }
if (action.actionType === BaseEditTaskFilterCloudComponent.ACTION_DELETE) { if (action.actionType === ACTION_DELETE) {
return false; return false;
} }
@@ -231,18 +230,18 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
} }
executeFilterActions(action: TaskFilterAction): void { executeFilterActions(action: TaskFilterAction): void {
if (action.actionType === BaseEditTaskFilterCloudComponent.ACTION_SAVE) { if (action.actionType === ACTION_SAVE) {
this.save(action); this.save(action);
} else if (action.actionType === BaseEditTaskFilterCloudComponent.ACTION_SAVE_AS) { } else if (action.actionType === ACTION_SAVE_AS) {
this.saveAs(action); this.saveAs(action);
} else if (action.actionType === BaseEditTaskFilterCloudComponent.ACTION_DELETE) { } else if (action.actionType === ACTION_DELETE) {
this.delete(action); this.delete(action);
} }
} }
getRunningApplications() { getRunningApplications() {
this.appsProcessCloudService this.appsProcessCloudService
.getDeployedApplicationsByStatus(BaseEditTaskFilterCloudComponent.APP_RUNNING_STATUS, this.role) .getDeployedApplicationsByStatus(APP_RUNNING_STATUS, this.role)
.subscribe((applications) => { .subscribe((applications) => {
if (applications && applications.length > 0) { if (applications && applications.length > 0) {
applications.map((application) => { applications.map((application) => {
@@ -268,7 +267,7 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
checkMandatoryActions(): void { checkMandatoryActions(): void {
if (this.actions === undefined || this.actions.length === 0) { if (this.actions === undefined || this.actions.length === 0) {
this.actions = BaseEditTaskFilterCloudComponent.DEFAULT_ACTIONS; this.actions = [...DEFAULT_ACTIONS];
} }
} }
@@ -284,9 +283,9 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
return this.editTaskFilterForm.get(property.key); return this.editTaskFilterForm.get(property.key);
} }
onDateChanged(newDateValue: any, dateProperty: TaskFilterProperties) { onDateChanged(newDateValue: string | Moment, dateProperty: TaskFilterProperties) {
if (newDateValue) { if (newDateValue) {
const momentDate = moment(newDateValue, BaseEditTaskFilterCloudComponent.FORMAT_DATE, true); const momentDate = moment(newDateValue, DATE_FORMAT, true);
const controller = this.getPropertyController(dateProperty); const controller = this.getPropertyController(dateProperty);
if (momentDate.isValid()) { if (momentDate.isValid()) {
@@ -363,7 +362,7 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
} }
hasLastModifiedProperty(): boolean { hasLastModifiedProperty(): boolean {
return this.filterProperties.indexOf(BaseEditTaskFilterCloudComponent.LAST_MODIFIED) >= 0; return this.filterProperties.indexOf(LAST_MODIFIED_PROPERTY) >= 0;
} }
get createSortProperties(): FilterOptions[] { get createSortProperties(): FilterOptions[] {
@@ -386,12 +385,12 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
} }
hasSortProperty(): boolean { hasSortProperty(): boolean {
return this.filterProperties.indexOf(BaseEditTaskFilterCloudComponent.SORT) >= 0; return this.filterProperties.indexOf(SORT_PROPERTY) >= 0;
} }
removeOrderProperty(filteredProperties: TaskFilterProperties[]): TaskFilterProperties[] { removeOrderProperty(filteredProperties: TaskFilterProperties[]): TaskFilterProperties[] {
if (filteredProperties?.length > 0) { if (filteredProperties?.length > 0) {
return filteredProperties.filter((property) => property.key !== BaseEditTaskFilterCloudComponent.ORDER); return filteredProperties.filter((property) => property.key !== ORDER_PROPERTY);
} }
return []; return [];
} }
@@ -399,11 +398,11 @@ export abstract class BaseEditTaskFilterCloudComponent<T> implements OnInit, OnC
createAndFilterProperties() { createAndFilterProperties() {
this.checkMandatoryFilterProperties(); this.checkMandatoryFilterProperties();
if (this.checkForProperty(BaseEditTaskFilterCloudComponent.APPLICATION_NAME)) { if (this.checkForProperty(APPLICATION_NAME)) {
this.applicationNames = []; this.applicationNames = [];
this.getRunningApplications(); this.getRunningApplications();
} }
if (this.checkForProperty(BaseEditTaskFilterCloudComponent.PROCESS_DEFINITION_NAME)) { if (this.checkForProperty(PROCESS_DEFINITION_NAME)) {
this.processDefinitionNames = []; this.processDefinitionNames = [];
this.getProcessDefinitions(); this.getProcessDefinitions();
} }

View File

@@ -15,18 +15,10 @@
* limitations under the License. * limitations under the License.
*/ */
import { Component, ViewEncapsulation } from '@angular/core'; import { Component, ViewEncapsulation, inject } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { DateAdapter } from '@angular/material/core';
import { MatDialog } from '@angular/material/dialog';
import { takeUntil } from 'rxjs/operators'; import { takeUntil } from 'rxjs/operators';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { Moment } from 'moment';
import { TaskFilterProperties, TaskFilterAction, ServiceTaskFilterCloudModel } from '../../models/filter-cloud.model'; import { TaskFilterProperties, TaskFilterAction, ServiceTaskFilterCloudModel } from '../../models/filter-cloud.model';
import { TranslationService, UserPreferencesService } from '@alfresco/adf-core';
import { AppsProcessCloudService } from '../../../../app/services/apps-process-cloud.service';
import { TaskCloudService } from '../../../services/task-cloud.service';
import { ServiceTaskFilterCloudService } from '../../services/service-task-filter-cloud.service'; import { ServiceTaskFilterCloudService } from '../../services/service-task-filter-cloud.service';
import { BaseEditTaskFilterCloudComponent, DropdownOption } from './base-edit-task-filter-cloud.component'; import { BaseEditTaskFilterCloudComponent, DropdownOption } from './base-edit-task-filter-cloud.component';
@@ -37,16 +29,10 @@ import { BaseEditTaskFilterCloudComponent, DropdownOption } from './base-edit-ta
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None
}) })
export class EditServiceTaskFilterCloudComponent extends BaseEditTaskFilterCloudComponent<ServiceTaskFilterCloudModel> { export class EditServiceTaskFilterCloudComponent extends BaseEditTaskFilterCloudComponent<ServiceTaskFilterCloudModel> {
constructor( private serviceTaskFilterCloudService = inject(ServiceTaskFilterCloudService);
formBuilder: UntypedFormBuilder,
dialog: MatDialog, constructor() {
translateService: TranslationService, super();
private serviceTaskFilterCloudService: ServiceTaskFilterCloudService,
dateAdapter: DateAdapter<Moment>,
userPreferencesService: UserPreferencesService,
appsProcessCloudService: AppsProcessCloudService,
taskCloudService: TaskCloudService) {
super(formBuilder, dateAdapter, userPreferencesService, appsProcessCloudService, taskCloudService, dialog, translateService);
} }
assignNewFilter(model: ServiceTaskFilterCloudModel) { assignNewFilter(model: ServiceTaskFilterCloudModel) {

View File

@@ -32,7 +32,6 @@ import { TaskFilterCloudService } from '../../services/task-filter-cloud.service
import { TaskCloudService } from '../../../services/task-cloud.service'; import { TaskCloudService } from '../../../services/task-cloud.service';
import { fakeFilter } from '../../mock/task-filters-cloud.mock'; import { fakeFilter } from '../../mock/task-filters-cloud.mock';
import { AbstractControl } from '@angular/forms'; import { AbstractControl } from '@angular/forms';
import moment from 'moment';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { DateCloudFilterType } from '../../../../models/date-cloud-filter.model'; import { DateCloudFilterType } from '../../../../models/date-cloud-filter.model';
import { AssignmentType, TaskFilterCloudModel, TaskStatusFilter } from '../../models/filter-cloud.model'; import { AssignmentType, TaskFilterCloudModel, TaskStatusFilter } from '../../models/filter-cloud.model';
@@ -55,12 +54,14 @@ import { mockFoodUsers } from '../../../../people/mock/people-cloud.mock';
import { mockFoodGroups } from '../../../../group/mock/group-cloud.mock'; import { mockFoodGroups } from '../../../../group/mock/group-cloud.mock';
import { SimpleChanges } from '@angular/core'; import { SimpleChanges } from '@angular/core';
import { TaskFilterDialogCloudComponent } from '../task-filter-dialog/task-filter-dialog-cloud.component'; import { TaskFilterDialogCloudComponent } from '../task-filter-dialog/task-filter-dialog-cloud.component';
import { set } from 'date-fns';
describe('EditTaskFilterCloudComponent', () => { describe('EditTaskFilterCloudComponent', () => {
let component: EditTaskFilterCloudComponent; let component: EditTaskFilterCloudComponent;
let service: TaskFilterCloudService; let service: TaskFilterCloudService;
let appsService: AppsProcessCloudService; let appsService: AppsProcessCloudService;
let fixture: ComponentFixture<EditTaskFilterCloudComponent>; let fixture: ComponentFixture<EditTaskFilterCloudComponent>;
let nativeElement: HTMLElement;
let dialog: MatDialog; let dialog: MatDialog;
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
let getTaskFilterSpy: jasmine.Spy; let getTaskFilterSpy: jasmine.Spy;
@@ -84,6 +85,7 @@ describe('EditTaskFilterCloudComponent', () => {
}); });
fixture = TestBed.createComponent(EditTaskFilterCloudComponent); fixture = TestBed.createComponent(EditTaskFilterCloudComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
nativeElement = fixture.debugElement.nativeElement;
service = TestBed.inject(TaskFilterCloudService); service = TestBed.inject(TaskFilterCloudService);
appsService = TestBed.inject(AppsProcessCloudService); appsService = TestBed.inject(AppsProcessCloudService);
taskService = TestBed.inject(TaskCloudService); taskService = TestBed.inject(TaskCloudService);
@@ -101,6 +103,14 @@ describe('EditTaskFilterCloudComponent', () => {
afterEach(() => fixture.destroy()); afterEach(() => fixture.destroy());
const clickExpansionPanel = async () => {
const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click();
fixture.detectChanges();
await fixture.whenStable();
};
it('should fetch task filter by taskId', async () => { it('should fetch task filter by taskId', async () => {
component.ngOnChanges({ id: mockTaskFilterIdChange }); component.ngOnChanges({ id: mockTaskFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
@@ -222,8 +232,8 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const title = fixture.debugElement.nativeElement.querySelector('#adf-edit-task-filter-title-id'); const title = nativeElement.querySelector<HTMLElement>('#adf-edit-task-filter-title-id');
const subTitle = fixture.debugElement.nativeElement.querySelector('#adf-edit-task-filter-sub-title-id'); const subTitle = nativeElement.querySelector<HTMLElement>('#adf-edit-task-filter-sub-title-id');
expect(title.innerText).toEqual('FakeInvolvedTasks'); expect(title.innerText).toEqual('FakeInvolvedTasks');
expect(subTitle.innerText.trim()).toEqual('ADF_CLOUD_EDIT_TASK_FILTER.TITLE'); expect(subTitle.innerText.trim()).toEqual('ADF_CLOUD_EDIT_TASK_FILTER.TITLE');
}); });
@@ -235,7 +245,7 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const title = fixture.debugElement.nativeElement.querySelector('#adf-edit-task-filter-title-id'); const title = nativeElement.querySelector<HTMLElement>('#adf-edit-task-filter-title-id');
expect(title).toBeNull(); expect(title).toBeNull();
}); });
@@ -245,9 +255,9 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const title = fixture.debugElement.nativeElement.querySelector('#adf-edit-task-filter-title-id'); const title = nativeElement.querySelector<HTMLElement>('#adf-edit-task-filter-title-id');
const subTitle = fixture.debugElement.nativeElement.querySelector('#adf-edit-task-filter-sub-title-id'); const subTitle = nativeElement.querySelector<HTMLElement>('#adf-edit-task-filter-sub-title-id');
const matSpinnerElement = fixture.debugElement.nativeElement.querySelector('.adf-cloud-edit-task-filter-loading-margin'); const matSpinnerElement = nativeElement.querySelector<HTMLElement>('.adf-cloud-edit-task-filter-loading-margin');
expect(matSpinnerElement).toBeNull(); expect(matSpinnerElement).toBeNull();
expect(title.innerText).toEqual('FakeInvolvedTasks'); expect(title.innerText).toEqual('FakeInvolvedTasks');
@@ -261,7 +271,7 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const matSpinnerElement = fixture.debugElement.nativeElement.querySelector('.adf-cloud-edit-task-filter-loading-margin'); const matSpinnerElement = nativeElement.querySelector('.adf-cloud-edit-task-filter-loading-margin');
expect(matSpinnerElement).toBeDefined(); expect(matSpinnerElement).toBeDefined();
}); });
@@ -296,15 +306,11 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
expect(saveButton.disabled).toBe(true); expect(saveButton.disabled).toBe(true);
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]'); const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
expect(deleteButton.disabled).toBe(true); expect(deleteButton.disabled).toBe(true);
}); });
@@ -313,15 +319,11 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
expect(saveButton.disabled).toBe(true); expect(saveButton.disabled).toBe(true);
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]'); const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
expect(deleteButton.disabled).toBe(false); expect(deleteButton.disabled).toBe(false);
}); });
@@ -330,20 +332,20 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editTaskFilterForm.valueChanges component.editTaskFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toBe(false); expect(saveButton.disabled).toBe(false);
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
const sortOptions = fixture.debugElement.queryAll(By.css('.mat-option-text')); const sortOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
@@ -353,13 +355,9 @@ describe('EditTaskFilterCloudComponent', () => {
it('should disable save button if the filter is not changed for custom filter', async () => { it('should disable save button if the filter is not changed for custom filter', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
expect(saveButton.disabled).toBe(true); expect(saveButton.disabled).toBe(true);
}); });
}); });
@@ -371,25 +369,17 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]');
expect(saveButton.disabled).toEqual(true); expect(saveButton.disabled).toEqual(true);
}); });
it('should disable saveAs button if the process filter is not changed for custom filter', async () => { it('should disable saveAs button if the process filter is not changed for custom filter', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]');
expect(saveButton.disabled).toEqual(true); expect(saveButton.disabled).toEqual(true);
}); });
@@ -400,20 +390,20 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editTaskFilterForm.valueChanges component.editTaskFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toEqual(false); expect(saveButton.disabled).toEqual(false);
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -424,20 +414,20 @@ describe('EditTaskFilterCloudComponent', () => {
it('should enable saveAs button if the filter values are changed for custom filter', (done) => { it('should enable saveAs button if the filter values are changed for custom filter', (done) => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
component.editTaskFilterForm.valueChanges component.editTaskFilterForm.valueChanges
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe(() => { .subscribe(() => {
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
fixture.detectChanges(); fixture.detectChanges();
expect(saveButton.disabled).toEqual(false); expect(saveButton.disabled).toEqual(false);
done(); done();
}); });
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -451,31 +441,25 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-status"]');
await fixture.whenStable(); const assigneeElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-assignee"]');
const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"]');
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-status"]'); const orderElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-order"]');
const assigneeElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-assignee"]');
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"]');
const orderElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-order"]');
expect(assigneeElement).toBeDefined(); expect(assigneeElement).toBeDefined();
expect(stateElement.textContent.trim()).toBe('ADF_CLOUD_TASK_FILTERS.STATUS.CREATED'); expect(stateElement.textContent.trim()).toBe('ADF_CLOUD_TASK_FILTERS.STATUS.CREATED');
expect(sortElement.textContent.trim()).toBe('id'); expect(sortElement.textContent.trim()).toBe('id');
expect(orderElement.textContent.trim()).toBe('ADF_CLOUD_TASK_FILTERS.DIRECTION.ASCENDING'); expect(orderElement.textContent.trim()).toBe('ADF_CLOUD_TASK_FILTERS.DIRECTION.ASCENDING');
}); });
it('should display all the statuses that are defined in the task filter', () => { it('should display all the statuses that are defined in the task filter', async () => {
await clickExpansionPanel();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-status"]');
expansionPanel.click();
fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-status"]');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const statusOptions = fixture.debugElement.queryAll(By.css('[data-automation-id="adf-cloud-edit-task-property-options-status"]')); const statusOptions = fixture.debugElement.queryAll(By.css('[data-automation-id="adf-cloud-edit-task-property-options-status"]'));
@@ -489,10 +473,9 @@ describe('EditTaskFilterCloudComponent', () => {
it('should display sort drop down', async () => { it('should display sort drop down', async () => {
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"]');
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"]');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -504,10 +487,9 @@ describe('EditTaskFilterCloudComponent', () => {
it('should display order drop down', async () => { it('should display order drop down', async () => {
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const orderElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-order"]');
const orderElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-order"]');
orderElement.click(); orderElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -572,7 +554,7 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const peopleCloudComponent = fixture.debugElement.nativeElement.querySelector('adf-cloud-people'); const peopleCloudComponent = nativeElement.querySelector<HTMLElement>('adf-cloud-people');
expect(peopleCloudComponent).toBeTruthy(); expect(peopleCloudComponent).toBeTruthy();
}); });
@@ -624,7 +606,7 @@ describe('EditTaskFilterCloudComponent', () => {
component.ngOnChanges({ id: mockTaskFilterIdChange }); component.ngOnChanges({ id: mockTaskFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-dueDateRange"] .mat-select-trigger'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-process-property-dueDateRange"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -717,7 +699,7 @@ describe('EditTaskFilterCloudComponent', () => {
component.filterProperties = ['assignment']; component.filterProperties = ['assignment'];
component.ngOnChanges({ id: mockTaskFilterIdChange }); component.ngOnChanges({ id: mockTaskFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
const assignmentComponent = fixture.debugElement.nativeElement.querySelector('adf-cloud-task-assignment-filter'); const assignmentComponent = nativeElement.querySelector<HTMLElement>('adf-cloud-task-assignment-filter');
expect(assignmentComponent).toBeTruthy(); expect(assignmentComponent).toBeTruthy();
}); });
@@ -822,10 +804,8 @@ describe('EditTaskFilterCloudComponent', () => {
it('should display default sort properties', async () => { it('should display default sort properties', async () => {
component.ngOnChanges({ id: mockTaskFilterIdChange }); component.ngOnChanges({ id: mockTaskFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"]');
fixture.detectChanges();
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"]');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -849,10 +829,8 @@ describe('EditTaskFilterCloudComponent', () => {
component.ngOnChanges({ id: mockTaskFilterIdChange }); component.ngOnChanges({ id: mockTaskFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"]');
fixture.detectChanges();
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"]');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -870,10 +848,8 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
component.sortProperties = []; component.sortProperties = [];
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); const sortElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"]');
fixture.detectChanges();
const sortElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"]');
sortElement.click(); sortElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -892,15 +868,11 @@ describe('EditTaskFilterCloudComponent', () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
component.ngOnChanges({ id: mockTaskFilterIdChange }); component.ngOnChanges({ id: mockTaskFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveAsButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
await fixture.whenStable(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
const saveAsButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]');
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
expect(component.taskFilterActions.map(action => action.actionType)).toEqual(['save', 'saveAs', 'delete']); expect(component.taskFilterActions.map(action => action.actionType)).toEqual(['save', 'saveAs', 'delete']);
expect(component.taskFilterActions.length).toBe(3); expect(component.taskFilterActions.length).toBe(3);
expect(saveButton.disabled).toBe(true); expect(saveButton.disabled).toBe(true);
@@ -917,18 +889,14 @@ describe('EditTaskFilterCloudComponent', () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click();
fixture.detectChanges(); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]');
expect(component.taskFilterActions.map(action => action.actionType)).toEqual(['save']); expect(component.taskFilterActions.map(action => action.actionType)).toEqual(['save']);
expect(component.taskFilterActions.length).toBe(1); expect(component.taskFilterActions.length).toBe(1);
expect(saveButton.disabled).toBeTruthy(); expect(saveButton.disabled).toBeTruthy();
const saveAsButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]'); const saveAsButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]'); const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
expect(saveAsButton).toBeFalsy(); expect(saveAsButton).toBeFalsy();
expect(deleteButton).toBeFalsy(); expect(deleteButton).toBeFalsy();
}); });
@@ -939,18 +907,19 @@ describe('EditTaskFilterCloudComponent', () => {
component.ngOnChanges({ id: mockTaskFilterIdChange }); component.ngOnChanges({ id: mockTaskFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
const lastModifiedToControl: AbstractControl = component.editTaskFilterForm.get('lastModifiedTo'); const date = new Date();
lastModifiedToControl.setValue(new Date().toISOString()); const lastModifiedToControl = component.editTaskFilterForm.get('lastModifiedTo');
const lastModifiedToFilter = moment(lastModifiedToControl.value); lastModifiedToControl.setValue(date.toISOString());
lastModifiedToFilter.set({
hour: 23, const lastModifiedToFilter = set(date, {
minute: 59, hours: 23,
second: 59 minutes: 59,
}); seconds: 59
}).toISOString();
component.filterChange.subscribe(() => { component.filterChange.subscribe(() => {
if (component.changedTaskFilter instanceof TaskFilterCloudModel) { if (component.changedTaskFilter instanceof TaskFilterCloudModel) {
expect(component.changedTaskFilter.lastModifiedTo).toEqual(lastModifiedToFilter.toISOString(true)); expect(component.changedTaskFilter.lastModifiedTo).toEqual(lastModifiedToFilter);
} }
done(); done();
}); });
@@ -971,11 +940,11 @@ describe('EditTaskFilterCloudComponent', () => {
spyOn(service, 'updateFilter').and.returnValue(of([new TaskFilterCloudModel({ name: 'mock-filter-name' })])); spyOn(service, 'updateFilter').and.returnValue(of([new TaskFilterCloudModel({ name: 'mock-filter-name' })]));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = nativeElement.querySelector<HTMLElement>('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
tick(); tick();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
tick(); tick();
@@ -984,7 +953,7 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
tick(550); tick(550);
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-save"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-save"]');
saveButton.dispatchEvent(new Event('click')); saveButton.dispatchEvent(new Event('click'));
fixture.detectChanges(); fixture.detectChanges();
tick(); tick();
@@ -996,16 +965,14 @@ describe('EditTaskFilterCloudComponent', () => {
it('should emit delete event and delete the filter on click of delete button', async () => { it('should emit delete event and delete the filter on click of delete button', async () => {
spyOn(service, 'deleteFilter').and.returnValue(of(null)); spyOn(service, 'deleteFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]'); const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
expect(deleteButton.getAttribute('disabled')).toBeNull(); expect(deleteButton.getAttribute('disabled')).toBeNull();
deleteButton.click(); deleteButton.click();
expect(service.deleteFilter).toHaveBeenCalled(); expect(service.deleteFilter).toHaveBeenCalled();
@@ -1015,12 +982,9 @@ describe('EditTaskFilterCloudComponent', () => {
it('should emit saveAs event and add filter on click saveAs button', async () => { it('should emit saveAs event and add filter on click saveAs button', async () => {
spyOn(service, 'addFilter').and.returnValue(of(null)); spyOn(service, 'addFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
await clickExpansionPanel();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
expansionPanel.click();
fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -1029,7 +993,7 @@ describe('EditTaskFilterCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const saveButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-saveAs"]'); const saveButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-saveAs"]');
saveButton.dispatchEvent(new Event('click')); saveButton.dispatchEvent(new Event('click'));
fixture.detectChanges(); fixture.detectChanges();
afterClosedSubject.next({ afterClosedSubject.next({
@@ -1048,16 +1012,14 @@ describe('EditTaskFilterCloudComponent', () => {
spyOn(service, 'deleteFilter').and.returnValue(of([])); spyOn(service, 'deleteFilter').and.returnValue(of([]));
const restoreDefaultFiltersSpy = spyOn(component, 'restoreDefaultTaskFilters').and.returnValue(of([])); const restoreDefaultFiltersSpy = spyOn(component, 'restoreDefaultTaskFilters').and.returnValue(of([]));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]'); const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
expect(deleteButton.disabled).toBe(false); expect(deleteButton.disabled).toBe(false);
deleteButton.click(); deleteButton.click();
expect(service.deleteFilter).toHaveBeenCalled(); expect(service.deleteFilter).toHaveBeenCalled();
@@ -1069,16 +1031,14 @@ describe('EditTaskFilterCloudComponent', () => {
spyOn(service, 'deleteFilter').and.returnValue(of([new TaskFilterCloudModel({ name: 'mock-filter-name' })])); spyOn(service, 'deleteFilter').and.returnValue(of([new TaskFilterCloudModel({ name: 'mock-filter-name' })]));
const restoreDefaultFiltersSpy = spyOn(component, 'restoreDefaultTaskFilters').and.returnValue(of([])); const restoreDefaultFiltersSpy = spyOn(component, 'restoreDefaultTaskFilters').and.returnValue(of([]));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); await clickExpansionPanel();
expansionPanel.click(); const stateElement = nativeElement.querySelector<HTMLElement>('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
fixture.detectChanges();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-task-property-sort"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]'); const deleteButton = nativeElement.querySelector<HTMLButtonElement>('[data-automation-id="adf-filter-action-delete"]');
expect(deleteButton.disabled).toBe(false); expect(deleteButton.disabled).toBe(false);
deleteButton.click(); deleteButton.click();
expect(service.deleteFilter).toHaveBeenCalled(); expect(service.deleteFilter).toHaveBeenCalled();

View File

@@ -15,21 +15,14 @@
* limitations under the License. * limitations under the License.
*/ */
import { Component, ViewEncapsulation } from '@angular/core'; import { Component, ViewEncapsulation, inject } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { DateAdapter } from '@angular/material/core';
import { MatDialog } from '@angular/material/dialog';
import { takeUntil, map } from 'rxjs/operators'; import { takeUntil, map } from 'rxjs/operators';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import moment, { Moment } from 'moment';
import { TaskFilterCloudModel, TaskFilterProperties, TaskFilterAction, TaskStatusFilter } from '../../models/filter-cloud.model'; import { TaskFilterCloudModel, TaskFilterProperties, TaskFilterAction, TaskStatusFilter } from '../../models/filter-cloud.model';
import { TaskFilterCloudService } from '../../services/task-filter-cloud.service'; import { TaskFilterCloudService } from '../../services/task-filter-cloud.service';
import { TranslationService, UserPreferencesService } from '@alfresco/adf-core';
import { AppsProcessCloudService } from '../../../../app/services/apps-process-cloud.service';
import { DateCloudFilterType } from '../../../../models/date-cloud-filter.model'; import { DateCloudFilterType } from '../../../../models/date-cloud-filter.model';
import { TaskCloudService } from '../../../services/task-cloud.service';
import { BaseEditTaskFilterCloudComponent, DropdownOption } from './base-edit-task-filter-cloud.component'; import { BaseEditTaskFilterCloudComponent, DropdownOption } from './base-edit-task-filter-cloud.component';
import { set } from 'date-fns';
@Component({ @Component({
selector: 'adf-cloud-edit-task-filter', selector: 'adf-cloud-edit-task-filter',
@@ -38,16 +31,10 @@ import { BaseEditTaskFilterCloudComponent, DropdownOption } from './base-edit-ta
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None
}) })
export class EditTaskFilterCloudComponent extends BaseEditTaskFilterCloudComponent<TaskFilterCloudModel> { export class EditTaskFilterCloudComponent extends BaseEditTaskFilterCloudComponent<TaskFilterCloudModel> {
constructor( private taskFilterCloudService = inject(TaskFilterCloudService);
formBuilder: UntypedFormBuilder,
dialog: MatDialog, constructor() {
translateService: TranslationService, super();
private taskFilterCloudService: TaskFilterCloudService,
dateAdapter: DateAdapter<Moment>,
userPreferencesService: UserPreferencesService,
appsProcessCloudService: AppsProcessCloudService,
taskCloudService: TaskCloudService) {
super(formBuilder, dateAdapter, userPreferencesService, appsProcessCloudService, taskCloudService, dialog, translateService);
} }
assignNewFilter(model: TaskFilterCloudModel) { assignNewFilter(model: TaskFilterCloudModel) {
@@ -88,13 +75,15 @@ export class EditTaskFilterCloudComponent extends BaseEditTaskFilterCloudCompone
private setLastModifiedToFilter(formValues: TaskFilterCloudModel) { private setLastModifiedToFilter(formValues: TaskFilterCloudModel) {
if (formValues.lastModifiedTo && Date.parse(formValues.lastModifiedTo.toString())) { if (formValues.lastModifiedTo && Date.parse(formValues.lastModifiedTo.toString())) {
const lastModifiedToFilterValue = moment(formValues.lastModifiedTo); const lastModifiedToFilterValue = set(
lastModifiedToFilterValue.set({ new Date(formValues.lastModifiedTo),
hour: 23, {
minute: 59, hours: 23,
second: 59 minutes: 59,
}); seconds: 59
formValues.lastModifiedTo = lastModifiedToFilterValue.toISOString(true); }
);
formValues.lastModifiedTo = lastModifiedToFilterValue.toISOString();
} }
} }

View File

@@ -15,9 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { import { LogService, FormFieldModel, FormModel, DateFnsUtils, AdfDateFnsAdapter, ADF_DATE_FORMATS } from '@alfresco/adf-core';
LogService, UserPreferencesService, UserPreferenceValues, FormFieldModel, FormModel, DateFnsUtils
} from '@alfresco/adf-core';
import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation, OnDestroy } from '@angular/core'; import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation, OnDestroy } from '@angular/core';
import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core'; import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import { EMPTY, Observable, Subject } from 'rxjs'; import { EMPTY, Observable, Subject } from 'rxjs';
@@ -28,7 +26,6 @@ import { switchMap, defaultIfEmpty, takeUntil } from 'rxjs/operators';
import { UntypedFormBuilder, AbstractControl, Validators, UntypedFormGroup, UntypedFormControl } from '@angular/forms'; import { UntypedFormBuilder, AbstractControl, Validators, UntypedFormGroup, UntypedFormControl } from '@angular/forms';
import { UserProcessModel } from '../../common/models/user-process.model'; import { UserProcessModel } from '../../common/models/user-process.model';
import { isValid } from 'date-fns'; import { isValid } from 'date-fns';
import { DateFnsAdapter, MAT_DATE_FNS_FORMATS } from '@angular/material-date-fns-adapter';
const FORMAT_DATE = 'DD/MM/YYYY'; const FORMAT_DATE = 'DD/MM/YYYY';
const MAX_LENGTH = 255; const MAX_LENGTH = 255;
@@ -38,8 +35,8 @@ const MAX_LENGTH = 255;
templateUrl: './start-task.component.html', templateUrl: './start-task.component.html',
styleUrls: ['./start-task.component.scss'], styleUrls: ['./start-task.component.scss'],
providers: [ providers: [
{ provide: DateAdapter, useClass: DateFnsAdapter }, { provide: DateAdapter, useClass: AdfDateFnsAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_DATE_FNS_FORMATS }], { provide: MAT_DATE_FORMATS, useValue: ADF_DATE_FORMATS }],
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None
}) })
export class StartTaskComponent implements OnInit, OnDestroy { export class StartTaskComponent implements OnInit, OnDestroy {
@@ -75,8 +72,6 @@ export class StartTaskComponent implements OnInit, OnDestroy {
private onDestroy$ = new Subject<boolean>(); private onDestroy$ = new Subject<boolean>();
constructor(private taskService: TaskListService, constructor(private taskService: TaskListService,
private dateAdapter: DateAdapter<DateFnsAdapter>,
private userPreferencesService: UserPreferencesService,
private formBuilder: UntypedFormBuilder, private formBuilder: UntypedFormBuilder,
private logService: LogService) { private logService: LogService) {
} }
@@ -90,11 +85,6 @@ export class StartTaskComponent implements OnInit, OnDestroy {
this.field = new FormFieldModel(new FormModel(), { id: this.assigneeId, value: this.assigneeId, placeholder: 'Assignee' }); this.field = new FormFieldModel(new FormModel(), { id: this.assigneeId, value: this.assigneeId, placeholder: 'Assignee' });
this.userPreferencesService
.select(UserPreferenceValues.Locale)
.pipe(takeUntil(this.onDestroy$))
.subscribe(locale => this.dateAdapter.setLocale(DateFnsUtils.getLocaleFromString(locale)));
this.loadFormsTask(); this.loadFormsTask();
this.buildForm(); this.buildForm();
} }
@@ -142,10 +132,10 @@ export class StartTaskComponent implements OnInit, OnDestroy {
} }
this.taskService.createNewTask(this.taskDetailsModel) this.taskService.createNewTask(this.taskDetailsModel)
.pipe( .pipe(
switchMap((createRes: any) => switchMap((createRes) =>
this.attachForm(createRes.id, this.taskDetailsModel.formKey).pipe( this.attachForm(createRes.id, this.taskDetailsModel.formKey).pipe(
defaultIfEmpty(createRes), defaultIfEmpty(createRes),
switchMap((attachRes: any) => switchMap((attachRes) =>
this.assignTaskByUserId(createRes.id, this.assigneeId).pipe( this.assignTaskByUserId(createRes.id, this.assigneeId).pipe(
defaultIfEmpty(attachRes ? attachRes : createRes) defaultIfEmpty(attachRes ? attachRes : createRes)
) )
@@ -183,7 +173,7 @@ export class StartTaskComponent implements OnInit, OnDestroy {
return firstName + delimiter + lastName; return firstName + delimiter + lastName;
} }
onDateChanged(newDateValue: any) { onDateChanged(newDateValue: Date | string) {
this.dateError = false; this.dateError = false;
if (newDateValue) { if (newDateValue) {
@@ -233,12 +223,11 @@ export class StartTaskComponent implements OnInit, OnDestroy {
return response; return response;
} }
private assignTaskByUserId(taskId: string, userId: any): Observable<any> { private assignTaskByUserId(taskId: string, userId: any): Observable<TaskDetailsModel> {
let response: any = EMPTY;
if (taskId && userId) { if (taskId && userId) {
response = this.taskService.assignTaskByUserId(taskId, userId); return this.taskService.assignTaskByUserId(taskId, userId);
} }
return response; return EMPTY;
} }
private loadFormsTask(): void { private loadFormsTask(): void {