Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Extend queryProps instead of modifying query itself

Oliver Günther3db7154c88ea
diff --git a/frontend/src/app/features/work-packages/components/wp-list/wp-list-checksum.service.ts b/frontend/src/app/features/work-packages/components/wp-list/wp-list-checksum.service.ts
index 69f32773e92..e84fd8a9f2a 100644
--- a/frontend/src/app/features/work-packages/components/wp-list/wp-list-checksum.service.ts
+++ b/frontend/src/app/features/work-packages/components/wp-list/wp-list-checksum.service.ts
@@ -142,7 +142,13 @@ export class WorkPackagesListChecksumService {
}
private getNewChecksum(query:QueryResource, pagination:WorkPackageViewPagination) {
- return this.UrlParamsHelper.encodeQueryJsonParams(query, _.pick(pagination, ['page', 'perPage']));
+ return this.UrlParamsHelper.encodeQueryJsonParams(
+ query,
+ {
+ pa: pagination.page,
+ pp: pagination.perPage,
+ },
+ );
}
private maintainUrlQueryState(id:string|null, checksum:string|null):TransitionPromise {
diff --git a/frontend/src/app/features/work-packages/components/wp-list/wp-list.service.ts b/frontend/src/app/features/work-packages/components/wp-list/wp-list.service.ts
index 50c6a301ffc..c47e443dc61 100644
--- a/frontend/src/app/features/work-packages/components/wp-list/wp-list.service.ts
+++ b/frontend/src/app/features/work-packages/components/wp-list/wp-list.service.ts
@@ -35,10 +35,19 @@ import { Injectable } from '@angular/core';
import { UrlParamsHelperService } from 'core-app/features/work-packages/components/wp-query/url-params-helper';
import { ToastService } from 'core-app/shared/components/toaster/toast.service';
import { I18nService } from 'core-app/core/i18n/i18n.service';
-import { from, Observable, of } from 'rxjs';
+import {
+ from,
+ Observable,
+ of,
+} from 'rxjs';
import { input } from 'reactivestates';
import {
- catchError, mapTo, mergeMap, share, switchMap, take,
+ catchError,
+ mapTo,
+ mergeMap,
+ share,
+ switchMap,
+ take,
} from 'rxjs/operators';
import {
WorkPackageViewPaginationService,
@@ -163,8 +172,7 @@ export class WorkPackagesListService {
* Reloads the current query and set the pagination to the first page.
*/
public reloadQuery(query:QueryResource, projectIdentifier?:string):Observable<QueryResource> {
- const pagination = { ...this.wpTablePagination.current, page: 1 };
- const queryParams = this.UrlParamsHelper.encodeQueryJsonParams(query, pagination);
+ const queryParams = this.extractParamsFromQuery(query, { pa: 1 });
this.queryRequests.clear();
this.queryRequests.putValue({
@@ -179,6 +187,25 @@ export class WorkPackagesListService {
);
}
+ /**
+ * Extract a set of query params from the current query resource
+ * @param query The query to derive props from
+ * @param additional Additional props to append
+ */
+ public extractParamsFromQuery(
+ query:QueryResource,
+ additional:Record<string, unknown> = {},
+ ):string {
+ return this.UrlParamsHelper.encodeQueryJsonParams(
+ query,
+ {
+ pa: this.wpTablePagination.current.page,
+ pp: this.wpTablePagination.current.perPage,
+ ...additional,
+ },
+ );
+ }
+
/**
* Update the query from an existing (probably unsaved) query.
*
diff --git a/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.spec.ts b/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.spec.ts
index 2f6ef2f868d..27612c0aae9 100644
--- a/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.spec.ts
+++ b/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.spec.ts
@@ -105,14 +105,14 @@ describe('UrlParamsHelper', () => {
};
additional = {
- page: 10,
- perPage: 100,
+ pa: 10,
+ pp: 100,
};
});
it('should encode query to params JSON', () => {
const encodedJSON = UrlParamsHelper.encodeQueryJsonParams(query, additional);
- const expectedJSON = '{"c":["type","status","soße"],"s":true,"tv":true,"tzl":"days","hl":"disabled","hi":true,"g":"status","t":"type:desc","f":[{"n":"soße","o":"=","v":["knoblauch"]},{"n":"created_at","o":"<t-","v":["5"]}],"pa":10,"pp":100}';
+ const expectedJSON = '{"c":["type","status","soße"],"hi":true,"g":"status","s":true,"tv":true,"tzl":"days","hl":"disabled","t":"type:desc","f":[{"n":"soße","o":"=","v":["knoblauch"]},{"n":"created_at","o":"<t-","v":["5"]}],"pa":10,"pp":100}'
expect(encodedJSON).toEqual(expectedJSON);
});
diff --git a/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.ts b/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.ts
index 0caf24639ae..b56bb909892 100644
--- a/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.ts
+++ b/frontend/src/app/features/work-packages/components/wp-query/url-params-helper.ts
@@ -33,8 +33,47 @@ import idFromLink from 'core-app/features/hal/helpers/id-from-link';
import isPersistedResource from 'core-app/features/hal/helpers/is-persisted-resource';
import { Injectable } from '@angular/core';
import { QueryFilterInstanceResource } from 'core-app/features/hal/resources/query-filter-instance-resource';
-import { ApiV3Filter, FilterOperator } from 'core-app/shared/helpers/api-v3/api-v3-filter-builder';
+import {
+ ApiV3Filter,
+ FilterOperator,
+} from 'core-app/shared/helpers/api-v3/api-v3-filter-builder';
import { PaginationService } from 'core-app/shared/components/table-pagination/pagination-service';
+import { HalResource } from 'core-app/features/hal/resources/hal-resource';
+
+export interface QueryPropsFilter {
+ n:string;
+ o:string
+ v:unknown[];
+}
+
+export interface QueryProps {
+ // Columns
+ c:string[];
+ // Sums enabled?
+ s?:boolean;
+ // Sort by criteria
+ t?:string;
+ // Group by criteria
+ g:string|null;
+ // Filters
+ f:QueryPropsFilter[];
+ // Hierarchies
+ hi:boolean;
+ // Highlighting mode
+ hl?:string;
+ // Highlighted attributes
+ hla?:string[];
+ // Display representation
+ dr?:string;
+ // Pagination
+ pa?:string|number;
+ pp?:string|number;
+
+ // Timeline options
+ tv?:boolean;
+ tzl?:string;
+ tll?:string;
+}
@Injectable({ providedIn: 'root' })
export class UrlParamsHelperService {
@@ -68,85 +107,90 @@ export class UrlParamsHelperService {
return parts.join('&');
}
- public encodeQueryJsonParams(query:QueryResource, additional:any = {}) {
- let paramsData:any = {};
-
- paramsData = this.encodeColumns(paramsData, query);
- paramsData = this.encodeSums(paramsData, query);
- paramsData = this.encodeTimelineVisible(paramsData, query);
- paramsData = this.encodeHighlightingMode(paramsData, query);
- paramsData = this.encodeHighlightedAttributes(paramsData, query);
- paramsData.hi = !!query.showHierarchies;
- paramsData.g = _.get(query.groupBy, 'id', '');
- paramsData = this.encodeSortBy(paramsData, query);
- paramsData = this.encodeFilters(paramsData, query.filters);
- paramsData.pa = additional.page;
- paramsData.pp = additional.perPage;
- paramsData.dr = query.displayRepresentation;
+ public encodeQueryJsonParams(
+ query:QueryResource,
+ extender?:Partial<QueryProps>|((paramsData:QueryProps) => QueryProps),
+ ):string {
+ const paramsData:QueryProps = {
+ c: query.columns.map((column) => column.id),
+ hi: !!query.showHierarchies,
+ g: _.get(query.groupBy, 'id', ''),
+ dr: query.displayRepresentation,
+ ...this.encodeSums(query),
+ ...this.encodeTimelineVisible(query),
+ ...this.encodeHighlightingMode(query),
+ ...this.encodeHighlightedAttributes(query),
+ ...this.encodeSortBy(query),
+ ...this.encodeFilters(query.filters),
+ };
- return JSON.stringify(paramsData);
- }
+ if (typeof extender === 'function') {
+ return JSON.stringify(extender(paramsData));
+ }
- private encodeColumns(paramsData:any, query:QueryResource) {
- paramsData.c = query.columns.map((column) => column.id);
+ if (typeof extender === 'object') {
+ return JSON.stringify(_.merge(paramsData, extender));
+ }
- return paramsData;
+ return JSON.stringify(paramsData);
}
- private encodeSums(paramsData:any, query:QueryResource) {
+ private encodeSums(query:QueryResource):Partial<QueryProps> {
if (query.sums) {
- paramsData.s = query.sums;
+ return { s: query.sums };
}
- return paramsData;
+
+ return {};
}
- private encodeHighlightingMode(paramsData:any, query:QueryResource) {
+ private encodeHighlightingMode(query:QueryResource):Partial<QueryProps> {
if (query.highlightingMode && (isPersistedResource(query) || query.highlightingMode !== 'inline')) {
- paramsData.hl = query.highlightingMode;
+ return { hl: query.highlightingMode };
}
- return paramsData;
+
+ return {};
}
- private encodeHighlightedAttributes(paramsData:any, query:QueryResource) {
+ private encodeHighlightedAttributes(query:QueryResource):Partial<QueryProps> {
if (query.highlightingMode === 'inline') {
if (Array.isArray(query.highlightedAttributes) && query.highlightedAttributes.length > 0) {
- paramsData.hla = query.highlightedAttributes.map((el) => el.id);
+ return { hla: query.highlightedAttributes.map((el) => el.id as string) };
}
}
- return paramsData;
+
+ return {};
}
- private encodeSortBy(paramsData:any, query:QueryResource) {
+ private encodeSortBy(query:QueryResource):Partial<QueryProps> {
if (query.sortBy) {
- paramsData.t = query
- .sortBy
- .map((sort:QuerySortByResource) => sort.id!.replace('-', ':'))
- .join();
+ return {
+ t: query
+ .sortBy
+ .map((sort:QuerySortByResource) => (sort.id as string).replace('-', ':'))
+ .join(),
+ };
}
- return paramsData;
+
+ return {};
}
- public encodeFilters(paramsData:any, filters:QueryFilterInstanceResource[]) {
+ public encodeFilters(filters:QueryFilterInstanceResource[]):Pick<QueryProps, 'f'> {
if (filters && filters.length > 0) {
- paramsData.f = filters
- .map((filter:any) => {
- const { id } = filter;
-
- const operator = filter.operator.id;
+ const filterProps:QueryPropsFilter[] = filters.map((filter) => ({
+ n: filter.id,
+ o: filter.operator.id,
+ v: filter.values.map((value:HalResource|string) => this.queryFilterValueToParam(value)),
+ }));
- return {
- n: id,
- o: operator,
- v: _.map(filter.values, (v) => this.queryFilterValueToParam(v)),
- };
- });
- } else {
- paramsData.f = [];
+ return { f: filterProps };
}
- return paramsData;
+
+ return { f: [] };
}
- private encodeTimelineVisible(paramsData:any, query:QueryResource) {
+ private encodeTimelineVisible(query:QueryResource):Partial<QueryProps> {
+ const paramsData:Partial<QueryProps> = {};
+
if (query.timelineVisible) {
paramsData.tv = query.timelineVisible;
@@ -158,6 +202,7 @@ export class UrlParamsHelperService {
} else {
paramsData.tv = false;
}
+
return paramsData;
}
@@ -282,25 +327,31 @@ export class UrlParamsHelperService {
return _.extend(additionalParams, queryData);
}
- public queryFilterValueToParam(value:any) {
+ public queryFilterValueToParam(value:HalResource|string|boolean):string {
if (typeof (value) === 'boolean') {
return value ? 't' : 'f';
}
if (!value) {
return '';
- } if (value.id) {
- return value.id.toString();
- } if (value.href) {
- return value.href.split('/').pop().toString();
}
+
+ const halValue = value as HalResource;
+ if (halValue.id) {
+ return halValue.id.toString();
+ }
+ if (halValue.href) {
+ return halValue.href.split('/').pop() as string;
+ }
+
return value.toString();
}
private buildV3GetColumnsFromQueryResource(query:QueryResource) {
if (query.columns) {
return query.columns.map((column:any) => column.id || idFromLink(column.href));
- } if (query._links.columns) {
+ }
+ if (query._links.columns) {
return query._links.columns.map((column:HalLink) => {
const id = column.href!;
diff --git a/frontend/src/app/shared/components/calendar/op-calendar.service.ts b/frontend/src/app/shared/components/calendar/op-calendar.service.ts
index fc0cc96df8f..dd53600c499 100644
--- a/frontend/src/app/shared/components/calendar/op-calendar.service.ts
+++ b/frontend/src/app/shared/components/calendar/op-calendar.service.ts
@@ -30,7 +30,11 @@ import { take } from 'rxjs/operators';
import { HalResourceService } from 'core-app/features/hal/services/hal-resource.service';
import { QueryFilterInstanceResource } from 'core-app/features/hal/resources/query-filter-instance-resource';
import { QueryResource } from 'core-app/features/hal/resources/query-resource';
-import { UrlParamsHelperService } from 'core-app/features/work-packages/components/wp-query/url-params-helper';
+import {
+ QueryProps,
+ QueryPropsFilter,
+ UrlParamsHelperService,
+} from 'core-app/features/work-packages/components/wp-query/url-params-helper';
import { ApiV3Service } from 'core-app/core/apiv3/api-v3.service';
import { UIRouterGlobals } from '@uirouter/core';
import { TimezoneService } from 'core-app/core/datetime/timezone.service';
@@ -150,15 +154,24 @@ export class OpCalendarService extends UntilDestroyedMixin {
this.resizeObs.observe(v.nativeElement);
}
- updateTimeframe(fetchInfo:{ start:Date, end:Date, timeZone:string }, projectIdentifier:string|undefined):void {
- if (this.areFiltersEmpty && this.querySpace.query.value) {
- // nothing to do
- return;
- }
-
+ async updateTimeframe(
+ fetchInfo:{ start:Date, end:Date, timeZone:string },
+ projectIdentifier:string|undefined,
+ ):Promise<unknown> {
const startDate = moment(fetchInfo.start).format('YYYY-MM-DD');
const endDate = moment(fetchInfo.end).format('YYYY-MM-DD');
+ let queryId:string|undefined;
+ if (this.urlParams.query_id) {
+ queryId = this.urlParams.query_id as string;
+ }
+
+ // We derive the necessary props in the following cases
+ // 1. We load a queryId with no props
+ // 2. We load visible query props or empty
+ // 3. We are already loaded and are refetching data (for changed dates, e.g.)
+ let queryProps:string|undefined;
+
if (this.initializingWithQuery) {
// This is the case on initially loading the calendar with a query_id present in the url params but no
// query props to overwrite the query settings.
@@ -167,47 +180,41 @@ export class OpCalendarService extends UntilDestroyedMixin {
// such filter exists yet, we need to add it to the existing filter set.
// In order to do both, we first need to fetch the query as we cannot signal
// to the backend yet to only add this one filter but leave the rest unchanged.
- void this
+ const initialQuery = await this
.apiV3Service
.queries
- .find({ perPage: 0 }, this.urlParams.query_id)
- .toPromise()
- .then((query) => {
- this.updateQueryDateFilter(query, startDate, endDate);
-
- const props = this.urlParamsHelper.encodeQueryJsonParams(query, { perPage: OpCalendarService.MAX_DISPLAYED });
+ .find({ perPage: 0 }, queryId)
+ .toPromise();
- void this
- .wpListService
- .fromQueryParams({ query_id: query.id || undefined, query_props: props })
- .toPromise();
- });
+ queryProps = this.urlParamsHelper.encodeQueryJsonParams(initialQuery, { pa: OpCalendarService.MAX_DISPLAYED });
} else if (this.initializingWithQueryProps) {
// This is the case on initially loading the calendar with query_props present in the url params.
// There might also be a query_id but the settings persisted in it are overwritten by the props.
-
- let queryProps = OpCalendarService.defaultQueryProps(startDate, endDate);
if (this.urlParams.query_props) {
queryProps = decodeURIComponent(this.urlParams.query_props || '');
+ } else {
+ queryProps = OpCalendarService.defaultQueryProps(startDate, endDate);
}
-
- let queryId;
- if (this.urlParams.query_id) {
- queryId = this.urlParams.query_id as string;
- }
-
- void this
- .wpListService
- .fromQueryParams({ query_id: queryId, query_props: queryProps }, projectIdentifier || undefined)
- .toPromise();
} else {
- this.wpTableFilters.modify('datesInterval', (datesIntervalFilter) => {
- // eslint-disable-next-line no-param-reassign
- datesIntervalFilter.values[0] = startDate;
- // eslint-disable-next-line no-param-reassign
- datesIntervalFilter.values[1] = endDate;
- });
+ queryProps = this.urlParamsHelper.encodeQueryJsonParams(
+ this.querySpace.query.value as QueryResource,
+ (props) => {
+ return {
+ ...props,
+ pa: OpCalendarService.MAX_DISPLAYED,
+ f: [
+ ...props.f.filter((filter) => filter.n !== 'datesInterval'),
+ OpCalendarService.dateFilter(startDate, endDate),
+ ],
+ };
+ },
+ );
}
+
+ return this
+ .wpListService
+ .fromQueryParams({ query_id: queryId, query_props: queryProps }, projectIdentifier || undefined)
+ .toPromise();
}
private defaultOptions():CalendarOptions {
@@ -286,16 +293,18 @@ export class OpCalendarService extends UntilDestroyedMixin {
c: ['id'],
t:
'id:asc',
- f: [{ n: 'status', o: 'o', v: [] },
- { n: 'datesInterval', o: '<>d', v: [startDate, endDate] }],
+ f: [
+ { n: 'status', o: 'o', v: [] },
+ this.dateFilter(startDate, endDate),
+ ],
pp: OpCalendarService.MAX_DISPLAYED,
};
return JSON.stringify(props);
}
- private get initializingWithQuery():boolean {
- return (this.areFiltersEmpty && this.urlParams.query_id && !this.urlParams.query_props) as boolean;
+ private static dateFilter(startDate:string, endDate:string):QueryPropsFilter {
+ return { n: 'datesInterval', o: '<>d', v: [startDate, endDate] };
}
private get initializingWithQueryProps():boolean {
@@ -304,36 +313,12 @@ export class OpCalendarService extends UntilDestroyedMixin {
return (this.areFiltersEmpty || this.urlParams.query_props) as boolean;
}
- private get urlParams() {
- return this.$state.params;
- }
-
- private updateQueryDateFilter(query:QueryResource, startDate:string, endDate:string) {
- const filter = query.filters.find((filterInstance) => filterInstance.filter.href === '/api/v3/queries/filters/datesInterval');
-
- if (filter) {
- filter.values = [startDate, endDate];
- } else {
- query.filters.push(this.dateFilter(startDate, endDate));
- }
+ private get initializingWithQuery():boolean {
+ return (this.areFiltersEmpty && this.urlParams.query_id && !this.urlParams.query_props) as boolean;
}
- private dateFilter(startDate:string, endDate:string):QueryFilterInstanceResource {
- return this.halResourceService.createHalResource({
- _type: 'QueryFilterInstance',
- values: [startDate, endDate],
- _links: {
- filter: {
- href: '/api/v3/queries/filters/datesInterval',
- },
- operator: {
- href: '/api/v3/queries/operators/%3C%3Ed',
- },
- schema: {
- href: '/api/v3/queries/filter_instance_schemas/datesInterval',
- },
- },
- });
+ private get urlParams() {
+ return this.uiRouterGlobals.params;
}
private get areFiltersEmpty() {
@@ -341,7 +326,7 @@ export class OpCalendarService extends UntilDestroyedMixin {
}
private get initialDate():string|undefined {
- const date = this.uiRouterGlobals.params.cdate as string|undefined;
+ const date = this.urlParams.cdate as string|undefined;
if (date) {
return this.timezoneService.formattedISODate(date);
}