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

Avoid using the create service for the time entry

Oliver Günther42a7f4532d20
diff --git a/frontend/src/app/features/work-packages/components/wp-timer-button/wp-timer-button.component.ts b/frontend/src/app/features/work-packages/components/wp-timer-button/wp-timer-button.component.ts
index 2032d057fad..93209049eda 100644
--- a/frontend/src/app/features/work-packages/components/wp-timer-button/wp-timer-button.component.ts
+++ b/frontend/src/app/features/work-packages/components/wp-timer-button/wp-timer-button.component.ts
@@ -27,39 +27,20 @@
//++
import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';
-import {
- AfterViewInit,
- ChangeDetectionStrategy,
- ChangeDetectorRef,
- Component,
- Injector,
- Input,
- OnDestroy,
-} from '@angular/core';
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Injector, Input } from '@angular/core';
import { I18nService } from 'core-app/core/i18n/i18n.service';
import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';
import { ApiV3Service } from 'core-app/core/apiv3/api-v3.service';
-import { TimeEntryCreateService } from 'core-app/shared/components/time_entries/create/create.service';
-import {
- filter,
- map,
- switchMap,
-} from 'rxjs/operators';
-import {
- firstValueFrom,
- from,
- Observable,
- timer,
-} from 'rxjs';
+import { filter, map, switchMap } from 'rxjs/operators';
+import { Observable, timer } from 'rxjs';
import { TimeEntryResource } from 'core-app/features/hal/resources/time-entry-resource';
-import { HalResourceEditingService } from 'core-app/shared/components/fields/edit/services/hal-resource-editing.service';
-import moment from 'moment';
+import {
+ HalResourceEditingService,
+} from 'core-app/shared/components/fields/edit/services/hal-resource-editing.service';
import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';
import { TimezoneService } from 'core-app/core/datetime/timezone.service';
import { TimeEntryTimerService } from 'core-app/shared/components/time_entries/services/time-entry-timer.service';
import { formatElapsedTime } from 'core-app/features/work-packages/components/wp-timer-button/time-formatter.helper';
-import { OpModalService } from 'core-app/shared/components/modal/modal.service';
-import { StopExistingTimerModalComponent } from 'core-app/shared/components/time_entries/timer/stop-existing-timer-modal.component';
import { ToastService } from 'core-app/shared/components/toaster/toast.service';
import { InjectField } from 'core-app/shared/helpers/angular/inject-field.decorator';
import { PathHelperService } from 'core-app/core/path-helper/path-helper.service';
@@ -72,7 +53,7 @@ import { TurboRequestsService } from 'core-app/core/turbo/turbo-requests.service
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
-export class WorkPackageTimerButtonComponent extends UntilDestroyedMixin implements AfterViewInit, OnDestroy {
+export class WorkPackageTimerButtonComponent extends UntilDestroyedMixin {
@Input() public workPackage:WorkPackageResource;
@InjectField() PathHelper:PathHelperService;
@InjectField() TurboRequests:TurboRequestsService;
@@ -93,17 +74,13 @@ export class WorkPackageTimerButtonComponent extends UntilDestroyedMixin impleme
timer_already_stopped: this.I18n.t('js.timer.timer_already_stopped'),
};
- private closeDialogHandler:EventListener = this.handleTimeEntryDialogClose.bind(this);
- private shouldStartNewTimer = false;
constructor(
readonly injector:Injector,
readonly I18n:I18nService,
readonly apiV3Service:ApiV3Service,
readonly timeEntryService:TimeEntryTimerService,
- readonly timeEntryCreateService:TimeEntryCreateService,
readonly halEditing:HalResourceEditingService,
- readonly modalService:OpModalService,
readonly schemaCache:SchemaCacheService,
readonly timezoneService:TimezoneService,
readonly toastService:ToastService,
@@ -112,13 +89,6 @@ export class WorkPackageTimerButtonComponent extends UntilDestroyedMixin impleme
super();
}
- ngAfterViewInit():void {
- document.addEventListener('dialog:close', this.closeDialogHandler);
- }
-
- ngOnDestroy():void {
- document.removeEventListener('dialog:close', this.closeDialogHandler);
- }
activeForWorkPackage(entry:TimeEntryResource | null):boolean {
return !!entry && entry.entity.href === this.workPackage.href;
@@ -128,74 +98,11 @@ export class WorkPackageTimerButtonComponent extends UntilDestroyedMixin impleme
this.timeEntryService.timer$.next(null);
}
- async stop() {
- const active = await firstValueFrom(this.timeEntryService.refresh());
-
- if (!active) {
- return this.toastService.addWarning(this.text.timer_already_stopped);
- }
-
- return this.TurboRequests.request(
- `${this.PathHelper.timeEntryEditDialog(active.id as string)}`,
- { method: 'GET' },
- );
- }
-
start():void {
- this
- .timeEntryService
- .refresh()
- .subscribe((active) => {
- if (active) {
- this.showStopModal(active)
- .then(() => {
- this.shouldStartNewTimer = true;
- void this.stop();
- })
- .catch(() => undefined);
- } else {
- this.startTimer();
- }
- });
- }
-
- private startTimer():void {
- this.timeEntryCreateService
- .createNewTimeEntry(moment(), this.workPackage, true)
- .pipe(
- switchMap((changeset) => from(this.halEditing.save(changeset))),
- map((result) => result.resource as TimeEntryResource),
- )
- .subscribe((active) => {
- this.timeEntryService.timer$.next(active);
- });
- }
-
- private showStopModal(active:TimeEntryResource):Promise<void> {
- return new Promise<void>((resolve, reject) => {
- this
- .modalService
- .show(StopExistingTimerModalComponent, this.injector, { timer: active })
- .subscribe((modal) => modal.closingEvent.subscribe(() => {
- if (modal.confirmed) {
- resolve();
- } else {
- reject();
- }
- }));
- });
+ this.timeEntryService.start(this.workPackage);
}
- private handleTimeEntryDialogClose(event:CustomEvent):void {
- const { detail: { dialog, submitted } } = event as { detail:{ dialog:HTMLDialogElement, submitted:boolean } };
- const isOngoing = dialog.dataset.ongoing === 'true';
-
- if (dialog.id === 'time-entry-dialog' && submitted && isOngoing) {
- this.timeEntryService.timer$.next(null);
- if (this.shouldStartNewTimer) {
- this.shouldStartNewTimer = false;
- this.startTimer();
- }
- }
+ stop():void {
+ this.timeEntryService.stop();
}
}
diff --git a/frontend/src/app/shared/components/op-context-menu/wp-context-menu/wp-single-context-menu.ts b/frontend/src/app/shared/components/op-context-menu/wp-context-menu/wp-single-context-menu.ts
index 1d86478ec52..b6ab7dd3373 100644
--- a/frontend/src/app/shared/components/op-context-menu/wp-context-menu/wp-single-context-menu.ts
+++ b/frontend/src/app/shared/components/op-context-menu/wp-context-menu/wp-single-context-menu.ts
@@ -1,4 +1,4 @@
-import { AfterViewInit, Directive, ElementRef, Injector, Input, OnDestroy } from '@angular/core';
+import { AfterViewInit, Directive, ElementRef, inject, Injector, Input, OnDestroy } from '@angular/core';
import { StateService } from '@uirouter/core';
import { isClickedWithModifier } from 'core-app/shared/helpers/link-handling/link-handling';
import { AuthorisationService } from 'core-app/core/model-auth/model-auth.service';
@@ -28,6 +28,7 @@ export class WorkPackageSingleContextMenuDirective extends OpContextMenuTrigger
private currentTimer:TimeEntryResource|null = null;
+
constructor(
readonly HookService:HookService,
readonly $state:StateService,
@@ -80,10 +81,10 @@ export class WorkPackageSingleContextMenuDirective extends OpContextMenuTrigger
window.location.href = `${this.PathHelper.staticBase}/work_packages/move/new?copy=true&ids[]=${this.workPackage.id as string}`;
break;
case 'start_timer':
- // do stuff
+ this.timeEntryService.start(this.workPackage);
break;
case 'stop_timer':
- // do stuff
+ this.timeEntryService.stop();
break;
case 'copy':
this.$state.go('work-packages.copy', { copiedFromWorkPackageId: this.workPackage.id });
@@ -141,31 +142,11 @@ export class WorkPackageSingleContextMenuDirective extends OpContextMenuTrigger
}
}
- private removeTimerActions(actions:WorkPackageAction[]):WorkPackageAction[] {
- return actions.filter((action) => action.key !== 'start_timer' && action.key !== 'stop_timer');
- }
-
private getPermittedActions(authorization:WorkPackageAuthorization) {
let actions:WorkPackageAction[] = authorization.permittedActionsWithLinks(PERMITTED_CONTEXT_MENU_ACTIONS);
- if (this.hasTimerPermission()) {
- const requiredTimerAction = this.getTimerAction();
- actions = actions.filter((action) => {
- // Show one action
- if (action.key === requiredTimerAction) {
- return true;
- }
-
- // Hide the other
- if (action.key === 'start_timer' || action.key === 'stop_timer') {
- return false;
- }
-
- return true;
- });
- } else {
- actions = this.removeTimerActions(actions);
- }
+ // Reduce the available actions on timers
+ actions = this.reduceTimerAction(actions);
// Splice plugin actions onto the core actions
_.each(this.getPermittedPluginActions(authorization), (action:WorkPackageAction) => {
@@ -176,6 +157,23 @@ export class WorkPackageSingleContextMenuDirective extends OpContextMenuTrigger
return actions;
}
+ private reduceTimerAction(actions:WorkPackageAction[]) {
+ const requiredTimerAction = this.getTimerAction();
+ return actions.filter((action) => {
+ // Show one action
+ if (action.key === requiredTimerAction) {
+ return true;
+ }
+
+ // Hide the other
+ if (action.key === 'start_timer' || action.key === 'stop_timer') {
+ return false;
+ }
+
+ return true;
+ });
+ }
+
private getPermittedPluginActions(authorization:WorkPackageAuthorization) {
const actions:WorkPackageAction[] = this.HookService.call('workPackageSingleContextMenu');
return authorization.permittedActionsWithLinks(actions);
diff --git a/frontend/src/app/shared/components/time_entries/openproject-time-entries.module.ts b/frontend/src/app/shared/components/time_entries/openproject-time-entries.module.ts
index 199b4d1d610..cd391370222 100644
--- a/frontend/src/app/shared/components/time_entries/openproject-time-entries.module.ts
+++ b/frontend/src/app/shared/components/time_entries/openproject-time-entries.module.ts
@@ -33,12 +33,15 @@ import { OpenprojectFieldsModule } from 'core-app/shared/components/fields/openp
import { TimeEntryCreateModalComponent } from 'core-app/shared/components/time_entries/create/create.modal';
import { TimeEntryEditModalComponent } from 'core-app/shared/components/time_entries/edit/edit.modal';
import { TimeEntryFormComponent } from 'core-app/shared/components/time_entries/form/form.component';
-import { TimeEntryEditService } from 'core-app/shared/components/time_entries/edit/edit.service';
import { TriggerActionsEntryComponent } from 'core-app/shared/components/time_entries/edit/trigger-actions-entry.component';
import { TimeEntryTimerService } from 'core-app/shared/components/time_entries/services/time-entry-timer.service';
import { CommonModule } from '@angular/common';
import { TimerAccountMenuComponent } from 'core-app/shared/components/time_entries/timer/timer-account-menu.component';
import { StopExistingTimerModalComponent } from 'core-app/shared/components/time_entries/timer/stop-existing-timer-modal.component';
+import { TimeEntryCreateService } from 'core-app/shared/components/time_entries/create/create.service';
+import {
+ HalResourceEditingService
+} from 'core-app/shared/components/fields/edit/services/hal-resource-editing.service';
@NgModule({
imports: [
@@ -59,6 +62,7 @@ import { StopExistingTimerModalComponent } from 'core-app/shared/components/time
StopExistingTimerModalComponent,
],
providers: [
+ TimeEntryCreateService,
TimeEntryTimerService,
],
})
diff --git a/frontend/src/app/shared/components/time_entries/services/time-entry-timer.service.ts b/frontend/src/app/shared/components/time_entries/services/time-entry-timer.service.ts
index a9b3db91820..f3b92b64b15 100644
--- a/frontend/src/app/shared/components/time_entries/services/time-entry-timer.service.ts
+++ b/frontend/src/app/shared/components/time_entries/services/time-entry-timer.service.ts
@@ -1,9 +1,20 @@
-import { inject, Injectable } from '@angular/core';
+import { inject, Injectable, Injector } from '@angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { ApiV3Service } from 'core-app/core/apiv3/api-v3.service';
import { TimeEntryResource } from 'core-app/features/hal/resources/time-entry-resource';
import { ApiV3FilterBuilder } from 'core-app/shared/helpers/api-v3/api-v3-filter-builder';
-import { BehaviorSubject, Observable } from 'rxjs';
+import { BehaviorSubject, firstValueFrom, Observable } from 'rxjs';
+import { TurboRequestsService } from 'core-app/core/turbo/turbo-requests.service';
+import { ToastService } from 'core-app/shared/components/toaster/toast.service';
+import { PathHelperService } from 'core-app/core/path-helper/path-helper.service';
+import { I18nService } from 'core-app/core/i18n/i18n.service';
+import moment from 'moment/moment';
+import {
+ StopExistingTimerModalComponent,
+} from 'core-app/shared/components/time_entries/timer/stop-existing-timer-modal.component';
+import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';
+import { OpModalService } from 'core-app/shared/components/modal/modal.service';
+import { HalResourceService } from 'core-app/features/hal/services/hal-resource.service';
@Injectable()
export class TimeEntryTimerService {
@@ -17,8 +28,21 @@ export class TimeEntryTimerService {
);
private apiV3Service = inject(ApiV3Service);
+ private toastService = inject(ToastService);
+ private turboRequestsService = inject(TurboRequestsService);
+ private pathHelperService = inject(PathHelperService);
+ private I18n = inject(I18nService);
+ private halResourceService = inject(HalResourceService);
+ private modalService = inject(OpModalService);
+ private injector = inject(Injector);
+
+ private closeDialogHandler:EventListener = this.handleTimeEntryDialogClose.bind(this);
+ private shouldStartTimerFor:WorkPackageResource|null = null;
public initialize() {
+ // Listen to dialog close events to possibly start a new timer
+ document.addEventListener('dialog:close', this.closeDialogHandler);
+
// Refresh the timer after some interval to not block other resources
setTimeout(() => this.refresh().subscribe(), 100);
@@ -48,6 +72,38 @@ export class TimeEntryTimerService {
);
}
+ async stop():Promise<unknown> {
+ const active = await firstValueFrom(this.refresh());
+
+ if (!active) {
+ return this.toastService.addWarning(this.I18n.t('js.timer.timer_already_stopped'));
+ }
+
+ return this.turboRequestsService.request(
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ this.pathHelperService.timeEntryEditDialog(active.id!),
+ { method: 'GET' },
+ );
+ }
+
+ start(workPackage:WorkPackageResource):void {
+ this
+ .refresh()
+ .subscribe((active) => {
+ if (active) {
+ this.showStopModal(active)
+ .then(() => {
+ this.shouldStartTimerFor = workPackage;
+ void this.stop();
+ })
+ .catch(() => undefined);
+ } else {
+ this.startTimer(workPackage);
+ }
+ });
+ }
+
+
private renderTimer() {
const timerElement = document.createElement('span');
const icon = document.createElement('span');
@@ -60,7 +116,65 @@ export class TimeEntryTimerService {
}
private removeTimer() {
- const timerElement = document.querySelector('.op-principal--timer') as HTMLElement;
+ const timerElement = document.querySelector<HTMLElement>('.op-principal--timer');
timerElement?.remove();
}
+
+ private startTimer(workPackage:WorkPackageResource):void {
+ this
+ .createTimer(workPackage)
+ .subscribe((active) => {
+ this.timer$.next(active);
+ });
+ }
+
+ private createTimer(workPackage:WorkPackageResource):Observable<TimeEntryResource> {
+ return this
+ .apiV3Service
+ .time_entries
+ .post(this.timerPayload(workPackage));
+ }
+
+ private timerPayload(workPackage:WorkPackageResource) {
+ return {
+ spentOn: moment().format('YYYY-MM-DD'),
+ hours: null,
+ ongoing: true,
+ _links: {
+ workPackage: {
+ href: workPackage.href,
+ },
+ },
+ };
+ }
+
+ private showStopModal(active:TimeEntryResource):Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ this
+ .modalService
+ .show(StopExistingTimerModalComponent, this.injector, { timer: active })
+ .subscribe((modal) => modal.closingEvent.subscribe(() => {
+ if (modal.confirmed) {
+ resolve();
+ } else {
+ reject(new Error());
+ }
+ }));
+ });
+ }
+
+
+ private handleTimeEntryDialogClose(event:CustomEvent):void {
+ const { detail: { dialog, submitted } } = event as { detail:{ dialog:HTMLDialogElement, submitted:boolean } };
+ const isOngoing = dialog.dataset.ongoing === 'true';
+
+ if (dialog.id === 'time-entry-dialog' && submitted && isOngoing) {
+ this.timer$.next(null);
+ if (this.shouldStartTimerFor) {
+ const workPackage = this.shouldStartTimerFor;
+ this.shouldStartTimerFor = null;
+ this.startTimer(workPackage);
+ }
+ }
+ }
}