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

resolving conflict override situations

Jonas Jabari0765c74787a8
diff --git a/app/components/work_packages/activities_tab/index_component.rb b/app/components/work_packages/activities_tab/index_component.rb
index 92f4cdad2b6..6dc1e101000 100644
--- a/app/components/work_packages/activities_tab/index_component.rb
+++ b/app/components/work_packages/activities_tab/index_component.rb
@@ -48,20 +48,21 @@ module WorkPackages
attr_reader :work_package, :filter, :last_server_timestamp
def wrapper_data_attributes
+ stimulus_controller = "work-packages--activities-tab--index"
+
{
test_selector: "op-wp-activity-tab",
- controller: "work-packages--activities-tab--index",
+ controller: stimulus_controller,
"application-target": "dynamic",
- "work-packages--activities-tab--index-update-streams-url-value": update_streams_work_package_activities_url(
- work_package
- ),
- "work-packages--activities-tab--index-sorting-value": journal_sorting,
- "work-packages--activities-tab--index-filter-value": filter,
- "work-packages--activities-tab--index-user-id-value": User.current.id,
- "work-packages--activities-tab--index-work-package-id-value": work_package.id,
- "work-packages--activities-tab--index-polling-interval-in-ms-value": polling_interval,
- "work-packages--activities-tab--index-notification-center-path-name-value": notifications_path,
- "work-packages--activities-tab--index-last-server-timestamp-value": last_server_timestamp
+ "#{stimulus_controller}-update-streams-url-value": update_streams_work_package_activities_url(work_package),
+ "#{stimulus_controller}-sorting-value": journal_sorting,
+ "#{stimulus_controller}-filter-value": filter,
+ "#{stimulus_controller}-user-id-value": User.current.id,
+ "#{stimulus_controller}-work-package-id-value": work_package.id,
+ "#{stimulus_controller}-polling-interval-in-ms-value": polling_interval,
+ "#{stimulus_controller}-notification-center-path-name-value": notifications_path,
+ "#{stimulus_controller}-show-conflict-flash-message-url-value": show_conflict_flash_message_work_packages_path,
+ "#{stimulus_controller}-last-server-timestamp-value": last_server_timestamp
}
end
diff --git a/app/components/work_packages/activities_tab/journals/item_component.html.erb b/app/components/work_packages/activities_tab/journals/item_component.html.erb
index 0e87fad9783..4ade6661700 100644
--- a/app/components/work_packages/activities_tab/journals/item_component.html.erb
+++ b/app/components/work_packages/activities_tab/journals/item_component.html.erb
@@ -1,6 +1,8 @@
<%=
component_wrapper(data: wrapper_data_attributes, class: "work-packages-activities-tab-journals-item-component") do
- flex_layout(data: { test_selector: "op-wp-journal-entry-#{journal.id}" }) do |journal_container|
+ flex_layout(data: {
+ test_selector: "op-wp-journal-entry-#{journal.id}"
+ }) do |journal_container|
if show_comment_container?
journal_container.with_row do
render(border_box_container(
diff --git a/app/components/work_packages/activities_tab/journals/item_component/details.html.erb b/app/components/work_packages/activities_tab/journals/item_component/details.html.erb
index 04e3144a0aa..22abf93d2c9 100644
--- a/app/components/work_packages/activities_tab/journals/item_component/details.html.erb
+++ b/app/components/work_packages/activities_tab/journals/item_component/details.html.erb
@@ -1,6 +1,14 @@
<%=
component_wrapper(class: "work-packages-activities-tab-journals-item-component-details") do
- flex_layout(my: 0, border: :left, classes: "work-packages-activities-tab-journals-item-component-details--journal-details-container") do |details_container|
+ flex_layout(
+ my: 0,
+ border: :left,
+ classes: "work-packages-activities-tab-journals-item-component-details--journal-details-container",
+ data: {
+ "journal-with-changeset-updated-at": journal.updated_at.to_i, # used for the stimulus controller to maintain state
+ "journal-with-changeset-user-id": journal.user_id
+ }
+ ) do |details_container|
case filter
when :only_comments
render_empty_line(details_container) unless journal.notes.blank? && !journal.noop?
diff --git a/app/components/work_packages/update_conflict_component.rb b/app/components/work_packages/update_conflict_component.rb
new file mode 100644
index 00000000000..a6b064acea0
--- /dev/null
+++ b/app/components/work_packages/update_conflict_component.rb
@@ -0,0 +1,72 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2024 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.
+#++
+
+module WorkPackages
+ class UpdateConflictComponent < ApplicationComponent
+ include OpPrimer::ComponentHelpers
+ include OpTurbo::Streamable
+
+ def initialize(scheme: :warning, button_text: I18n.t("label_meeting_reload"))
+ super
+
+ @scheme = scheme
+ @button_text = button_text
+
+ if %i[warning danger].exclude?(@scheme)
+ raise ArgumentError, "Invalid scheme: #{@scheme}. Must be :warning or :danger."
+ end
+ end
+
+ def call
+ render(
+ ::OpPrimer::FlashComponent.new(
+ scheme: @scheme,
+ icon: @scheme == :danger ? :stop : :"alert-fill",
+ dismiss_scheme: :hide,
+ unique_key: "work-package-update-conflict",
+ data: {
+ "banner-scheme": @scheme.to_s # used for testing
+ }
+ )
+ ) do |banner|
+ banner.with_action_button(
+ tag: :a,
+ href: "#",
+ data: {
+ turbo: false,
+ action: "click->flash#reloadPage",
+ test_selector: "op-work-package-update-conflict-reload-button"
+ },
+ size: :medium
+ ) { @button_text }
+
+ content
+ end
+ end
+ end
+end
diff --git a/app/controllers/work_packages_controller.rb b/app/controllers/work_packages_controller.rb
index 3d8e1298603..c17fec99524 100644
--- a/app/controllers/work_packages_controller.rb
+++ b/app/controllers/work_packages_controller.rb
@@ -32,6 +32,7 @@ class WorkPackagesController < ApplicationController
include Layout
include WorkPackagesControllerHelper
include OpTurbo::DialogStreamHelper
+ include OpTurbo::ComponentStream
accept_key_auth :index, :show
@@ -40,6 +41,8 @@ class WorkPackagesController < ApplicationController
before_action :load_and_authorize_in_optional_project,
:check_allowed_export,
:protect_from_unauthorized_export, only: %i[index export_dialog]
+
+ before_action :authorize, only: :show_conflict_flash_message
authorization_checked! :index, :show, :export_dialog
before_action :load_and_validate_query, only: :index, unless: -> { request.format.html? }
@@ -90,6 +93,19 @@ class WorkPackagesController < ApplicationController
respond_with_dialog WorkPackages::Exports::ModalDialogComponent.new(query: @query, project: @project, title: params[:title])
end
+ def show_conflict_flash_message
+ scheme = params[:scheme]&.to_sym || :danger
+
+ update_flash_message_via_turbo_stream(
+ component: WorkPackages::UpdateConflictComponent,
+ scheme:,
+ message: I18n.t("notice_locking_conflict_#{scheme}"),
+ button_text: I18n.t("notice_locking_conflict_action_button")
+ )
+
+ respond_with_turbo_streams
+ end
+
protected
def load_and_validate_query_for_export
diff --git a/config/initializers/permissions.rb b/config/initializers/permissions.rb
index 91a8810c924..51b4d6184a4 100644
--- a/config/initializers/permissions.rb
+++ b/config/initializers/permissions.rb
@@ -219,7 +219,7 @@ Rails.application.reloader.to_prepare do
{
versions: %i[index show status_by],
journals: %i[index],
- work_packages: %i[show index],
+ work_packages: %i[show index show_conflict_flash_message],
work_packages_api: [:get],
"work_packages/reports": %i[report report_details],
"work_packages/activities_tab": %i[index update_streams update_sorting update_filter],
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 50c86ac363c..1fca7d6b14d 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -2955,6 +2955,9 @@ en:
notice_locking_conflict: "Information has been updated by at least one other user in the meantime."
notice_locking_conflict_additional_information: "The update(s) came from %{users}."
notice_locking_conflict_reload_page: "Please reload the page, review the changes and reapply your updates."
+ notice_locking_conflict_warning: "This page has been updated by someone else. To not lose your edits, copy them locally and reload to view the updated version."
+ notice_locking_conflict_danger: "Could not save your changes because of conflicting modifications. To not lose your edits, copy them locally and reload to view the updated version."
+ notice_locking_conflict_action_button: "Discard changes and reload"
notice_member_added: Added %{name} to the project.
notice_members_added: Added %{number} users to the project.
notice_member_removed: "Removed %{user} from project."
diff --git a/config/locales/js-en.yml b/config/locales/js-en.yml
index 5928b444704..322eeb3246f 100644
--- a/config/locales/js-en.yml
+++ b/config/locales/js-en.yml
@@ -391,8 +391,6 @@ en:
format:
date: "%{attribute} is no valid date - YYYY-MM-DD expected."
general: "An error has occurred."
- warning:
- potential_update_conflict: "The resource you're about to update was edited by another user."
homescreen:
blocks:
diff --git a/config/routes.rb b/config/routes.rb
index e7a185ba077..918159bfbac 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -600,6 +600,7 @@ Rails.application.routes.draw do
as: :work_package_progress
end
get "/export_dialog" => "work_packages#export_dialog", on: :collection, as: "export_dialog"
+ get :show_conflict_flash_message, on: :collection # we don't need a specific work package for this
get "/split_view/update_counter" => "work_packages/split_view#update_counter",
on: :member
diff --git a/frontend/src/app/features/work-packages/services/notifications/work-package-notification.service.ts b/frontend/src/app/features/work-packages/services/notifications/work-package-notification.service.ts
index 2b07cf74b1f..7044fb5d375 100644
--- a/frontend/src/app/features/work-packages/services/notifications/work-package-notification.service.ts
+++ b/frontend/src/app/features/work-packages/services/notifications/work-package-notification.service.ts
@@ -32,12 +32,14 @@ import { HalResourceNotificationService } from 'core-app/features/hal/services/h
import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';
import { ApiV3Service } from 'core-app/core/apiv3/api-v3.service';
import { HalResource } from 'core-app/features/hal/resources/hal-resource';
+import { TurboRequestsService } from 'core-app/core/turbo/turbo-requests.service';
@Injectable()
export class WorkPackageNotificationService extends HalResourceNotificationService {
constructor(
readonly injector:Injector,
readonly apiV3Service:ApiV3Service,
+ readonly turboRequests:TurboRequestsService,
) {
super(injector);
}
@@ -53,13 +55,11 @@ export class WorkPackageNotificationService extends HalResourceNotificationServi
protected showCustomError(errorResource:any, resource:WorkPackageResource):boolean {
if (errorResource.errorIdentifier === 'urn:openproject-org:api:v3:errors:UpdateConflict') {
- this.ToastService.addError({
- message: errorResource.message,
- type: 'error',
- link: {
- text: this.I18n.t('js.hal.error.update_conflict_refresh'),
- target: () => this.apiV3Service.work_packages.id(resource).refresh(),
- },
+ // currently we do not have a programmatic way to show the primer flash messages
+ // so we just do a request to the server to show it
+ // should be refactored once we have a programmatic way to show the primer flash messages!
+ void this.turboRequests.request('/work_packages/show_conflict_flash_message?scheme=danger', {
+ method: 'GET',
});
return true;
diff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.ts
index 23409bb62b5..16b6f0e9b61 100644
--- a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.ts
+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.ts
@@ -21,6 +21,7 @@ export default class IndexController extends Controller {
workPackageId: Number,
notificationCenterPathName: String,
lastServerTimestamp: String,
+ showConflictFlashMessageUrl: String,
};
static targets = ['journalsContainer', 'buttonRow', 'formRow', 'form', 'reactionButton'];
@@ -40,8 +41,9 @@ export default class IndexController extends Controller {
declare filterValue:string;
declare userIdValue:number;
declare workPackageIdValue:number;
- declare localStorageKey:string;
-
+ declare rescuedEditorDataKey:string;
+ declare latestKnownChangesetUpdatedAtKey:string;
+ declare showConflictFlashMessageUrlValue:string;
private handleWorkPackageUpdateBound:EventListener;
private handleVisibilityChangeBound:EventListener;
private rescueEditorContentBound:EventListener;
@@ -62,31 +64,15 @@ export default class IndexController extends Controller {
this.turboRequests = context.services.turboRequests;
this.apiV3Service = context.services.apiV3Service;
- this.setLocalStorageKey();
+ this.setLocalStorageKeys();
this.setupEventListeners();
this.handleInitialScroll();
- this.startPolling();
this.populateRescuedEditorContent();
this.markAsConnected();
+ this.safeUpdateWorkPackageFormsWithStateChecks(); // required if switching back to the activities tab from another tab
- // Towards using updateDisplayedWorkPackageAttributes here:
- //
- // this ideally only is triggered when switched back to the activities tab from e.g. the "Files" tab
- // in order to make sure that the state of the displayed work package attributes is aligned with the state of the refreshed journal entries
- //
- // this is necessary because the polling for updates (and related work package attribute updates) only happens when the activity tab is connected
- //
- // without any further checks, this update is currently triggered even after the very first rendering of the activity tab
- //
- // this is not ideal but I don't want to introduce another hacky "ui-state-check" for now
- this.safeUpdateDisplayedWorkPackageAttributes();
-
- // something like below could be used to check for the ui state in the disconnect method
- // in order to identify if the activity tab was connected at least once
- // and then call updateDisplayedWorkPackageAttributes accordingly after an "implicit" tab change:
- //
- // const workPackageContainer = document.getElementsByTagName('wp-full-view-entry')[0] as HTMLElement;
- // workPackageContainer.dataset.activityTabWasConnected = 'true';
+ this.setLatestKnownChangesetUpdatedAt();
+ this.startPolling();
}
disconnect() {
@@ -106,10 +92,11 @@ export default class IndexController extends Controller {
(this.element as HTMLElement).dataset.stimulusControllerConnected = 'false';
}
- private setLocalStorageKey() {
+ private setLocalStorageKeys() {
// scoped by user id in order to avoid data leakage when a user logs out and another user logs in on the same browser
// TODO: when a user logs out, the data should be removed anyways in order to avoid data leakage
- this.localStorageKey = `work-package-${this.workPackageIdValue}-rescued-editor-data-${this.userIdValue}`;
+ this.rescuedEditorDataKey = `work-package-${this.workPackageIdValue}-rescued-editor-data-${this.userIdValue}`;
+ this.latestKnownChangesetUpdatedAtKey = `work-package-${this.workPackageIdValue}-latest-known-changeset-updated-at-${this.userIdValue}`;
}
private setupEventListeners() {
@@ -137,6 +124,28 @@ export default class IndexController extends Controller {
}
}
+ private safeUpdateWorkPackageFormsWithStateChecks() {
+ const latestKnownChangesetIsOutdated = this.latestKnownChangesetOutdated();
+ const latestChangesetIsFromOtherUser = this.latestChangesetFromOtherUser();
+
+ if (latestKnownChangesetIsOutdated && latestChangesetIsFromOtherUser) {
+ this.safeUpdateWorkPackageForms();
+ }
+ }
+
+ private latestKnownChangesetOutdated():boolean {
+ const latestKnownChangesetUpdatedAt = this.getLatestKnownChangesetUpdatedAt();
+ const latestChangesetUpdatedAt = this.parseLatestChangesetUpdatedAtFromDom();
+
+ return !!(latestKnownChangesetUpdatedAt && latestChangesetUpdatedAt && (latestKnownChangesetUpdatedAt < latestChangesetUpdatedAt));
+ }
+
+ private latestChangesetFromOtherUser():boolean {
+ const latestChangesetUserId = this.parseLatestChangesetUserIdFromDom();
+
+ return !!(latestChangesetUserId && (latestChangesetUserId !== this.userIdValue));
+ }
+
private startPolling() {
if (this.intervallId) window.clearInterval(this.intervallId);
this.intervallId = this.pollForUpdates();
@@ -196,33 +205,72 @@ export default class IndexController extends Controller {
});
}
- private handleUpdateStreamsResponse(html:string, lastResponseHeaders:Headers, journalsContainerAtBottom:boolean) {
- // extract server timestamp from response headers in order to be in sync with the server
- this.setLastServerTimestampViaHeaders(lastResponseHeaders);
+ private handleUpdateStreamsResponse(html:string, headers:Headers, journalsContainerAtBottom:boolean) {
+ // the timeout is require in order to give the Turb.renderStream method enough time to render the new journals
+ // the methods below partially rely on the DOM to be updated
+ // a specific signal would be way better than a static timeout, but I couldn't find a suitable one
+ setTimeout(() => {
+ this.setLastServerTimestampViaHeaders(headers);
+ this.checkForAndHandleWorkPackageUpdate(html);
+ this.checkForNewNotifications(html);
+ this.performAutoScrolling(html, journalsContainerAtBottom);
+ this.setLatestKnownChangesetUpdatedAt();
+ }, 100);
+ }
- this.checkForAndHandleWorkPackageUpdate(html);
- this.checkForNewNotifications(html);
- this.performAutoScrolling(html, journalsContainerAtBottom);
+ private getLatestKnownChangesetUpdatedAt():Date | null {
+ const latestKnownChangesetUpdatedAt = localStorage.getItem(this.latestKnownChangesetUpdatedAtKey);
+ return latestKnownChangesetUpdatedAt ? new Date(latestKnownChangesetUpdatedAt) : null;
+ }
+
+ private setLatestKnownChangesetUpdatedAt() {
+ const latestChangesetUpdatedAt = this.parseLatestChangesetUpdatedAtFromDom();
+
+ if (latestChangesetUpdatedAt) {
+ localStorage.setItem(this.latestKnownChangesetUpdatedAtKey, latestChangesetUpdatedAt.toString());
+ }
+ }
+
+ private parseLatestChangesetUpdatedAtFromDom():Date | null {
+ const elements = this.element.querySelectorAll('[data-journal-with-changeset-updated-at]');
+
+ const dates = Array.from(elements)
+ .map((element) => element.getAttribute('data-journal-with-changeset-updated-at'))
+ .filter((dateStr):dateStr is string => dateStr !== null)
+ .map((dateStr) => new Date(parseInt(dateStr, 10) * 1000))
+ .filter((date) => !Number.isNaN(date.getTime())); // filter out invalid dates
+
+ if (dates.length === 0) return null;
+
+ // find the latest date
+ return new Date(Math.max(...dates.map((date) => date.getTime())));
+ }
+
+ private parseLatestChangesetUserIdFromDom():number | null {
+ const latestChangesetUpdatedAt = this.parseLatestChangesetUpdatedAtFromDom();
+ if (!latestChangesetUpdatedAt) return null;
+
+ const railsTimestamp = latestChangesetUpdatedAt.getTime() / 1000;
+ const userId = this.element
+ .querySelector(`[data-journal-with-changeset-updated-at="${railsTimestamp}"]`)
+ ?.getAttribute('data-journal-with-changeset-user-id');
+
+ return userId ? parseInt(userId, 10) : null;
}
private checkForAndHandleWorkPackageUpdate(html:string) {
if (html.includes('work-packages-activities-tab-journals-item-component-details--journal-detail-container')) {
- this.safeUpdateDisplayedWorkPackageAttributes();
+ if (this.latestChangesetFromOtherUser()) {
+ this.safeUpdateWorkPackageForms();
+ }
}
}
- private safeUpdateDisplayedWorkPackageAttributes() {
+ private safeUpdateWorkPackageForms() {
if (this.anyInlineEditActiveInWpSingleView()) {
- this.toastService.addWarning({
- message: this.i18n.t('js.hal.warning.potential_update_conflict'),
- type: 'warning',
- link: {
- text: this.i18n.t('js.hal.error.update_conflict_refresh'),
- target: () => this.updateDisplayedWorkPackageAttributes(),
- },
- });
+ this.showConflictFlashMessage();
} else {
- this.updateDisplayedWorkPackageAttributes();
+ this.updateWorkPackageForms();
}
}
@@ -240,7 +288,16 @@ export default class IndexController extends Controller {
return false;
}
- private updateDisplayedWorkPackageAttributes() {
+ private showConflictFlashMessage() {
+ // currently we do not have a programmatic way to show the primer flash messages
+ // so we just do a request to the server to show it
+ // should be refactored once we have a programmatic way to show the primer flash messages!
+ void this.turboRequests.request(`${this.showConflictFlashMessageUrlValue}?scheme=warning`, {
+ method: 'GET',
+ });
+ }
+
+ private updateWorkPackageForms() {
const wp = this.apiV3Service.work_packages.id(this.workPackageIdValue);
void wp.refresh();
}
@@ -254,17 +311,15 @@ export default class IndexController extends Controller {
if (!(html.includes('action="append"') || html.includes('action="prepend"') || html.includes('action="update"'))) {
return;
}
- // the timeout is require in order to give the Turb.renderStream method enough time to render the new journals
- setTimeout(() => {
- if (this.sortingValue === 'asc' && journalsContainerAtBottom) {
- // scroll to (new) bottom if sorting is ascending and journals container was already at bottom before a new activity was added
- if (this.isMobile()) {
- this.scrollInputContainerIntoView(300);
- } else {
- this.scrollJournalContainer(true, true);
- }
+
+ if (this.sortingValue === 'asc' && journalsContainerAtBottom) {
+ // scroll to (new) bottom if sorting is ascending and journals container was already at bottom before a new activity was added
+ if (this.isMobile()) {
+ this.scrollInputContainerIntoView(300);
+ } else {
+ this.scrollJournalContainer(true, true);
}
- }, 100);
+ }
}
private rescueEditorContent() {
@@ -272,16 +327,16 @@ export default class IndexController extends Controller {
if (ckEditorInstance) {
const data = ckEditorInstance.getData({ trim: false });
if (data.length > 0) {
- localStorage.setItem(this.localStorageKey, data);
+ localStorage.setItem(this.rescuedEditorDataKey, data);
}
}
}
private populateRescuedEditorContent() {
- const rescuedEditorContent = localStorage.getItem(this.localStorageKey);
+ const rescuedEditorContent = localStorage.getItem(this.rescuedEditorDataKey);
if (rescuedEditorContent) {
this.openEditorWithInitialData(rescuedEditorContent);
- localStorage.removeItem(this.localStorageKey);
+ localStorage.removeItem(this.rescuedEditorDataKey);
}
}
diff --git a/frontend/src/stimulus/controllers/flash.controller.ts b/frontend/src/stimulus/controllers/flash.controller.ts
index 61178e1ca0a..d09aad6d196 100644
--- a/frontend/src/stimulus/controllers/flash.controller.ts
+++ b/frontend/src/stimulus/controllers/flash.controller.ts
@@ -15,6 +15,10 @@ export default class FlashController extends ApplicationController {
declare readonly itemTargets:HTMLElement;
+ reloadPage() {
+ window.location.reload();
+ }
+
itemTargetConnected(element:HTMLElement) {
const autohide = element.dataset.autohide === 'true';
if (this.autohideValue && autohide) {
diff --git a/spec/features/activities/work_package/activities_spec.rb b/spec/features/activities/work_package/activities_spec.rb
index e5968834e57..4861e856c00 100644
--- a/spec/features/activities/work_package/activities_spec.rb
+++ b/spec/features/activities/work_package/activities_spec.rb
@@ -993,5 +993,209 @@ RSpec.describe "Work package activity", :js, :with_cuprite, with_flag: { primeri
# work package page should also show the updated attribute
wp_page.expect_attributes(subject: "Subject updated")
end
+
+ it "shows the updated work package attribute without reload after switching back to the activity tab", :aggregate_failures do
+ # wait for the latest comments to be loaded before proceeding!
+ activity_tab.expect_journal_notes(text: "First comment by member")
+ wp_page.expect_attributes(subject: work_package.subject)
+
+ # we need to wait a bit before triggering the update below
+ # otherwise the update is already picked up by the initial (async) workpackage attributes update called in the connect hook
+ # and we wouldn't test the polling based update below
+ sleep 2
+ wp_page.expect_attributes(subject: work_package.subject) # check if the initial update picked up the original subject
+
+ wp_page.switch_to_tab(tab: :relations)
+ # simulate another user is updating the work package subject
+ # this btw does behave very strangely in test env and will not assign the change to the specified user
+ WorkPackages::UpdateService.new(user: admin, model: work_package).call(subject: "Subject updated")
+
+ sleep 2 # wait some time to really check for a stale UI state
+
+ # work package page is stale as the activity tab is not active and thus no polling is done
+ wp_page.expect_attributes(subject: work_package.subject)
+
+ wp_page.switch_to_tab(tab: :activity)
+ wp_page.wait_for_activity_tab
+
+ # activity tab should show the updated attribute
+ activity_tab.expect_journal_changed_attribute(text: "Subject updated")
+
+ # work package page should now also show the updated attribute
+ wp_page.expect_attributes(subject: "Subject updated")
+
+ # as this happened in this case while development and needed to be fixed
+ # I add the following check to make sure this does not happen again
+ wp_page.expect_no_conflict_warning_banner
+ wp_page.expect_no_conflict_error_banner
+ end
+ end
+
+ describe "conflict handling" do
+ let(:work_package) { create(:work_package, project:, author: admin) }
+
+ # make sure that all following changes are not merged to the initial journal
+ let!(:first_comment_by_member) do
+ create(:work_package_journal, user: member, notes: "First comment by member", journable: work_package, version: 2)
+ end
+
+ before do
+ # set WORK_PACKAGES_ACTIVITIES_TAB_POLLING_INTERVAL_IN_MS to 1000
+ # to speed up the polling interval for test duration
+ ENV["WORK_PACKAGES_ACTIVITIES_TAB_POLLING_INTERVAL_IN_MS"] = "1000"
+ end
+
+ after do
+ ENV.delete("WORK_PACKAGES_ACTIVITIES_TAB_POLLING_INTERVAL_IN_MS")
+ end
+
+ it "raises a conflict warning when the work package is updated by another user while the current user is editing",
+ :aggregate_failures do
+ using_session(:admin) do
+ login_as(admin)
+
+ wp_page.visit!
+ wp_page.wait_for_activity_tab
+
+ wp_page.edit_field(:description).display_element.click
+ wp_page.edit_field(:description).set_value("Description updated but not saved yet")
+
+ wp_page.expect_any_active_inline_edit_field
+ end
+
+ using_session(:member) do
+ login_as(member)
+
+ wp_page.visit!
+ wp_page.wait_for_activity_tab
+
+ wp_page.edit_field(:description).display_element.click
+ wp_page.edit_field(:description).set_value("Description updated by member")
+ wp_page.edit_field(:description).save!
+
+ wp_page.expect_no_active_inline_edit_field
+ end
+
+ using_session(:admin) do
+ wp_page.expect_any_active_inline_edit_field # editor is still active
+
+ wp_page.expect_conflict_warning_banner # warning banner is shown as another user has updated the work package
+
+ wp_page.edit_field(:description).save! # user ignores the warning and saves the changes
+
+ wp_page.expect_no_conflict_warning_banner # warning banner is gone and substituted by the error banner
+ wp_page.expect_conflict_error_banner # error banner is shown as the server does not allow a conflict
+ end
+ end
+
+ it "does NOT raise a conflict warning when the work package has been only commented by another user while the current
+ user is editing",
+ :aggregate_failures do
+ using_session(:admin) do
+ login_as(admin)
+
+ wp_page.visit!
+ wp_page.wait_for_activity_tab
+
+ wp_page.edit_field(:description).display_element.click
+ wp_page.edit_field(:description).set_value("Description updated but not saved yet")
+
+ wp_page.expect_any_active_inline_edit_field
+ end
+
+ using_session(:member) do
+ login_as(member)
+
+ wp_page.visit!
+ wp_page.wait_for_activity_tab
+
+ activity_tab.add_comment(text: "Second comment by member")
+ end
+
+ using_session(:admin) do
+ wp_page.expect_any_active_inline_edit_field # editor is still active
+
+ wp_page.expect_no_conflict_warning_banner
+ wp_page.expect_no_conflict_error_banner
+ end
+ end
+
+ context "when the current user does not have the activity tab open the whole time" do
+ it "raises a conflict warning when the work package is updated by another user while the current user is editing",
+ :aggregate_failures do
+ using_session(:admin) do
+ login_as(admin)
+
+ wp_page.visit!
+ wp_page.wait_for_activity_tab
+ wp_page.switch_to_tab(tab: :relations) # navigate to another tab, the journal polling stops
+
+ wp_page.edit_field(:description).display_element.click
+ wp_page.edit_field(:description).set_value("Description updated but not saved yet")
+
+ wp_page.expect_any_active_inline_edit_field
+ end
+
+ using_session(:member) do
+ login_as(member)
+
+ wp_page.visit!
+ wp_page.wait_for_activity_tab
+
+ wp_page.edit_field(:description).display_element.click
+ wp_page.edit_field(:description).set_value("Description updated by member")
+ wp_page.edit_field(:description).save!
+
+ wp_page.expect_no_active_inline_edit_field
+ end
+
+ using_session(:admin) do
+ wp_page.expect_no_conflict_warning_banner
+ wp_page.expect_no_conflict_error_banner
+
+ wp_page.switch_to_tab(tab: :activity) # re-visit the activity tab, the journal polling starts again
+ wp_page.wait_for_activity_tab
+
+ wp_page.expect_any_active_inline_edit_field # editor is still active
+
+ # this works as expected but cannot be tested in test env, reason unknown
+ # sleep 1
+ # wp_page.expect_conflict_warning_banner # warning banner is shown as another user has updated the work package
+
+ wp_page.edit_field(:description).save! # user ignores the warning and saves the changes
+
+ wp_page.expect_no_conflict_warning_banner # warning banner is gone and substituted by the error banner
+ wp_page.expect_conflict_error_banner # error banner is shown as the server does not allow a conflict
+ end
+ end
+
+ it "does NOT raise a conflict warning when the work package is updated by the same user while the current user is editing",
+ :aggregate_failures do
+ using_session(:admin) do
+ login_as(admin)
+
+ wp_page.visit!
+ wp_page.wait_for_activity_tab
+ wp_page.switch_to_tab(tab: :relations) # navigate to another tab, the journal polling stops
+
+ wp_page.edit_field(:description).display_element.click
+ wp_page.edit_field(:description).set_value("Description updated and saved")
+ wp_page.edit_field(:description).save!
+
+ wp_page.expect_no_active_inline_edit_field
+
+ wp_page.edit_field(:description).display_element.click
+ wp_page.edit_field(:description).set_value("Description updated again but not saved yet by the same user")
+
+ wp_page.expect_any_active_inline_edit_field
+
+ wp_page.switch_to_tab(tab: :activity)
+ wp_page.wait_for_activity_tab
+
+ wp_page.expect_no_conflict_warning_banner
+ wp_page.expect_no_conflict_error_banner
+ end
+ end
+ end
end
end
diff --git a/spec/support/pages/work_packages/abstract_work_package.rb b/spec/support/pages/work_packages/abstract_work_package.rb
index 14d2ddf8ff9..bcf09426480 100644
--- a/spec/support/pages/work_packages/abstract_work_package.rb
+++ b/spec/support/pages/work_packages/abstract_work_package.rb
@@ -89,6 +89,14 @@ module Pages
end
end
+ def expect_any_active_inline_edit_field
+ expect(page).to have_css(".inline-edit--active-field")
+ end
+
+ def expect_no_active_inline_edit_field
+ expect(page).to have_no_css(".inline-edit--active-field")
+ end
+
def expect_hidden_field(attribute)
page.within(container) do
expect(page).to have_no_css(".inline-edit--display-field.#{attribute}")
@@ -332,6 +340,34 @@ module Pages
find('[data-test-selector="mark-notification-read-button"]').click
end
+ def expect_conflict_warning_banner
+ expect(page).to have_test_selector("op-primer-flash-message",
+ text: I18n.t("notice_locking_conflict_warning"),
+ visible: true) do |element|
+ expect(element["data-banner-scheme"]).to eq("warning")
+ end
+ end
+
+ def expect_conflict_error_banner
+ expect(page).to have_test_selector("op-primer-flash-message",
+ text: I18n.t("notice_locking_conflict_danger"),
+ visible: true) do |element|
+ expect(element["data-banner-scheme"]).to eq("danger")
+ end
+ end
+
+ def expect_no_conflict_warning_banner
+ expect(page).not_to have_test_selector("op-primer-flash-message",
+ text: I18n.t("notice_locking_conflict_warning"),
+ visible: true)
+ end
+
+ def expect_no_conflict_error_banner
+ expect(page).not_to have_test_selector("op-primer-flash-message",
+ text: I18n.t("notice_locking_conflict_danger"),
+ visible: true)
+ end
+
private
def create_page(_args)