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

Refactor user-autocompleter

Benjamin Bädorf00d1747712ad
diff --git a/app/views/groups/_users.html.erb b/app/views/groups/_users.html.erb
index 3f2a575bdae..04185ce9008 100644
--- a/app/views/groups/_users.html.erb
+++ b/app/views/groups/_users.html.erb
@@ -54,10 +54,10 @@ See COPYRIGHT and LICENSE files for more details.
<legend class="form--fieldset-legend"><%=t(:label_user_new)%></legend>
<div class="form--field -vertical">
<%= hidden_field_tag :user_ids, nil %>
- <user-autocompleter data-update-input-selector='"user_ids"'
+ <op-user-autocompleter data-name='"user_ids"'
data-additional-filter="<%= autocompleter_filters(@group).to_json %>"
class="new-group-members--autocomplete">
- </user-autocompleter>
+ </op-user-autocompleter>
</div>
<div>
<%= styled_button_tag t(:button_add),
diff --git a/app/views/members/_member_form.html.erb b/app/views/members/_member_form.html.erb
index bbcb556fdfc..50eb596ede2 100644
--- a/app/views/members/_member_form.html.erb
+++ b/app/views/members/_member_form.html.erb
@@ -45,9 +45,9 @@ See COPYRIGHT and LICENSE files for more details.
<%= styled_label_tag :member_user_ids, user_id_title %>
<%= hidden_field_tag "member[user_ids][]", nil %>
- <%= angular_component_tag 'members-autocompleter',
+ <%= angular_component_tag 'op-members-autocompleter',
inputs: {
- updateInputSelector: "member[user_ids][]",
+ name: "member[user_ids][]",
url: autocomplete_for_member_project_members_path + '.json',
appendTo: "body",
multiple: true
diff --git a/app/views/oauth/applications/_form.html.erb b/app/views/oauth/applications/_form.html.erb
index d8832aed4ba..e56e8d1bedc 100644
--- a/app/views/oauth/applications/_form.html.erb
+++ b/app/views/oauth/applications/_form.html.erb
@@ -84,8 +84,8 @@ See COPYRIGHT and LICENSE files for more details.
<div class="form--field-container">
<div class="form--text-field-container -middle">
<%= f.hidden_field :client_credentials_user_id, value: @application.client_credentials_user_id %>
- <user-autocompleter data-allow-empty="true"
- data-update-input-selector="'application[client_credentials_user_id]'"></user-autocompleter>
+ <op-user-autocompleter data-allow-empty="true"
+ data-name="'application[client_credentials_user_id]'"></op-user-autocompleter>
</div>
</div>
<p class="form--field-instructions">
diff --git a/db/migrate/20220707192304_backfill_time_entries_with_logged_by_id.rb b/db/migrate/20220707192304_backfill_time_entries_with_logged_by_id.rb
new file mode 100644
index 00000000000..60acb376cf9
--- /dev/null
+++ b/db/migrate/20220707192304_backfill_time_entries_with_logged_by_id.rb
@@ -0,0 +1,5 @@
+class BackfillTimeEntriesWithLoggedById < ActiveRecord::Migration[7.0]
+ def change
+ TimeEntry.all.update_all('logged_by_id = user_id')
+ end
+end
diff --git a/frontend/src/app/features/work-packages/components/wp-single-view-tabs/watchers-tab/watchers-tab.html b/frontend/src/app/features/work-packages/components/wp-single-view-tabs/watchers-tab/watchers-tab.html
index 6a7cd6ae44e..a19a6458fc9 100644
--- a/frontend/src/app/features/work-packages/components/wp-single-view-tabs/watchers-tab/watchers-tab.html
+++ b/frontend/src/app/features/work-packages/components/wp-single-view-tabs/watchers-tab/watchers-tab.html
@@ -17,11 +17,11 @@
<div class="work-package--watchers-lookup hide-when-print"
[hidden]="!allowedToAdd">
<form name="watcherForm" novalidate>
- <user-autocompleter [clearAfterSelection]="true"
- (onChange)="addWatcher($event)"
+ <op-user-autocompleter [clearAfterSelection]="true"
+ (valueChange)="addWatcher($event)"
[url]="availableWatchersPath"
class="wp-watcher--autocomplete">
- </user-autocompleter>
+ </op-user-autocompleter>
</form>
</div>
</div>
diff --git a/frontend/src/app/shared/components/autocompleter/members-autocompleter/members-autocompleter.component.ts b/frontend/src/app/shared/components/autocompleter/members-autocompleter/members-autocompleter.component.ts
index eeba0894b11..403f7ab3388 100644
--- a/frontend/src/app/shared/components/autocompleter/members-autocompleter/members-autocompleter.component.ts
+++ b/frontend/src/app/shared/components/autocompleter/members-autocompleter/members-autocompleter.component.ts
@@ -9,7 +9,7 @@ import {
} from 'core-app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component';
import { URLParamsEncoder } from 'core-app/features/hal/services/url-params-encoder';
-export const membersAutocompleterSelector = 'members-autocompleter';
+export const membersAutocompleterSelector = 'op-members-autocompleter';
@Component({
templateUrl: '../user-autocompleter/user-autocompleter.component.html',
@@ -20,9 +20,9 @@ export class MembersAutocompleterComponent extends UserAutocompleterComponent {
@InjectField() pathHelper:PathHelperService;
- protected getAvailableUsers(url:string, searchTerm:any):Observable<IUserAutocompleteItem[]> {
+ public getAvailableUsers(searchTerm:any):Observable<IUserAutocompleteItem[]> {
return this.http
- .get<IUserAutocompleteItem[]>(url,
+ .get<IUserAutocompleteItem[]>(this.url,
{
params: new HttpParams({ encoder: new URLParamsEncoder(), fromObject: { q: searchTerm } }),
responseType: 'json',
diff --git a/frontend/src/app/shared/components/autocompleter/openproject-autocompleter.module.ts b/frontend/src/app/shared/components/autocompleter/openproject-autocompleter.module.ts
index 0b77e266d5d..3ede6c0d497 100644
--- a/frontend/src/app/shared/components/autocompleter/openproject-autocompleter.module.ts
+++ b/frontend/src/app/shared/components/autocompleter/openproject-autocompleter.module.ts
@@ -9,6 +9,7 @@ import { CommonModule } from '@angular/common';
import { DragulaModule } from 'ng2-dragula';
import { InviteUserButtonModule } from 'core-app/features/invite-user-modal/button/invite-user-button.module';
+import { OpenprojectPrincipalRenderingModule } from 'core-app/shared/components/principal/principal-rendering.module';
import { DraggableAutocompleteComponent } from 'core-app/shared/components/autocompleter/draggable-autocomplete/draggable-autocomplete.component';
import { ColorsAutocompleterComponent } from 'core-app/shared/components/colors/colors-autocompleter.component';
@@ -53,6 +54,7 @@ export const OPENPROJECT_AUTOCOMPLETE_COMPONENTS = [
ReactiveFormsModule,
DynamicModule.withComponents(OPENPROJECT_AUTOCOMPLETE_COMPONENTS),
+ OpenprojectPrincipalRenderingModule,
InviteUserButtonModule,
],
exports: OPENPROJECT_AUTOCOMPLETE_COMPONENTS,
diff --git a/frontend/src/app/shared/components/autocompleter/project-autocompleter/project-autocompleter.component.ts b/frontend/src/app/shared/components/autocompleter/project-autocompleter/project-autocompleter.component.ts
index 0c1a0bf0fe6..08f8259f18d 100644
--- a/frontend/src/app/shared/components/autocompleter/project-autocompleter/project-autocompleter.component.ts
+++ b/frontend/src/app/shared/components/autocompleter/project-autocompleter/project-autocompleter.component.ts
@@ -104,6 +104,8 @@ export class ProjectAutocompleterComponent implements ControlValueAccessor {
@Input() public dropdownPosition:'bottom'|'top'|'auto' = 'auto';
+ // ID that should be set on the input HTML element. It is used with
+ // <label> tags that have `for=""` set
@Input() public labelForId = '';
@Input() public apiFilters:ApiV3ListFilter[] = [];
diff --git a/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.html b/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.html
index 454e1f8b760..37d28a1236a 100644
--- a/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.html
+++ b/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.html
@@ -1,24 +1,37 @@
-<ng-select
- [items]="requests.output$ | async"
- bindLabel="name"
- bindValue="id"
- [ngModel]="initialSelection"
- [virtualScroll]="true"
+<op-autocompleter
+ [model]="value"
+
+ [getOptionsFn]="getAvailableUsers.bind(this)"
[trackByFn]="userTracker"
- [typeahead]="requests.input$"
- [loading]="requests.loading$ | async"
- (focus)="onFocus()"
- (change)="onModelChange($event)"
- [appendTo]="appendTo"
+
[multiple]="multiple"
+ [labelForId]="labelForId"
+
+ [appendTo]="appendTo"
+
+ (change)="writeValue($event)"
+ (keydown.escape)="cancel.emit()"
>
- <ng-template ng-option-tmp let-item="item" let-index="index">
+ <ng-template
+ op-autocompleter-option-tmp
+ let-item
+ let-search="search"
+ >
<op-principal
*ngIf="item && item.href"
[principal]="item"
[hideName]="true"
size="mini"
></op-principal>
- {{ item.name }}
+ <span [opSearchHighlight]="search">
+ {{ item.name }}
+ </span>
</ng-template>
-</ng-select>
+</op-autocompleter>
+
+<input
+ #hiddenInput
+ [name]="name"
+ type="hidden"
+ [value]="plainValue"
+/>
diff --git a/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.ts b/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.ts
index c97ddaf883c..c3289210989 100644
--- a/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.ts
+++ b/frontend/src/app/shared/components/autocompleter/user-autocompleter/user-autocompleter.component.ts
@@ -27,29 +27,27 @@
//++
import {
- Component, ElementRef, EventEmitter, Injector, Input, OnInit, Output, ViewChild,
+ ChangeDetectionStrategy, Component, ElementRef, EventEmitter,
+ forwardRef, Injector, Input, OnInit, Output, ViewChild,
} from '@angular/core';
import { HalResourceService } from 'core-app/features/hal/services/hal-resource.service';
import { PathHelperService } from 'core-app/core/path-helper/path-helper.service';
import { I18nService } from 'core-app/core/i18n/i18n.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
-import {
- DebouncedRequestSwitchmap,
- errorNotificationHandler,
-} from 'core-app/shared/helpers/rxjs/debounced-input-switchmap';
import { HalResourceNotificationService } from 'core-app/features/hal/services/hal-resource-notification.service';
import { NgSelectComponent } from '@ng-select/ng-select';
-import { UserResource } from 'core-app/features/hal/resources/user-resource';
import { ApiV3Service } from 'core-app/core/apiv3/api-v3.service';
import { ApiV3FilterBuilder, FilterOperator } from 'core-app/shared/helpers/api-v3/api-v3-filter-builder';
import { populateInputsFromDataset } from 'core-app/shared/components/dataset-inputs';
+import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
+import { ID } from '@datorama/akita';
-export const usersAutocompleterSelector = 'user-autocompleter';
+export const usersAutocompleterSelector = 'op-user-autocompleter';
export interface IUserAutocompleteItem {
+ id:ID;
name:string;
- id:string|null;
href:string|null;
avatar:string|null;
}
@@ -57,41 +55,64 @@ export interface IUserAutocompleteItem {
@Component({
templateUrl: './user-autocompleter.component.html',
selector: usersAutocompleterSelector,
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ providers: [{
+ provide: NG_VALUE_ACCESSOR,
+ useExisting: forwardRef(() => UserAutocompleterComponent),
+ multi: true,
+ }],
})
-export class UserAutocompleterComponent implements OnInit {
+export class UserAutocompleterComponent implements OnInit, ControlValueAccessor {
userTracker = (item:any) => item.href || item.id;
@ViewChild(NgSelectComponent, { static: true }) public ngSelectComponent:NgSelectComponent;
- @Output() public onChange = new EventEmitter<IUserAutocompleteItem>();
-
@Input() public clearAfterSelection = false;
+ @Input() public name = '';
+
// Load all users as default
@Input() public url:string = this.apiV3Service.users.path;
+ // ID that should be set on the input HTML element. It is used with
+ // <label> tags that have `for=""` set
+ @Input() public labelForId = '';
+
@Input() public allowEmpty = false;
@Input() public appendTo = '';
@Input() public multiple = false;
- @Input() public initialSelection:number|null = null;
+ @Input('value') public _value:IUserAutocompleteItem|IUserAutocompleteItem[]|null = null;
+
+ get value():IUserAutocompleteItem|IUserAutocompleteItem[]|null {
+ return this._value;
+ }
+
+ set value(value:IUserAutocompleteItem|IUserAutocompleteItem[]|null) {
+ this._value = value;
+ this.onChange(value);
+ this.valueChange.emit(value);
+ this.onTouched(value);
+ setTimeout(() => {
+ this.hiddenInput.nativeElement?.dispatchEvent(new Event('change'));
+ }, 100);
+ }
+
+ get plainValue():ID|ID[] {
+ return (Array.isArray(this.value) ? this.value?.map((i) => i.id) : this.value?.id) || '';
+ }
@Input() public additionalFilters:{ selector:string; operator:FilterOperator, values:string[] }[] = [];
public inputFilters:ApiV3FilterBuilder = new ApiV3FilterBuilder();
- @Input() public updateInputSelector:string;
+ @Output() public valueChange = new EventEmitter<IUserAutocompleteItem|IUserAutocompleteItem[]|null>();
- // Update an input field after changing, used when externally loaded
- private updateInputField:HTMLInputElement|undefined;
+ @Output() cancel = new EventEmitter();
- /** Keep a switchmap for search term and loading state */
- public requests = new DebouncedRequestSwitchmap<string, IUserAutocompleteItem>(
- (searchTerm:string) => this.getAvailableUsers(this.url, searchTerm),
- errorNotificationHandler(this.halNotification),
- );
+ @ViewChild('hiddenInput') hiddenInput:ElementRef;
constructor(
public elementRef:ElementRef,
@@ -106,40 +127,10 @@ export class UserAutocompleterComponent implements OnInit {
}
ngOnInit() {
- if (this.updateInputSelector) {
- this.updateInputField = document.getElementsByName(this.updateInputSelector)[0] as HTMLInputElement|undefined;
- this.setInitialSelection();
- }
-
this.additionalFilters.forEach((filter) => this.inputFilters.add(filter.selector, filter.operator, filter.values));
}
- public onFocus() {
- if (!this.requests.lastRequestedValue) {
- this.requests.input$.next('');
- }
- }
-
- public onModelChange(user:any) {
- if (user) {
- this.onChange.emit(user);
- this.requests.input$.next('');
-
- if (this.clearAfterSelection) {
- this.ngSelectComponent.clearItem(user);
- }
-
- if (this.updateInputField) {
- if (this.multiple) {
- this.updateInputField.value = user.map((u:UserResource) => u.id);
- } else {
- this.updateInputField.value = user.id;
- }
- }
- }
- }
-
- protected getAvailableUsers(url:string, searchTerm:any):Observable<IUserAutocompleteItem[]> {
+ public getAvailableUsers(searchTerm:any):Observable<IUserAutocompleteItem[]> {
// Need to clone the filters to not add additional filters on every
// search term being processed.
const searchFilters = this.inputFilters.clone();
@@ -149,7 +140,7 @@ export class UserAutocompleterComponent implements OnInit {
}
return this.halResourceService
- .get(url, { filters: searchFilters.toJson() })
+ .get(this.url, { filters: searchFilters.toJson() })
.pipe(
map((res) => {
const options = res.elements.map((el:any) => ({
@@ -165,10 +156,19 @@ export class UserAutocompleterComponent implements OnInit {
);
}
- private setInitialSelection() {
- if (this.updateInputField) {
- const id = parseInt(this.updateInputField.value);
- this.initialSelection = isNaN(id) ? null : id;
- }
+ writeValue(value:IUserAutocompleteItem|null):void {
+ this.value = value;
+ }
+
+ onChange = (_:IUserAutocompleteItem|IUserAutocompleteItem[]|null):void => {};
+
+ onTouched = (_:IUserAutocompleteItem|IUserAutocompleteItem[]|null):void => {};
+
+ registerOnChange(fn:(_:IUserAutocompleteItem|IUserAutocompleteItem[]|null) => void):void {
+ this.onChange = fn;
+ }
+
+ registerOnTouched(fn:(_:IUserAutocompleteItem|IUserAutocompleteItem[]|null) => void):void {
+ this.onTouched = fn;
}
}
diff --git a/frontend/src/app/shared/components/time_entries/form/form.component.html b/frontend/src/app/shared/components/time_entries/form/form.component.html
index 79cfbca50ab..e147e055545 100644
--- a/frontend/src/app/shared/components/time_entries/form/form.component.html
+++ b/frontend/src/app/shared/components/time_entries/form/form.component.html
@@ -4,9 +4,6 @@
[inEditMode]="inEditMode"
(onSaved)="signalModifiedEntry($event)">
<div class="attributes-map">
- <!-- <user-autocompleter [clearAfterSelection]="false"
- [url]="availableAssigneesPath">
- </user-autocompleter> -->
<div class="attributes-map--key"
[ngClass]="{'-required': isRequired('user')}"
[textContent]="text.attributes.user">
diff --git a/frontend/src/app/shared/components/time_entries/form/form.component.ts b/frontend/src/app/shared/components/time_entries/form/form.component.ts
index 95bce353b7a..d0a359d101f 100644
--- a/frontend/src/app/shared/components/time_entries/form/form.component.ts
+++ b/frontend/src/app/shared/components/time_entries/form/form.component.ts
@@ -17,7 +17,6 @@ import { HalResource } from 'core-app/features/hal/resources/hal-resource';
import { EditFormComponent } from 'core-app/shared/components/fields/edit/edit-form/edit-form.component';
import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';
import { ResourceChangeset } from 'core-app/shared/components/fields/changeset/resource-changeset';
-import { ApiV3Service } from 'core-app/core/apiv3/api-v3.service';
@Component({
templateUrl: './form.component.html',
@@ -54,8 +53,7 @@ export class TimeEntryFormComponent extends UntilDestroyedMixin implements OnIni
constructor(readonly halEditing:HalResourceEditingService,
readonly cdRef:ChangeDetectorRef,
- readonly i18n:I18nService,
- readonly apiV3Service:ApiV3Service) {
+ readonly i18n:I18nService) {
super();
}
@@ -67,8 +65,6 @@ export class TimeEntryFormComponent extends UntilDestroyedMixin implements OnIni
this.untilDestroyed(),
)
.subscribe((changeset) => {
- // this.availableAssigneesPath = this.apiV3Service.projects.id(changeset.project.id).available_assignees.path
-
if (changeset && changeset.workPackage) {
this.workPackageSelected = true;
this.cdRef.markForCheck();
diff --git a/lib/api/v3/work_packages/work_package_representer.rb b/lib/api/v3/work_packages/work_package_representer.rb
index 3fa38eb63e9..08e19a37789 100644
--- a/lib/api/v3/work_packages/work_package_representer.rb
+++ b/lib/api/v3/work_packages/work_package_representer.rb
@@ -80,7 +80,7 @@ module API
end
link :logTime,
- cache_if: -> { current_user_allowed_to(:log_own_time, context: represented.project) } do
+ cache_if: -> { current_user_allowed_to(:log_time, context: represented.project) || current_user_allowed_to(:log_own_time, context: represented.project) } do
next if represented.new_record?
{
diff --git a/modules/costs/app/contracts/time_entries/base_contract.rb b/modules/costs/app/contracts/time_entries/base_contract.rb
index 1e0126e9142..e7d82456418 100644
--- a/modules/costs/app/contracts/time_entries/base_contract.rb
+++ b/modules/costs/app/contracts/time_entries/base_contract.rb
@@ -59,7 +59,6 @@ module TimeEntries
attribute :tmonth
attribute :tweek
attribute :user_id
- attribute :logged_by_id
def assignable_activities
if model.project
@@ -105,5 +104,9 @@ module TimeEntries
def work_package_not_in_project?
model.work_package && model.project != model.work_package.project
end
+
+ def validate_logged_by_current_user
+ errors.add :logged_by_id, :not_current_user if model.logged_by != logged_by
+ end
end
end
diff --git a/modules/costs/app/contracts/time_entries/create_contract.rb b/modules/costs/app/contracts/time_entries/create_contract.rb
index 568fbcc255f..6703a2202d7 100644
--- a/modules/costs/app/contracts/time_entries/create_contract.rb
+++ b/modules/costs/app/contracts/time_entries/create_contract.rb
@@ -33,11 +33,19 @@ module TimeEntries
private
def user_allowed_to_add
- if model.project &&
- (!user.allowed_to?(:log_time, model.project) ||
- (model.user != user && !user.allowed_to?(:log_own_time, model.project)))
- errors.add :base, :error_unauthorized
- end
+ return unless model.project && model.user
+ return if allowed_to_log_for_others?
+ return if allowed_to_log_to_himself?
+
+ errors.add :base, :error_unauthorized
+ end
+
+ def allowed_to_log_for_others?
+ user.allowed_to?(:log_time, model.project)
+ end
+
+ def allowed_to_log_to_himself?
+ model.user == user && user.allowed_to?(:log_own_time, model.project)
end
end
end
diff --git a/modules/costs/app/services/time_entries/set_attributes_service.rb b/modules/costs/app/services/time_entries/set_attributes_service.rb
index 0fe591af39b..6ef416c27b7 100644
--- a/modules/costs/app/services/time_entries/set_attributes_service.rb
+++ b/modules/costs/app/services/time_entries/set_attributes_service.rb
@@ -38,17 +38,20 @@ module TimeEntries
if no_project_or_context_changed?
model.project = model.work_package&.project
end
+
+ set_logged_by unless model.user_changed?
end
def set_default_attributes(*)
set_default_user
set_default_activity
set_default_hours
- set_logged_by
end
def set_logged_by
- model.logged_by = user
+ model.change_by_system do
+ model.logged_by = user
+ end
end
def set_default_user
diff --git a/modules/costs/lib/api/v3/time_entries/available_projects_api.rb b/modules/costs/lib/api/v3/time_entries/available_projects_api.rb
index b2d9df8bc55..35003d2f759 100644
--- a/modules/costs/lib/api/v3/time_entries/available_projects_api.rb
+++ b/modules/costs/lib/api/v3/time_entries/available_projects_api.rb
@@ -41,6 +41,7 @@ module API
scope: -> {
Project
.where(id: Project.allowed_to(User.current, :log_own_time))
+ .or(Project.where(id: Project.allowed_to(User.current, :log_time)))
.or(Project.where(id: Project.allowed_to(User.current, :edit_time_entries)))
.or(Project.where(id: Project.allowed_to(User.current, :edit_own_time_entries)))
})
diff --git a/modules/costs/lib/api/v3/time_entries/available_work_packages_on_create_api.rb b/modules/costs/lib/api/v3/time_entries/available_work_packages_on_create_api.rb
index d92b0fc6dc9..a2dd934900e 100644
--- a/modules/costs/lib/api/v3/time_entries/available_work_packages_on_create_api.rb
+++ b/modules/costs/lib/api/v3/time_entries/available_work_packages_on_create_api.rb
@@ -40,6 +40,7 @@ module API
helpers do
def allowed_scope
WorkPackage.where(project_id: Project.allowed_to(User.current, :log_own_time))
+ .or(WorkPackage.where(project_id: Project.allowed_to(User.current, :log_time)))
end
end
diff --git a/modules/costs/lib/api/v3/time_entries/create_form_api.rb b/modules/costs/lib/api/v3/time_entries/create_form_api.rb
index 5fb33aeb319..d4ef3929056 100644
--- a/modules/costs/lib/api/v3/time_entries/create_form_api.rb
+++ b/modules/costs/lib/api/v3/time_entries/create_form_api.rb
@@ -32,7 +32,7 @@ module API
class CreateFormAPI < ::API::OpenProjectAPI
resource :form do
after_validation do
- authorize :log_own_time, global: true
+ authorize_any %i[log_time log_own_time], global: true
end
post &::API::V3::Utilities::Endpoints::CreateForm
diff --git a/modules/costs/lib/api/v3/time_entries/schemas/time_entry_schema_representer.rb b/modules/costs/lib/api/v3/time_entries/schemas/time_entry_schema_representer.rb
index 82ff06ff2d7..ec93ce0ef95 100644
--- a/modules/costs/lib/api/v3/time_entries/schemas/time_entry_schema_representer.rb
+++ b/modules/costs/lib/api/v3/time_entries/schemas/time_entry_schema_representer.rb
@@ -59,7 +59,7 @@ module API
schema_with_allowed_link :user,
has_default: false,
- required: false,
+ required: true,
href_callback: ->(*) {
allowed_user_href
}
@@ -71,6 +71,13 @@ module API
allowed_work_package_href
}
+ schema_with_allowed_link :project,
+ has_default: false,
+ required: false,
+ href_callback: ->(*) {
+ allowed_projects_href
+ }
+
schema_with_allowed_collection :activity,
type: 'TimeEntriesActivity',
value_representer: TimeEntriesActivityRepresenter,
diff --git a/modules/costs/lib/api/v3/time_entries/time_entry_collection_representer.rb b/modules/costs/lib/api/v3/time_entries/time_entry_collection_representer.rb
index 7dcc294201f..a2c4e790b33 100644
--- a/modules/costs/lib/api/v3/time_entries/time_entry_collection_representer.rb
+++ b/modules/costs/lib/api/v3/time_entries/time_entry_collection_representer.rb
@@ -31,7 +31,7 @@ module API
module TimeEntries
class TimeEntryCollectionRepresenter < ::API::Decorators::OffsetPaginatedCollection
link :createTimeEntry do
- next unless current_user.allowed_to_globally?(:log_own_time)
+ next unless current_user.allowed_to_globally?(:log_own_time) || current_user.allowed_to_globally?(:log_time)
{
href: api_v3_paths.create_time_entry_form,
@@ -40,7 +40,7 @@ module API
end
link :createTimeEntryImmediately do
- next unless current_user.allowed_to_globally?(:log_own_time)
+ next unless current_user.allowed_to_globally?(:log_own_time) || current_user.allowed_to_globally?(:log_time)
{
href: api_v3_paths.time_entries,
diff --git a/modules/costs/spec/contracts/time_entries/create_contract_spec.rb b/modules/costs/spec/contracts/time_entries/create_contract_spec.rb
index 1187f9d50c0..a2226e652ab 100644
--- a/modules/costs/spec/contracts/time_entries/create_contract_spec.rb
+++ b/modules/costs/spec/contracts/time_entries/create_contract_spec.rb
@@ -66,19 +66,37 @@ describe TimeEntries::CreateContract do
end
context 'if time_entry user is not contract user' do
+ let(:other_user) do
+ build_stubbed(:user) do |user|
+ allow(user)
+ .to receive(:allowed_to?) do |permission, permission_project|
+ permissions.include?(permission) && time_entry_project == permission_project
+ end
+ end
+ end
+ let(:permissions) { [] }
let(:time_entry_user) { other_user }
it 'is invalid' do
- expect_valid(false, user_id: %i(not_current_user))
+ expect_valid(false, base: %i(error_unauthorized))
end
end
context 'if time_entry user was not set by system' do
+ let(:other_user) do
+ build_stubbed(:user) do |user|
+ allow(user)
+ .to receive(:allowed_to?) do |permission, permission_project|
+ permissions.include?(permission) && time_entry_project == permission_project
+ end
+ end
+ end
let(:time_entry_user) { other_user }
+ let(:permissions) { [] }
let(:changed_by_system) { {} }
it 'is invalid' do
- expect_valid(false, user_id: %i(not_current_user error_readonly))
+ expect_valid(false, base: %i(error_unauthorized))
end
end
@@ -86,7 +104,7 @@ describe TimeEntries::CreateContract do
let(:time_entry_user) { nil }
it 'is invalid' do
- expect_valid(false, user_id: %i(blank not_current_user))
+ expect_valid(false, user_id: %i(blank))
end
end
end
diff --git a/modules/costs/spec/contracts/time_entries/update_contract_spec.rb b/modules/costs/spec/contracts/time_entries/update_contract_spec.rb
index eacc1344ea3..19c88627b3b 100644
--- a/modules/costs/spec/contracts/time_entries/update_contract_spec.rb
+++ b/modules/costs/spec/contracts/time_entries/update_contract_spec.rb
@@ -120,9 +120,11 @@ describe TimeEntries::UpdateContract do
end
context 'if the user is changed' do
+ let(:permissions) { %i(edit_own_time_entries) }
+
it 'is invalid' do
time_entry.user = other_user
- expect_valid(false, user_id: %i(error_readonly))
+ expect_valid(false, base: %i(error_unauthorized))
end
end
diff --git a/modules/costs/spec/lib/api/v3/time_entries/schemas/time_entry_schema_representer_spec.rb b/modules/costs/spec/lib/api/v3/time_entries/schemas/time_entry_schema_representer_spec.rb
index f43196329c7..f3e9a6b43dd 100644
--- a/modules/costs/spec/lib/api/v3/time_entries/schemas/time_entry_schema_representer_spec.rb
+++ b/modules/costs/spec/lib/api/v3/time_entries/schemas/time_entry_schema_representer_spec.rb
@@ -45,11 +45,12 @@ describe ::API::V3::TimeEntries::Schemas::TimeEntrySchemaRepresenter do
contract = double('contract',
new_record?: new_record,
id: new_record ? nil : 5,
- project: assigned_project)
+ project: assigned_project,
+ project_id: project.id)
allow(contract)
.to receive(:writable?) do |attribute|
- %w(spent_on hours project work_package activity comment).include?(attribute.to_s)
+ %w(spent_on hours project work_package activity comment user).include?(attribute.to_s)
end
allow(contract)
@@ -155,7 +156,7 @@ describe ::API::V3::TimeEntries::Schemas::TimeEntrySchemaRepresenter do
let(:type) { 'User' }
let(:name) { TimeEntry.human_attribute_name('user') }
let(:required) { true }
- let(:writable) { false }
+ let(:writable) { true }
let(:location) { '_links' }
end
end
diff --git a/modules/costs/spec/requests/api/time_entries/create_form_resource_spec.rb b/modules/costs/spec/requests/api/time_entries/create_form_resource_spec.rb
index 2aaf0075611..8330df7a3fa 100644
--- a/modules/costs/spec/requests/api/time_entries/create_form_resource_spec.rb
+++ b/modules/costs/spec/requests/api/time_entries/create_form_resource_spec.rb
@@ -49,7 +49,7 @@ describe ::API::V3::TimeEntries::CreateFormAPI, content_type: :json do
create(:work_package, project:)
end
let(:other_user) { create(:user) }
- let(:permissions) { %i[log_time view_work_packages] }
+ let(:permissions) { %i[log_own_time view_work_packages] }
let(:path) { api_v3_paths.create_time_entry_form }
let(:parameters) { {} }
@@ -149,6 +149,10 @@ describe ::API::V3::TimeEntries::CreateFormAPI, content_type: :json do
expect(body)
.to be_json_eql(api_v3_paths.time_entries_activity(active_activity.id).to_json)
.at_path('_embedded/payload/_links/activity/href')
+
+ expect(body)
+ .to be_json_eql(api_v3_paths.user(user.id).to_json)
+ .at_path('_embedded/payload/_links/user/href')
expect(body)
.to be_json_eql("some comment".to_json)
@@ -165,10 +169,6 @@ describe ::API::V3::TimeEntries::CreateFormAPI, content_type: :json do
expect(body)
.to be_json_eql("some cf text".to_json)
.at_path("_embedded/payload/customField#{custom_field.id}/raw")
-
- # As the user is always the current user, it is not part of the payload
- expect(body)
- .not_to have_json_path('_embedded/payload/_links/user')
end
it 'has the available values listed in the schema' do
diff --git a/modules/costs/spec/requests/api/time_entries/update_form_resource_spec.rb b/modules/costs/spec/requests/api/time_entries/update_form_resource_spec.rb
index a960b64027e..0a810d6e098 100644
--- a/modules/costs/spec/requests/api/time_entries/update_form_resource_spec.rb
+++ b/modules/costs/spec/requests/api/time_entries/update_form_resource_spec.rb
@@ -139,9 +139,9 @@ describe ::API::V3::TimeEntries::UpdateFormAPI, content_type: :json do
.to be_json_eql("some cf text".to_json)
.at_path("_embedded/payload/customField#{custom_field.id}/raw")
- # As the user is always the current user, it is not part of the payload
expect(body)
- .not_to have_json_path('_embedded/payload/_links/user')
+ .to be_json_eql(api_v3_paths.user(time_entry.user.id).to_json)
+ .at_path("_embedded/payload/_links/user/href")
end
it 'has the available values listed in the schema' do
diff --git a/modules/reporting/app/helpers/reporting_helper.rb b/modules/reporting/app/helpers/reporting_helper.rb
index 5793835280d..8bb835d0db6 100644
--- a/modules/reporting/app/helpers/reporting_helper.rb
+++ b/modules/reporting/app/helpers/reporting_helper.rb
@@ -106,7 +106,7 @@ module ReportingHelper
case key.to_sym
when :activity_id then mapped value, Enumeration, "<i>#{I18n.t(:caption_material_costs)}</i>"
when :project_id then link_to_project Project.find(value.to_i)
- when :user_id, :assigned_to_id, :author_id then link_to_user(User.find_by_id(value.to_i) || DeletedUser.first)
+ when :user_id, :assigned_to_id, :author_id, :logged_by_id then link_to_user(User.find_by_id(value.to_i) || DeletedUser.first)
when :tyear, :units then h(value.to_s)
when :tweek then "#{I18n.t(:label_week)} ##{h value}"
when :tmonth then month_name(value.to_i)
diff --git a/modules/reporting/app/models/cost_query/filter.rb b/modules/reporting/app/models/cost_query/filter.rb
index eeec3875a0c..71b2743e4ba 100644
--- a/modules/reporting/app/models/cost_query/filter.rb
+++ b/modules/reporting/app/models/cost_query/filter.rb
@@ -52,6 +52,7 @@ class CostQuery::Filter < Report::Filter
CostQuery::Filter::TypeId,
CostQuery::Filter::UpdatedOn,
CostQuery::Filter::UserId,
+ CostQuery::Filter::LoggedById,
CostQuery::Filter::PermissionFilter,
*CostQuery::Filter::CustomFieldEntries.all
]
diff --git a/modules/reporting/app/models/cost_query/filter/logged_by_id.rb b/modules/reporting/app/models/cost_query/filter/logged_by_id.rb
new file mode 100644
index 00000000000..396c0f6e5db
--- /dev/null
+++ b/modules/reporting/app/models/cost_query/filter/logged_by_id.rb
@@ -0,0 +1,66 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2022 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+class CostQuery::Filter::LoggedById < Report::Filter::Base
+ def self.label
+ WorkPackage.human_attribute_name(:logged_by)
+ end
+
+ def self.me_value
+ 'me'.freeze
+ end
+
+ def transformed_values
+ # Map the special 'me' value
+ super
+ .map { |val| replace_me_value(val) }
+ .compact
+ end
+
+ def replace_me_value(value)
+ return value unless value == CostQuery::Filter::LoggedById.me_value
+
+ if User.current.logged?
+ User.current.id
+ end
+ end
+
+ def self.available_values(*)
+ # All users which are members in projects the user can see.
+ # Excludes the anonymous user
+ users = User.joins(members: :project)
+ .merge(Project.visible)
+ .human
+ .select(User::USER_FORMATS_STRUCTURE[Setting.user_format].map(&:to_s) << :id)
+ .distinct
+
+ values = users.map { |u| [u.name, u.id] }
+ values.unshift [::I18n.t(:label_me), me_value] if User.current.logged?
+ values
+ end
+end
diff --git a/modules/reporting/app/models/cost_query/group_by.rb b/modules/reporting/app/models/cost_query/group_by.rb
index 70bce4c657b..10511808dd6 100644
--- a/modules/reporting/app/models/cost_query/group_by.rb
+++ b/modules/reporting/app/models/cost_query/group_by.rb
@@ -49,6 +49,7 @@ class CostQuery::GroupBy < Report::GroupBy
CostQuery::GroupBy::AssignedToId,
CostQuery::GroupBy::CategoryId,
CostQuery::GroupBy::StatusId,
+ CostQuery::GroupBy::LoggedById,
*CostQuery::GroupBy::CustomFieldEntries.all
]
end
diff --git a/modules/reporting/app/models/cost_query/group_by/author_id.rb b/modules/reporting/app/models/cost_query/group_by/author_id.rb
index 23c7971be9e..7b0b9887718 100644
--- a/modules/reporting/app/models/cost_query/group_by/author_id.rb
+++ b/modules/reporting/app/models/cost_query/group_by/author_id.rb
@@ -27,9 +27,6 @@
#++
class CostQuery::GroupBy::AuthorId < Report::GroupBy::Base
- join_table WorkPackage
- applies_for :label_work_package_attributes
-
def self.label
WorkPackage.human_attribute_name(:author)
end
diff --git a/modules/reporting/app/models/cost_query/group_by/logged_by_id.rb b/modules/reporting/app/models/cost_query/group_by/logged_by_id.rb
new file mode 100644
index 00000000000..d23b8f6afaa
--- /dev/null
+++ b/modules/reporting/app/models/cost_query/group_by/logged_by_id.rb
@@ -0,0 +1,33 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2022 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+class CostQuery::GroupBy::LoggedById < Report::GroupBy::Base
+ def self.label
+ WorkPackage.human_attribute_name(:logged_by)
+ end
+end
diff --git a/modules/reporting/app/models/cost_query/sql_statement.rb b/modules/reporting/app/models/cost_query/sql_statement.rb
index bd6b2120c85..ad8eb2c92bb 100644
--- a/modules/reporting/app/models/cost_query/sql_statement.rb
+++ b/modules/reporting/app/models/cost_query/sql_statement.rb
@@ -102,7 +102,7 @@ class CostQuery::SqlStatement < Report::SqlStatement
#
# @param [CostQuery::SqlStatement] query The statement to adjust
def self.unify_time_entries(query)
- query.select :activity_id, units: :hours, cost_type_id: -1
+ query.select :activity_id, :logged_by_id, units: :hours, cost_type_id: -1
query.select cost_type: quoted_label(:caption_labor)
end
@@ -111,7 +111,7 @@ class CostQuery::SqlStatement < Report::SqlStatement
#
# @param [CostQuery::SqlStatement] query The statement to adjust
def self.unify_cost_entries(query)
- query.select :units, :cost_type_id, activity_id: -1
+ query.select :units, :cost_type_id, activity_id: -1, logged_by_id: -1
query.select cost_type: "cost_types.name"
query.join CostType
end
diff --git a/modules/reporting/lib/widget/table/entry_table.rb b/modules/reporting/lib/widget/table/entry_table.rb
index c971feff831..f6f156967bc 100644
--- a/modules/reporting/lib/widget/table/entry_table.rb
+++ b/modules/reporting/lib/widget/table/entry_table.rb
@@ -27,7 +27,7 @@
#++
class ::Widget::Table::EntryTable < ::Widget::Table
- FIELDS = %i[spent_on user_id activity_id work_package_id comments project_id]
+ FIELDS = %i[spent_on user_id activity_id work_package_id comments logged_by_id project_id]
def render
content = content_tag :div, class: 'generic-table--container -with-footer' do
diff --git a/spec/support/pages/members.rb b/spec/support/pages/members.rb
index cc6b0d8f67c..bacd7eda506 100644
--- a/spec/support/pages/members.rb
+++ b/spec/support/pages/members.rb
@@ -170,7 +170,7 @@ module Pages
end
def select_principal!(principal_name)
- select_autocomplete page.find("members-autocompleter"),
+ select_autocomplete page.find("op-members-autocompleter"),
query: principal_name,
results_selector: '.ng-dropdown-panel-items'
end
@@ -187,7 +187,7 @@ module Pages
end
def search_principal!(query)
- search_autocomplete page.find("members-autocompleter"),
+ search_autocomplete page.find("op-members-autocompleter"),
query:,
results_selector: '.ng-dropdown-panel-items'
end