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
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Extract non-workPackage specific logic to a separate service to be able to use it other calendars as well (e.g spent time graph)
Henriette Darge580ee22d89ef
diff --git a/frontend/src/app/features/calendar/op-calendar.service.ts b/frontend/src/app/features/calendar/op-calendar.service.tsindex 4711bd6a553..a74417ee869 100644--- a/frontend/src/app/features/calendar/op-calendar.service.ts+++ b/frontend/src/app/features/calendar/op-calendar.service.ts@@ -1,160 +1,25 @@import {ElementRef,Injectable,- Injector,} from '@angular/core';-import {- CalendarOptions,- DatesSetArg,- DayCellMountArg,- DayHeaderMountArg,- EventApi,- EventDropArg,- SlotLabelMountArg,- SlotLaneMountArg,-} from '@fullcalendar/core';-import { I18nService } from 'core-app/core/i18n/i18n.service';-import { ConfigurationService } from 'core-app/core/config/configuration.service';-import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';-import { DomSanitizer } from '@angular/platform-browser';-import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';-import { splitViewRoute } from 'core-app/features/work-packages/routing/split-view-routes.helper';-import { StateService } from '@uirouter/angular';-import { WorkPackageCollectionResource } from 'core-app/features/hal/resources/wp-collection-resource';-import { ToastService } from 'core-app/shared/components/toaster/toast.service';-import {- Observable,- Subject,-} from 'rxjs';-import { WorkPackageViewFiltersService } from 'core-app/features/work-packages/routing/wp-view-base/view-services/wp-view-filters.service';-import { WorkPackagesListService } from 'core-app/features/work-packages/components/wp-list/wp-list.service';-import { IsolatedQuerySpace } from 'core-app/features/work-packages/directives/query-space/isolated-query-space';+import { Subject } from 'rxjs';import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';-import { take } from 'rxjs/operators';-import { HalResourceService } from 'core-app/features/hal/services/hal-resource.service';-import { QueryResource } from 'core-app/features/hal/resources/query-resource';-import {- 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';-import { WorkPackagesListChecksumService } from 'core-app/features/work-packages/components/wp-list/wp-list-checksum.service';-import {- EventReceiveArg,- EventResizeDoneArg,-} from '@fullcalendar/interaction';-import { HalResourceEditingService } from 'core-app/shared/components/fields/edit/services/hal-resource-editing.service';-import { ResourceChangeset } from 'core-app/shared/components/fields/changeset/resource-changeset';-import * as moment from 'moment';-import { WorkPackageViewSelectionService } from 'core-app/features/work-packages/routing/wp-view-base/view-services/wp-view-selection.service';-import { isClickedWithModifier } from 'core-app/shared/helpers/link-handling/link-handling';-import { uiStateLinkClass } from 'core-app/features/work-packages/components/wp-fast-table/builders/ui-state-link-builder';-import { debugLog } from 'core-app/shared/helpers/debug_output';-import { WorkPackageViewContextMenu } from 'core-app/shared/components/op-context-menu/wp-context-menu/wp-view-context-menu.directive';-import { OPContextMenuService } from 'core-app/shared/components/op-context-menu/op-context-menu.service';import { WeekdayService } from 'core-app/core/days/weekday.service';-export interface CalendarViewEvent {- el:HTMLElement;- event:EventApi;-}--// The CalenderOptions typings are missing daygrid hooks-interface CalendarOptionsWithDayGrid extends CalendarOptions {- dayGridDidMount:(data:DayCellMountArg) => void;-}-@Injectable()export class OpCalendarService extends UntilDestroyedMixin {- static MAX_DISPLAYED = 100;-resize$ = new Subject<void>();resizeObs:ResizeObserver;- tooManyResultsText:string|null;-- currentWorkPackages$:Observable<WorkPackageCollectionResource> = this- .querySpace- .results- .values$()- .pipe(- take(1),- );-weekdaysPromise = this.weekdayService.loadWeekdays().toPromise();constructor(- private I18n:I18nService,- private configuration:ConfigurationService,- private sanitizer:DomSanitizer,- private $state:StateService,- readonly injector:Injector,- readonly schemaCache:SchemaCacheService,- readonly toastService:ToastService,- readonly wpTableFilters:WorkPackageViewFiltersService,- readonly wpListService:WorkPackagesListService,- readonly wpListChecksumService:WorkPackagesListChecksumService,- readonly urlParamsHelper:UrlParamsHelperService,- readonly querySpace:IsolatedQuerySpace,- readonly apiV3Service:ApiV3Service,- readonly halResourceService:HalResourceService,- readonly uiRouterGlobals:UIRouterGlobals,- readonly timezoneService:TimezoneService,- readonly halEditing:HalResourceEditingService,- readonly wpTableSelection:WorkPackageViewSelectionService,- readonly contextMenuService:OPContextMenuService,readonly weekdayService:WeekdayService,) {super();}- workPackagesListener$(callbackFn:() => void):void {- this- .querySpace- .results- .values$()- .pipe(- this.untilDestroyed(),- )- .subscribe(() => {- callbackFn();- });- }-- calendarOptions(additionalOptions:CalendarOptions):CalendarOptions {- return { ...this.defaultOptions(), ...additionalOptions };- }-- eventDate(workPackage:WorkPackageResource, type:'start'|'due'):string {- if (this.isMilestone(workPackage)) {- return workPackage.date;- }- return workPackage[`${type}Date`];- }-- isMilestone(workPackage:WorkPackageResource):boolean {- return this.schemaCache.of(workPackage).isMilestone as boolean;- }-- warnOnTooManyResults(collection:WorkPackageCollectionResource, isStatic = false):void {- if (collection.count < collection.total) {- this.tooManyResultsText = this.I18n.t('js.calendar.too_many',- {- count: collection.total,- max: OpCalendarService.MAX_DISPLAYED,- });- } else {- this.tooManyResultsText = null;- }-- if (this.tooManyResultsText && !isStatic) {- this.toastService.addNotice(this.tooManyResultsText);- }- }-resizeObserver(v:ElementRef|undefined):void {if (!v) {return;@@ -167,272 +32,7 @@ export class OpCalendarService extends UntilDestroyedMixin {this.resizeObs.observe(v.nativeElement);}- async updateTimeframe(- fetchInfo:{ start:Date, end:Date, timeZone:string },- projectIdentifier:string|undefined,- ):Promise<unknown> {- if (this.areFiltersEmpty && this.querySpace.query.value) {- // nothing to do- return Promise.resolve();- }-- const startDate = moment(fetchInfo.start).format('YYYY-MM-DD');- const endDate = moment(fetchInfo.end).format('YYYY-MM-DD');-- let queryId:string|null = null;- 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.- // We want to always use the currently displayed time interval to be filtered for- // so we need to adapt any eventually existing dateInterval filter to have that time interval. If no- // 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.- const initialQuery = await this- .apiV3Service- .queries- .find({ pageSize: 0 }, queryId)- .toPromise();-- queryProps = this.generateQueryProps(- initialQuery,- startDate,- endDate,- );- } 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.- if (this.urlParams.query_props) {- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment- const oldQueryProps:{ [key:string]:unknown } = JSON.parse(this.urlParams.query_props);-- // Update the date period of the calendar in the filter- const newQueryProps = {- ...oldQueryProps,- f: [- ...(oldQueryProps.f as QueryPropsFilter[]).filter((filter:QueryPropsFilter) => filter.n !== 'datesInterval'),- OpCalendarService.dateFilter(startDate, endDate),- ],- };-- queryProps = JSON.stringify(newQueryProps);- } else {- queryProps = OpCalendarService.defaultQueryProps(startDate, endDate);- }- } else {- queryProps = this.generateQueryProps(- this.querySpace.query.value as QueryResource,- startDate,- endDate,- );-- // There are no query props, ensure that they are not being shown the next load- this.wpListChecksumService.set(queryId, queryProps);- }-- return this- .wpListService- .fromQueryParams({ query_id: queryId, query_props: queryProps }, projectIdentifier || undefined)- .toPromise();- }-- public generateQueryProps(- query:QueryResource,- startDate:string,- endDate:string,- ):string {- return this.urlParamsHelper.encodeQueryJsonParams(- query,- (props) => ({- ...props,- pp: OpCalendarService.MAX_DISPLAYED,- pa: 1,- f: [- ...props.f.filter((filter) => filter.n !== 'datesInterval'),- OpCalendarService.dateFilter(startDate, endDate),- ],- }),- );- }-- public get initialView():string|undefined {- return this.urlParams.cview as string|undefined;- }-- dateEditable(wp:WorkPackageResource):boolean {- const schema = this.schemaCache.of(wp);- const schemaEditable = schema.isAttributeEditable('startDate') && schema.isAttributeEditable('dueDate');- return (wp.isLeaf || wp.scheduleManually) && schemaEditable;- }-- eventDurationEditable(wp:WorkPackageResource):boolean {- return this.dateEditable(wp) && !this.isMilestone(wp);- }-- /**- * The end date from fullcalendar is open, which means it targets- * the next day instead of current day 23:59:59.- * @param end- */- public getEndDateFromTimestamp(end:Date):string {- return moment(end).subtract(1, 'd').format('YYYY-MM-DD');- }-- public openSplitView(id:string, onlyWhenOpen = false):void {- this.wpTableSelection.setSelection(id, -1);-- // Only open the split view if already open, otherwise only clicking the details opens- if (onlyWhenOpen && !this.$state.includes('**.details.*')) {- return;- }-- void this.$state.go(- `${splitViewRoute(this.$state)}.tabs`,- { workPackageId: id, tabIdentifier: 'overview' },- );- }-- public onCardClicked({ workPackageId, event }:{ workPackageId:string, event:MouseEvent }):void {- if (isClickedWithModifier(event)) {- return;- }-- this.openSplitView(workPackageId, true);- }-- public showEventContextMenu({ workPackageId, event }:{ workPackageId:string, event:MouseEvent }):void {- if (isClickedWithModifier(event)) {- return;- }-- // We want to keep the original context menu on hrefs- // (currently, this is only the id)- if ((event.target as HTMLElement).closest(`.${uiStateLinkClass}`)) {- debugLog('Allowing original context menu on state link');- return;- }-- // Set the selection to single- this.wpTableSelection.setSelection(workPackageId, -1);-- event.preventDefault();-- const handler = new WorkPackageViewContextMenu(this.injector, workPackageId, jQuery(event.target as HTMLElement));- this.contextMenuService.show(handler, event);- }-- private defaultOptions():CalendarOptionsWithDayGrid {- return {- editable: false,- locale: this.I18n.locale,- fixedWeekCount: false,- firstDay: this.configuration.startOfWeek(),- timeZone: this.configuration.isTimezoneSet() ? this.configuration.timezone() : 'local',- height: 'auto',- headerToolbar: {- left: 'prev,next today',- center: 'title',- right: '',- },- initialDate: this.initialDate,- initialView: this.initialView,- datesSet: (dates) => this.updateDateParam(dates),- dayHeaderDidMount: (data:DayHeaderMountArg) => this.applyNonWorkingDay(data),- dayCellDidMount: (data:DayCellMountArg) => this.applyNonWorkingDay(data),- dayGridDidMount: (data:DayCellMountArg) => this.applyNonWorkingDay(data),- slotLaneDidMount: (data:SlotLaneMountArg) => this.applyNonWorkingDay(data),- slotLabelDidMount: (data:SlotLabelMountArg) => this.applyNonWorkingDay(data),- };- }-- private static defaultQueryProps(startDate:string, endDate:string) {- const props = {- c: ['id'],- t:- 'id:asc',- f: [- { n: 'status', o: '*', v: [] },- this.dateFilter(startDate, endDate),- ],- dr: 'cards',- hi: false,- pp: OpCalendarService.MAX_DISPLAYED,- pa: 1,- };-- return JSON.stringify(props);- }-- private static dateFilter(startDate:string, endDate:string):QueryPropsFilter {- return { n: 'datesInterval', o: '<>d', v: [startDate, endDate] };- }-- private get initializingWithQueryProps():boolean {- // Initialise with current query props- // If the filters are empty, they still need to be initialised (with empty props)- return (this.areFiltersEmpty || this.urlParams.query_props) as boolean;- }-- private get initializingWithQuery():boolean {- return this.areFiltersEmpty- && !!this.urlParams.query_id- && !this.urlParams.query_props;- }-- private get urlParams() {- return this.uiRouterGlobals.params;- }-- private get areFiltersEmpty():boolean {- return this.wpTableFilters.isEmpty;- }-- private get initialDate():string|undefined {- const date = this.urlParams.cdate as string|undefined;- if (date) {- return this.timezoneService.formattedISODate(date);- }-- return undefined;- }-- private updateDateParam(dates:DatesSetArg) {- void this.$state.go(- '.',- {- cdate: this.timezoneService.formattedISODate(dates.view.currentStart),- cview: dates.view.type,- },- {- custom: { notify: false },- },- );- }-- updateDates(resizeInfo:EventResizeDoneArg|EventDropArg|EventReceiveArg):ResourceChangeset<WorkPackageResource> {- const workPackage = resizeInfo.event.extendedProps.workPackage as WorkPackageResource;-- const changeset = this.halEditing.edit(workPackage);- changeset.setValue('startDate', resizeInfo.event.startStr);- const due = moment(resizeInfo.event.endStr)- .subtract(1, 'day')- .format('YYYY-MM-DD');- changeset.setValue('dueDate', due);-- return changeset;- }-- private async applyNonWorkingDay(data:{ date?:Date, el:HTMLElement }) {+ async applyNonWorkingDay(data:{ date?:Date, el:HTMLElement }) {await this.weekdaysPromise;if (data.date && this.weekdayService.isNonWorkingDay(data.date)) {diff --git a/frontend/src/app/features/calendar/op-work-packages-calendar.service.ts b/frontend/src/app/features/calendar/op-work-packages-calendar.service.tsnew file mode 100644index 00000000000..b0ea7e72c16--- /dev/null+++ b/frontend/src/app/features/calendar/op-work-packages-calendar.service.ts@@ -0,0 +1,417 @@+import {+ ElementRef,+ Injectable,+ Injector,+} from '@angular/core';+import {+ CalendarOptions,+ DatesSetArg,+ DayCellMountArg,+ DayHeaderMountArg,+ EventApi,+ EventDropArg,+ SlotLabelMountArg,+ SlotLaneMountArg,+} from '@fullcalendar/core';+import { I18nService } from 'core-app/core/i18n/i18n.service';+import { ConfigurationService } from 'core-app/core/config/configuration.service';+import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';+import { DomSanitizer } from '@angular/platform-browser';+import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';+import { splitViewRoute } from 'core-app/features/work-packages/routing/split-view-routes.helper';+import { StateService } from '@uirouter/angular';+import { WorkPackageCollectionResource } from 'core-app/features/hal/resources/wp-collection-resource';+import { ToastService } from 'core-app/shared/components/toaster/toast.service';+import {+ Observable,+ Subject,+} from 'rxjs';+import { WorkPackageViewFiltersService } from 'core-app/features/work-packages/routing/wp-view-base/view-services/wp-view-filters.service';+import { WorkPackagesListService } from 'core-app/features/work-packages/components/wp-list/wp-list.service';+import { IsolatedQuerySpace } from 'core-app/features/work-packages/directives/query-space/isolated-query-space';+import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';+import { take } from 'rxjs/operators';+import { HalResourceService } from 'core-app/features/hal/services/hal-resource.service';+import { QueryResource } from 'core-app/features/hal/resources/query-resource';+import {+ 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';+import { WorkPackagesListChecksumService } from 'core-app/features/work-packages/components/wp-list/wp-list-checksum.service';+import {+ EventReceiveArg,+ EventResizeDoneArg,+} from '@fullcalendar/interaction';+import { HalResourceEditingService } from 'core-app/shared/components/fields/edit/services/hal-resource-editing.service';+import { ResourceChangeset } from 'core-app/shared/components/fields/changeset/resource-changeset';+import * as moment from 'moment';+import { WorkPackageViewSelectionService } from 'core-app/features/work-packages/routing/wp-view-base/view-services/wp-view-selection.service';+import { isClickedWithModifier } from 'core-app/shared/helpers/link-handling/link-handling';+import { uiStateLinkClass } from 'core-app/features/work-packages/components/wp-fast-table/builders/ui-state-link-builder';+import { debugLog } from 'core-app/shared/helpers/debug_output';+import { WorkPackageViewContextMenu } from 'core-app/shared/components/op-context-menu/wp-context-menu/wp-view-context-menu.directive';+import { OPContextMenuService } from 'core-app/shared/components/op-context-menu/op-context-menu.service';+import { WeekdayService } from 'core-app/core/days/weekday.service';+import { OpCalendarService } from 'core-app/features/calendar/op-calendar.service';++export interface CalendarViewEvent {+ el:HTMLElement;+ event:EventApi;+}++// The CalenderOptions typings are missing daygrid hooks+interface CalendarOptionsWithDayGrid extends CalendarOptions {+ dayGridDidMount:(data:DayCellMountArg) => void;+}++@Injectable()+export class OpWorkPackagesCalendarService extends UntilDestroyedMixin {+ static MAX_DISPLAYED = 100;++ tooManyResultsText:string|null;++ currentWorkPackages$:Observable<WorkPackageCollectionResource> = this+ .querySpace+ .results+ .values$()+ .pipe(+ take(1),+ );++ constructor(+ private I18n:I18nService,+ private configuration:ConfigurationService,+ private sanitizer:DomSanitizer,+ private $state:StateService,+ readonly injector:Injector,+ readonly schemaCache:SchemaCacheService,+ readonly toastService:ToastService,+ readonly wpTableFilters:WorkPackageViewFiltersService,+ readonly wpListService:WorkPackagesListService,+ readonly wpListChecksumService:WorkPackagesListChecksumService,+ readonly urlParamsHelper:UrlParamsHelperService,+ readonly querySpace:IsolatedQuerySpace,+ readonly apiV3Service:ApiV3Service,+ readonly halResourceService:HalResourceService,+ readonly uiRouterGlobals:UIRouterGlobals,+ readonly timezoneService:TimezoneService,+ readonly halEditing:HalResourceEditingService,+ readonly wpTableSelection:WorkPackageViewSelectionService,+ readonly contextMenuService:OPContextMenuService,+ readonly calendarService:OpCalendarService,+ ) {+ super();+ }++ workPackagesListener$(callbackFn:() => void):void {+ this+ .querySpace+ .results+ .values$()+ .pipe(+ this.untilDestroyed(),+ )+ .subscribe(() => {+ callbackFn();+ });+ }++ calendarOptions(additionalOptions:CalendarOptions):CalendarOptions {+ return { ...this.defaultOptions(), ...additionalOptions };+ }++ eventDate(workPackage:WorkPackageResource, type:'start'|'due'):string {+ if (this.isMilestone(workPackage)) {+ return workPackage.date;+ }+ return workPackage[`${type}Date`];+ }++ isMilestone(workPackage:WorkPackageResource):boolean {+ return this.schemaCache.of(workPackage).isMilestone as boolean;+ }++ warnOnTooManyResults(collection:WorkPackageCollectionResource, isStatic = false):void {+ if (collection.count < collection.total) {+ this.tooManyResultsText = this.I18n.t('js.calendar.too_many',+ {+ count: collection.total,+ max: OpWorkPackagesCalendarService.MAX_DISPLAYED,+ });+ } else {+ this.tooManyResultsText = null;+ }++ if (this.tooManyResultsText && !isStatic) {+ this.toastService.addNotice(this.tooManyResultsText);+ }+ }++ async updateTimeframe(+ fetchInfo:{ start:Date, end:Date, timeZone:string },+ projectIdentifier:string|undefined,+ ):Promise<unknown> {+ if (this.areFiltersEmpty && this.querySpace.query.value) {+ // nothing to do+ return Promise.resolve();+ }++ const startDate = moment(fetchInfo.start).format('YYYY-MM-DD');+ const endDate = moment(fetchInfo.end).format('YYYY-MM-DD');++ let queryId:string|null = null;+ 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.+ // We want to always use the currently displayed time interval to be filtered for+ // so we need to adapt any eventually existing dateInterval filter to have that time interval. If no+ // 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.+ const initialQuery = await this+ .apiV3Service+ .queries+ .find({ pageSize: 0 }, queryId)+ .toPromise();++ queryProps = this.generateQueryProps(+ initialQuery,+ startDate,+ endDate,+ );+ } 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.+ if (this.urlParams.query_props) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const oldQueryProps:{ [key:string]:unknown } = JSON.parse(this.urlParams.query_props);++ // Update the date period of the calendar in the filter+ const newQueryProps = {+ ...oldQueryProps,+ f: [+ ...(oldQueryProps.f as QueryPropsFilter[]).filter((filter:QueryPropsFilter) => filter.n !== 'datesInterval'),+ OpWorkPackagesCalendarService.dateFilter(startDate, endDate),+ ],+ };++ queryProps = JSON.stringify(newQueryProps);+ } else {+ queryProps = OpWorkPackagesCalendarService.defaultQueryProps(startDate, endDate);+ }+ } else {+ queryProps = this.generateQueryProps(+ this.querySpace.query.value as QueryResource,+ startDate,+ endDate,+ );++ // There are no query props, ensure that they are not being shown the next load+ this.wpListChecksumService.set(queryId, queryProps);+ }++ return this+ .wpListService+ .fromQueryParams({ query_id: queryId, query_props: queryProps }, projectIdentifier || undefined)+ .toPromise();+ }++ public generateQueryProps(+ query:QueryResource,+ startDate:string,+ endDate:string,+ ):string {+ return this.urlParamsHelper.encodeQueryJsonParams(+ query,+ (props) => ({+ ...props,+ pp: OpWorkPackagesCalendarService.MAX_DISPLAYED,+ pa: 1,+ f: [+ ...props.f.filter((filter) => filter.n !== 'datesInterval'),+ OpWorkPackagesCalendarService.dateFilter(startDate, endDate),+ ],+ }),+ );+ }++ public get initialView():string|undefined {+ return this.urlParams.cview as string|undefined;+ }++ dateEditable(wp:WorkPackageResource):boolean {+ const schema = this.schemaCache.of(wp);+ const schemaEditable = schema.isAttributeEditable('startDate') && schema.isAttributeEditable('dueDate');+ return (wp.isLeaf || wp.scheduleManually) && schemaEditable;+ }++ eventDurationEditable(wp:WorkPackageResource):boolean {+ return this.dateEditable(wp) && !this.isMilestone(wp);+ }++ /**+ * The end date from fullcalendar is open, which means it targets+ * the next day instead of current day 23:59:59.+ * @param end+ */+ public getEndDateFromTimestamp(end:Date):string {+ return moment(end).subtract(1, 'd').format('YYYY-MM-DD');+ }++ public openSplitView(id:string, onlyWhenOpen = false):void {+ this.wpTableSelection.setSelection(id, -1);++ // Only open the split view if already open, otherwise only clicking the details opens+ if (onlyWhenOpen && !this.$state.includes('**.details.*')) {+ return;+ }++ void this.$state.go(+ `${splitViewRoute(this.$state)}.tabs`,+ { workPackageId: id, tabIdentifier: 'overview' },+ );+ }++ public onCardClicked({ workPackageId, event }:{ workPackageId:string, event:MouseEvent }):void {+ if (isClickedWithModifier(event)) {+ return;+ }++ this.openSplitView(workPackageId, true);+ }++ public showEventContextMenu({ workPackageId, event }:{ workPackageId:string, event:MouseEvent }):void {+ if (isClickedWithModifier(event)) {+ return;+ }++ // We want to keep the original context menu on hrefs+ // (currently, this is only the id)+ if ((event.target as HTMLElement).closest(`.${uiStateLinkClass}`)) {+ debugLog('Allowing original context menu on state link');+ return;+ }++ // Set the selection to single+ this.wpTableSelection.setSelection(workPackageId, -1);++ event.preventDefault();++ const handler = new WorkPackageViewContextMenu(this.injector, workPackageId, jQuery(event.target as HTMLElement));+ this.contextMenuService.show(handler, event);+ }++ private defaultOptions():CalendarOptionsWithDayGrid {+ return {+ editable: false,+ locale: this.I18n.locale,+ fixedWeekCount: false,+ firstDay: this.configuration.startOfWeek(),+ timeZone: this.configuration.isTimezoneSet() ? this.configuration.timezone() : 'local',+ height: 'auto',+ headerToolbar: {+ left: 'prev,next today',+ center: 'title',+ right: '',+ },+ initialDate: this.initialDate,+ initialView: this.initialView,+ datesSet: (dates) => this.updateDateParam(dates),+ dayHeaderDidMount: (data:DayHeaderMountArg) => this.calendarService.applyNonWorkingDay(data),+ dayCellDidMount: (data:DayCellMountArg) => this.calendarService.applyNonWorkingDay(data),+ dayGridDidMount: (data:DayCellMountArg) => this.calendarService.applyNonWorkingDay(data),+ slotLaneDidMount: (data:SlotLaneMountArg) => this.calendarService.applyNonWorkingDay(data),+ slotLabelDidMount: (data:SlotLabelMountArg) => this.calendarService.applyNonWorkingDay(data),+ };+ }++ private static defaultQueryProps(startDate:string, endDate:string) {+ const props = {+ c: ['id'],+ t:+ 'id:asc',+ f: [+ { n: 'status', o: '*', v: [] },+ this.dateFilter(startDate, endDate),+ ],+ dr: 'cards',+ hi: false,+ pp: OpWorkPackagesCalendarService.MAX_DISPLAYED,+ pa: 1,+ };++ return JSON.stringify(props);+ }++ private static dateFilter(startDate:string, endDate:string):QueryPropsFilter {+ return { n: 'datesInterval', o: '<>d', v: [startDate, endDate] };+ }++ private get initializingWithQueryProps():boolean {+ // Initialise with current query props+ // If the filters are empty, they still need to be initialised (with empty props)+ return (this.areFiltersEmpty || this.urlParams.query_props) as boolean;+ }++ private get initializingWithQuery():boolean {+ return this.areFiltersEmpty+ && !!this.urlParams.query_id+ && !this.urlParams.query_props;+ }++ private get urlParams() {+ return this.uiRouterGlobals.params;+ }++ private get areFiltersEmpty():boolean {+ return this.wpTableFilters.isEmpty;+ }++ private get initialDate():string|undefined {+ const date = this.urlParams.cdate as string|undefined;+ if (date) {+ return this.timezoneService.formattedISODate(date);+ }++ return undefined;+ }++ private updateDateParam(dates:DatesSetArg) {+ void this.$state.go(+ '.',+ {+ cdate: this.timezoneService.formattedISODate(dates.view.currentStart),+ cview: dates.view.type,+ },+ {+ custom: { notify: false },+ },+ );+ }++ updateDates(resizeInfo:EventResizeDoneArg|EventDropArg|EventReceiveArg):ResourceChangeset<WorkPackageResource> {+ const workPackage = resizeInfo.event.extendedProps.workPackage as WorkPackageResource;++ const changeset = this.halEditing.edit(workPackage);+ changeset.setValue('startDate', resizeInfo.event.startStr);+ const due = moment(resizeInfo.event.endStr)+ .subtract(1, 'day')+ .format('YYYY-MM-DD');+ changeset.setValue('dueDate', due);++ return changeset;+ }+}diff --git a/frontend/src/app/features/calendar/wp-calendar/wp-calendar.component.ts b/frontend/src/app/features/calendar/wp-calendar/wp-calendar.component.tsindex 371ab1b9f82..e24bde82f05 100644--- a/frontend/src/app/features/calendar/wp-calendar/wp-calendar.component.ts+++ b/frontend/src/app/features/calendar/wp-calendar/wp-calendar.component.ts@@ -33,22 +33,24 @@ import { debounceTime } from 'rxjs/operators';import { ConfigurationService } from 'core-app/core/config/configuration.service';import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';-import {- CalendarViewEvent,- OpCalendarService,-} from 'core-app/features/calendar/op-calendar.service';import { Subject } from 'rxjs';import { CurrentProjectService } from 'core-app/core/current-project/current-project.service';import interactionPlugin, { EventResizeDoneArg } from '@fullcalendar/interaction';import { HalResourceEditingService } from 'core-app/shared/components/fields/edit/services/hal-resource-editing.service';import { HalResourceNotificationService } from 'core-app/features/hal/services/hal-resource-notification.service';import { splitViewRoute } from 'core-app/features/work-packages/routing/split-view-routes.helper';+import {+ CalendarViewEvent,+ OpWorkPackagesCalendarService,+} from 'core-app/features/calendar/op-work-packages-calendar.service';+import { OpCalendarService } from 'core-app/features/calendar/op-calendar.service';@Component({templateUrl: './wp-calendar.template.html',styleUrls: ['./wp-calendar.sass'],selector: 'op-wp-calendar',providers: [+ OpWorkPackagesCalendarService,OpCalendarService,],})@@ -80,6 +82,7 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implementprivate sanitizer:DomSanitizer,private configuration:ConfigurationService,readonly calendar:OpCalendarService,+ readonly workPackagesCalendar:OpWorkPackagesCalendarService,readonly currentProject:CurrentProjectService,readonly halEditing:HalResourceEditingService,readonly halNotification:HalResourceNotificationService,@@ -115,7 +118,7 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implementsuccessCallback(events);} else {this- .calendar+ .workPackagesCalendar.currentWorkPackages$.subscribe((collection:WorkPackageCollectionResource) => {const events = this.updateResults((collection));@@ -123,7 +126,7 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implement});}- void this.calendar.updateTimeframe(fetchInfo, this.currentProject.identifier || undefined);+ void this.workPackagesCalendar.updateTimeframe(fetchInfo, this.currentProject.identifier || undefined);}// eslint-disable-next-line @angular-eslint/use-lifecycle-interface@@ -159,7 +162,7 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implement// Currently the calendar widget is shown on multiple pages,// but only the calendar module itself is a partitioned query space which can deal with a split screen requestif (this.$state.includes('calendar')) {- this.calendar.openSplitView(workPackageId);+ this.workPackagesCalendar.openSplitView(workPackageId);} else {void this.$state.go('work-packages.show',@@ -176,7 +179,7 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implementvoid this.configuration.initialized.then(() => {this.calendarOptions$.next(- this.calendar.calendarOptions(additionalOptions),+ this.workPackagesCalendar.calendarOptions(additionalOptions),);});}@@ -199,32 +202,32 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implement}const workPackageId = eventContainer.dataset.workPackageId as string;- this.calendar.showEventContextMenu({ workPackageId, event });+ this.workPackagesCalendar.showEventContextMenu({ workPackageId, event });}private setupWorkPackagesListener():void {- this.calendar.workPackagesListener$(() => {+ this.workPackagesCalendar.workPackagesListener$(() => {this.alreadyLoaded = true;this.ucCalendar.getApi().refetchEvents();});}private updateResults(collection:WorkPackageCollectionResource) {- this.calendar.warnOnTooManyResults(collection, this.static);+ this.workPackagesCalendar.warnOnTooManyResults(collection, this.static);return this.mapToCalendarEvents(collection.elements);}private mapToCalendarEvents(workPackages:WorkPackageResource[]) {const events = workPackages.map((workPackage:WorkPackageResource) => {- const startDate = this.calendar.eventDate(workPackage, 'start');- const endDate = this.calendar.eventDate(workPackage, 'due');+ const startDate = this.workPackagesCalendar.eventDate(workPackage, 'start');+ const endDate = this.workPackagesCalendar.eventDate(workPackage, 'due');const exclusiveEnd = moment(endDate).add(1, 'days').format('YYYY-MM-DD');return {title: workPackage.subject,start: startDate,- editable: this.calendar.eventDurationEditable(workPackage),+ editable: this.workPackagesCalendar.eventDurationEditable(workPackage),end: exclusiveEnd,allDay: true,className: `__hl_background_type_${workPackage.type.id}`,@@ -240,7 +243,7 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implement}private async updateEvent(info:EventResizeDoneArg|EventDropArg):Promise<void> {- const changeset = this.calendar.updateDates(info);+ const changeset = this.workPackagesCalendar.updateDates(info);try {const result = await this.halEditing.save(changeset);@@ -254,7 +257,7 @@ export class WorkPackagesCalendarComponent extends UntilDestroyedMixin implementprivate handleDateClicked(info:DateSelectArg) {const defaults = {startDate: info.startStr,- dueDate: this.calendar.getEndDateFromTimestamp(info.end),+ dueDate: this.workPackagesCalendar.getEndDateFromTimestamp(info.end),};void this.$state.go(diff --git a/frontend/src/app/features/calendar/wp-calendar/wp-calendar.template.html b/frontend/src/app/features/calendar/wp-calendar/wp-calendar.template.htmlindex de1964ac7c7..9f80613e1a9 100644--- a/frontend/src/app/features/calendar/wp-calendar/wp-calendar.template.html+++ b/frontend/src/app/features/calendar/wp-calendar/wp-calendar.template.html@@ -13,6 +13,6 @@</ng-container><div*ngIf="static"- [textContent]="calendar.tooManyResultsText"+ [textContent]="workPackagesCalendar.tooManyResultsText"class="op-wp-calendar--notification"></div></div>diff --git a/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.html b/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.htmlindex defabe11de8..12b278966ff 100644--- a/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.html+++ b/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.html@@ -30,7 +30,7 @@class="op-add-existing-pane--wp"[attr.data-qa-selector]="'op-add-existing-pane--wp-' + wp.id"(stateLinkClicked)="openStateLink($event)"- (cardClicked)="calendar.onCardClicked($event)"+ (cardClicked)="workPackagesCalendar.onCardClicked($event)"></wp-single-card></ng-container></div>diff --git a/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.ts b/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.tsindex 69c591a0a2a..e9a02ed76f1 100644--- a/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.ts+++ b/frontend/src/app/features/team-planner/team-planner/add-work-packages/add-existing-pane.component.ts@@ -38,6 +38,7 @@ import { ActionsService } from 'core-app/core/state/actions/actions.service';import { teamPlannerEventRemoved } from 'core-app/features/team-planner/team-planner/planner/team-planner.actions';import { WorkPackageViewFiltersService } from 'core-app/features/work-packages/routing/wp-view-base/view-services/wp-view-filters.service';import { OpCalendarService } from 'core-app/features/calendar/op-calendar.service';+import { OpWorkPackagesCalendarService } from 'core-app/features/calendar/op-work-packages-calendar.service';@Component({selector: 'op-add-existing-pane',@@ -117,7 +118,7 @@ export class AddExistingPaneComponent extends UntilDestroyedMixin implements OnIprivate readonly notificationService:WorkPackageNotificationService,private readonly currentProject:CurrentProjectService,private readonly urlParamsHelper:UrlParamsHelperService,- private readonly calendar:OpCalendarService,+ private readonly workPackagesCalendar:OpWorkPackagesCalendarService,private readonly calendarDrag:CalendarDragDropService,private readonly $state:StateService,private readonly actions$:ActionsService,diff --git a/frontend/src/app/features/team-planner/team-planner/calendar-drag-drop.service.ts b/frontend/src/app/features/team-planner/team-planner/calendar-drag-drop.service.tsindex 34922aad981..3af7af173c3 100644--- a/frontend/src/app/features/team-planner/team-planner/calendar-drag-drop.service.ts+++ b/frontend/src/app/features/team-planner/team-planner/calendar-drag-drop.service.ts@@ -11,6 +11,7 @@ import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';import { AuthorisationService } from 'core-app/core/model-auth/model-auth.service';import { I18nService } from 'core-app/core/i18n/i18n.service';import { OpCalendarService } from 'core-app/features/calendar/op-calendar.service';+import { OpWorkPackagesCalendarService } from 'core-app/features/calendar/op-work-packages-calendar.service';@Injectable()export class CalendarDragDropService {@@ -30,7 +31,7 @@ export class CalendarDragDropService {constructor(readonly authorisation:AuthorisationService,readonly schemaCache:SchemaCacheService,- readonly calendarService:OpCalendarService,+ readonly workPackagesCalendarService:OpWorkPackagesCalendarService,readonly I18n:I18nService,) {}@@ -98,7 +99,7 @@ export class CalendarDragDropService {return { disabled: true, reason: this.text.draggingDisabled.permissionDenied };}- if (!this.calendarService.dateEditable(workPackage)) {+ if (!this.workPackagesCalendarService.dateEditable(workPackage)) {return { disabled: true, reason: this.text.draggingDisabled.fallback };}diff --git a/frontend/src/app/features/team-planner/team-planner/page/team-planner-page.component.ts b/frontend/src/app/features/team-planner/team-planner/page/team-planner-page.component.tsindex 9757b3c18a6..e3c5f719069 100644--- a/frontend/src/app/features/team-planner/team-planner/page/team-planner-page.component.ts+++ b/frontend/src/app/features/team-planner/team-planner/page/team-planner-page.component.ts@@ -24,6 +24,7 @@ import {import { teamPlannerEventAdded } from 'core-app/features/team-planner/team-planner/planner/team-planner.actions';import { InjectField } from 'core-app/shared/helpers/angular/inject-field.decorator';import { ActionsService } from 'core-app/core/state/actions/actions.service';+import { OpWorkPackagesCalendarService } from 'core-app/features/calendar/op-work-packages-calendar.service';import { OpCalendarService } from 'core-app/features/calendar/op-calendar.service';@EffectHandler@@ -35,6 +36,7 @@ import { OpCalendarService } from 'core-app/features/calendar/op-calendar.servicchangeDetection: ChangeDetectionStrategy.OnPush,providers: [QueryParamListenerService,+ OpWorkPackagesCalendarService,OpCalendarService,CalendarDragDropService,],diff --git a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.html b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.htmlindex f3a2bb9b4f5..c5b2657d692 100644--- a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.html+++ b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.html@@ -43,7 +43,7 @@></full-calendar><div- [textContent]="calendar.tooManyResultsText"+ [textContent]="workPackagesCalendar.tooManyResultsText"class="op-wp-calendar--notification"></div>@@ -116,8 +116,8 @@[showStartDate]="!isWpStartDateInCurrentView(wp)"[showEndDate]="!isWpEndDateInCurrentView(wp)"(stateLinkClicked)="openStateLink($event)"- (cardClicked)="calendar.onCardClicked($event)"- (cardContextMenu)="calendar.showEventContextMenu($event)"+ (cardClicked)="workPackagesCalendar.onCardClicked($event)"+ (cardContextMenu)="workPackagesCalendar.showEventContextMenu($event)"></wp-single-card></ng-template>diff --git a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.ts b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.tsindex 674de47b37a..35e3c0ee122 100644--- a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.ts+++ b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.ts@@ -85,6 +85,7 @@ import { CapabilitiesResourceService } from 'core-app/core/state/capabilities/caimport { ICapability } from 'core-app/core/state/capabilities/capability.model';import { ToastService } from 'core-app/shared/components/toaster/toast.service';import { LoadingIndicatorService } from 'core-app/core/loading-indicator/loading-indicator.service';+import { OpWorkPackagesCalendarService } from 'core-app/features/calendar/op-work-packages-calendar.service';@Component({selector: 'op-team-planner',@@ -142,7 +143,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,filter((dragging) => !!dragging),map((dragging) => {const workPackage = (dragging as EventDragStartArg).event.extendedProps.workPackage as WorkPackageResource;- const dateEditable = this.calendar.dateEditable(workPackage);+ const dateEditable = this.workPackagesCalendar.dateEditable(workPackage);const resourceEditable = this.eventResourceEditable(workPackage);return dateEditable && resourceEditable;}),@@ -284,6 +285,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,private I18n:I18nService,readonly injector:Injector,readonly calendar:OpCalendarService,+ readonly workPackagesCalendar:OpWorkPackagesCalendarService,readonly halEditing:HalResourceEditingService,readonly halNotification:HalResourceNotificationService,readonly schemaCache:SchemaCacheService,@@ -381,13 +383,13 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,void this.configuration.initialized.then(() => {this.calendarOptions$.next(- this.calendar.calendarOptions({+ this.workPackagesCalendar.calendarOptions({schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',selectable: true,plugins: [resourceTimelinePlugin, interactionPlugin],titleFormat: { year: 'numeric', month: 'long', day: 'numeric' },buttonText: { today: this.text.today },- initialView: this.calendar.initialView || 'resourceTimelineWeek',+ initialView: this.workPackagesCalendar.initialView || 'resourceTimelineWeek',headerToolbar: {left: '',center: 'title',@@ -511,7 +513,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,failureCallback:(error:unknown) => void,):void|PromiseLike<EventInput[]> {this- .calendar+ .workPackagesCalendar.currentWorkPackages$.pipe(withLatestFrom(this.assigneeCaps$),@@ -531,7 +533,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,failureCallback,);- void this.calendar.updateTimeframe(fetchInfo, this.projectIdentifier);+ void this.workPackagesCalendar.updateTimeframe(fetchInfo, this.projectIdentifier);}/**@@ -685,7 +687,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,}const assignee = this.wpAssignee(workPackage);- const durationEditable = this.calendar.eventDurationEditable(workPackage);+ const durationEditable = this.workPackagesCalendar.eventDurationEditable(workPackage);const resourceEditable = this.eventResourceEditable(workPackage);return {@@ -711,7 +713,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,this.openNewSplitCreate(info.startStr,// end date is exclusive- this.calendar.getEndDateFromTimestamp(info.end),+ this.workPackagesCalendar.getEndDateFromTimestamp(info.end),info.resource?.id || '',);}@@ -762,7 +764,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,}private async updateEvent(info:EventResizeDoneArg|EventDropArg|EventReceiveArg):Promise<void> {- const changeset = this.calendar.updateDates(info);+ const changeset = this.workPackagesCalendar.updateDates(info);const resource = info.event.getResources()[0];if (resource) {@@ -803,7 +805,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,):{ [key:string]:string|string[] } {const constraints:{ [key:string]:string|string[] } = {};- if (!this.calendar.eventDurationEditable(wp) && !wp.date) {+ if (!this.workPackagesCalendar.eventDurationEditable(wp) && !wp.date) {constraints.start = this.wpStartDate(wp);constraints.end = this.wpEndDate(wp);}@@ -822,11 +824,11 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,}private wpStartDate(wp:WorkPackageResource):string {- return this.calendar.eventDate(wp, 'start');+ return this.workPackagesCalendar.eventDate(wp, 'start');}private wpEndDate(wp:WorkPackageResource):string {- const endDate = this.calendar.eventDate(wp, 'due');+ const endDate = this.workPackagesCalendar.eventDate(wp, 'due');return moment(endDate).add(1, 'days').format('YYYY-MM-DD');}