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

Feature/journal aggregation on write (#9396)

ulferts2a015eeac310
diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rb
index 481697f9691..150f53d1304 100644
--- a/app/controllers/journals_controller.rb
+++ b/app/controllers/journals_controller.rb
@@ -61,22 +61,21 @@ class JournalsController < ApplicationController
end
def diff
- journal = Journal::AggregatedJournal.containing_journal(@journal)
field = params[:field].parameterize.underscore.to_sym
unless valid_diff?
return render_404
end
- unless journal.details[field].is_a?(Array)
+ unless @journal.details[field].is_a?(Array)
return render_400 message: I18n.t(:error_journal_attribute_not_present, attribute: field)
end
- from = journal.details[field][0]
- to = journal.details[field][1]
+ from = @journal.details[field][0]
+ to = @journal.details[field][1]
@diff = Redmine::Helpers::Diff.new(to, from)
- @journable = journal.journable
+ @journable = @journal.journable
respond_to do |format|
format.html
format.js do
diff --git a/app/controllers/wiki_controller.rb b/app/controllers/wiki_controller.rb
index 8ceed253714..03ffe95dec5 100644
--- a/app/controllers/wiki_controller.rb
+++ b/app/controllers/wiki_controller.rb
@@ -262,7 +262,7 @@ class WikiController < ApplicationController
# don't load text
@versions = @page
.content
- .versions
+ .journals
.select(:id, :user_id, :notes, :created_at, :version)
.order(Arel.sql('version DESC'))
.page(page_param)
diff --git a/app/models/activities/base_activity_provider.rb b/app/models/activities/base_activity_provider.rb
index 0341faf3096..7d14ccf49a0 100644
--- a/app/models/activities/base_activity_provider.rb
+++ b/app/models/activities/base_activity_provider.rb
@@ -63,23 +63,17 @@ class Activities::BaseActivityProvider
end
def self.activity_provider_for(options = {})
- options.assert_valid_keys(:type, :permission, :activities, :aggregated)
+ options.assert_valid_keys(:type, :permission, :activities)
self.activity_provider_options = {
type: name.underscore.pluralize,
activities: [:activity],
- aggregated: false,
permission: "view_#{name.underscore.pluralize}".to_sym
}.merge(options)
end
def find_events(user, from, to, options)
- query = if aggregated?
- aggregated_event_selection_query(user, from, to, options)
- else
- event_selection_query(user, from, to, options)
- end
-
+ query = event_selection_query(user, from, to, options)
query = apply_order(query)
query = apply_limit(query, options)
query = apply_event_projection(query)
@@ -140,7 +134,7 @@ class Activities::BaseActivityProvider
def event_selection_query(user, from, to, options)
query = journals_with_data_query
- query = extend_event_query(query) unless aggregated?
+ query = extend_event_query(query)
query = filter_for_event_datetime(query, from, to)
query = restrict_user(query, options)
restrict_projects(query, user, options)
@@ -153,18 +147,6 @@ class Activities::BaseActivityProvider
query.project(projection)
end
- # When aggregating, we add the query that actually fetches the journals,
- # restricted by from, to, user permission, etc. as a CTE. That way,
- # that query has only to be executed once inside the aggregated journal query which
- # considerably reduces execution time.
- def aggregated_event_selection_query(user, from, to, options)
- query = aggregated_journal_query
- query = add_event_selection_query_as_cte(query, user, from, to, options)
- query = join_activity_journals_table(query)
- query = extend_event_query(query)
- join_with_projects_table(query)
- end
-
def apply_limit(query, options)
if options[:limit]
query.take(options[:limit])
@@ -247,25 +229,8 @@ class Activities::BaseActivityProvider
query.where(projects_table[:id].in(Project.allowed_to(user, perm).select(:id).arel))
end
- def aggregated_journal_query
- # As AggregatedJournal wraps the provided sql statement inside brackets we
- # need to provide a fully valid statement and not only the alias string.
- Journal.aggregated_journal(sql: "SELECT * FROM #{aggregated_journals_alias}").arel
- end
-
- def add_event_selection_query_as_cte(query, user, from, to, options)
- cte_query = event_selection_query(user, from, to, options).project('journals.*')
- cte = Arel::Nodes::As.new(Arel::Table.new(aggregated_journals_alias), cte_query)
-
- query.with(cte)
- end
-
attr_accessor :activity
- def aggregated?
- activity_provider_options[:aggregated]
- end
-
def journals_with_data_query
join_activity_journals_table(journals_table)
.where(journals_table[:journable_type].eq(activitied_type.name))
@@ -273,7 +238,9 @@ class Activities::BaseActivityProvider
def join_activity_journals_table(query)
query
- .join(activity_journals_table).on(journals_table[:id].eq(activity_journals_table[:journal_id]))
+ .join(activity_journals_table)
+ .on(journals_table[:data_id].eq(activity_journals_table[:id])
+ .and(journals_table[:data_type]).eq(activitied_type.journal_class.name))
end
def journals_table
@@ -308,10 +275,6 @@ class Activities::BaseActivityProvider
I18n.t(event_type(event).underscore, scope: 'events')
end
- def aggregated_journals_alias
- :relevant_journals
- end
-
def url_helpers
@url_helpers ||= OpenProject::StaticRouting::StaticUrlHelpers.new
end
diff --git a/app/models/activities/work_package_activity_provider.rb b/app/models/activities/work_package_activity_provider.rb
index c5c530a7502..b6a1f4651d3 100644
--- a/app/models/activities/work_package_activity_provider.rb
+++ b/app/models/activities/work_package_activity_provider.rb
@@ -30,7 +30,6 @@
class Activities::WorkPackageActivityProvider < Activities::BaseActivityProvider
activity_provider_for type: 'work_packages',
- aggregated: true,
permission: :view_work_packages
def extend_event_query(query)
diff --git a/app/models/journal.rb b/app/models/journal.rb
index 23368eb9487..97ca05e7ed5 100644
--- a/app/models/journal.rb
+++ b/app/models/journal.rb
@@ -34,7 +34,6 @@ class Journal < ApplicationRecord
include ::JournalChanges
include ::JournalFormatter
include ::Acts::Journalized::FormatHooks
- include ::Journal::Scopes::AggregatedJournal
register_journal_formatter :diff, OpenProject::JournalFormatter::Diff
register_journal_formatter :attachment, OpenProject::JournalFormatter::Attachment
@@ -46,12 +45,11 @@ class Journal < ApplicationRecord
belongs_to :user
belongs_to :journable, polymorphic: true
+ belongs_to :data, polymorphic: true, dependent: :destroy
has_many :attachable_journals, class_name: 'Journal::AttachableJournal', dependent: :destroy
has_many :customizable_journals, class_name: 'Journal::CustomizableJournal', dependent: :destroy
- before_destroy :destroy_data
-
# Scopes to all journals excluding the initial journal - useful for change
# logs like the history on issue#show
scope :changing, -> { where(['version > 1']) }
@@ -99,10 +97,6 @@ class Journal < ApplicationRecord
details[prop].first if details.keys.include? prop
end
- def data
- @data ||= "Journal::#{journable_type}Journal".constantize.find_by(journal_id: id)
- end
-
def previous
predecessor
end
@@ -113,10 +107,6 @@ class Journal < ApplicationRecord
private
- def destroy_data
- data&.destroy
- end
-
def predecessor
@predecessor ||= self.class
.where(journable_type: journable_type, journable_id: journable_id)
diff --git a/app/models/journal/aggregated_journal.rb b/app/models/journal/aggregated_journal.rb
deleted file mode 100644
index 7fb5f794ddc..00000000000
--- a/app/models/journal/aggregated_journal.rb
+++ /dev/null
@@ -1,285 +0,0 @@
-#-- encoding: UTF-8
-
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2021 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 docs/COPYRIGHT.rdoc for more details.
-#++
-
-# Similar to regular Journals, but under the following circumstances a set of individual journals is aggregated to
-# a single logical journal:
-# * they are in temporal proximity
-# * they belong to the same resource
-# * they were created by the same user (i.e. the same user edited the journable)
-# * no other user has an own journal on the same object between the aggregated ones
-# When a user commented (added a note) twice within a short time, the first comment will
-# finish the aggregation, since we do not want to merge comments in any way.
-# The term "aggregation" means the following when applied to our journaling:
-# * ignore/hide old journal rows (since every journal row contains a full copy of the journaled
-# object, dropping intermediate rows will just increase the diff of the following journal)
-# * in case an older row had notes, take the notes from the older row, since they shall not
-# be dropped
-class Journal::AggregatedJournal
- class << self
- def with_version(pure_journal)
- wp_journals = aggregated_journals(journable: pure_journal.journable)
- wp_journals.detect { |journal| journal.version == pure_journal.version }
- end
-
- # Returns the aggregated journal that contains the specified (vanilla/pure) journal.
- def containing_journal(pure_journal)
- raw = Journal
- .aggregated_journal(journable: pure_journal.journable)
- .where("version >= ?", pure_journal.version)
- .first
-
- raw ? Journal::AggregatedJournal.new(raw) : nil
- end
-
- ##
- # The +journable+ parameter allows to filter for aggregated journals of a given journable.
- #
- # The +until_version+ parameter can be used in conjunction with the +journable+ parameter
- # to see the aggregated journals as if no versions were known after the specified version.
- def aggregated_journals(journable: nil, sql: nil, until_version: nil, includes: [])
- raw_journals = Journal
- .aggregated_journal(journable: journable, sql: sql, until_version: until_version)
- .order('version ASC')
-
- aggregated_journals = map_to_aggregated_journals(raw_journals)
- preload_associations(journable, aggregated_journals, includes)
-
- aggregated_journals
- end
-
- # Returns whether "notification-hiding" should be assumed for the given journal pair.
- # This leads to an aggregated journal effectively blocking notifications of an earlier journal,
- # because it "steals" the addition from its predecessor. See the specs section under
- # "mail suppressing aggregation" (for NotifyJournalCompletedJob) for more details
- def hides_notifications?(successor, predecessor)
- return false unless successor && predecessor
- return false if belong_to_different_groups?(predecessor, successor)
-
- # imaginary state in which the successor never existed
- # if this makes the predecessor disappear, the successor must have taken journals
- # from it (that now became part of the predecessor again).
- !Journal
- .aggregated_journal(journable: successor.journable, until_version: successor.version - 1)
- .where(version: predecessor.version)
- .exists?
- end
-
- private
-
- def map_to_aggregated_journals(raw_journals)
- predecessors = {}
- raw_journals.each do |journal|
- journable_key = [journal.journable_type, journal.journable_id]
- predecessors[journable_key] = [nil] unless predecessors[journable_key]
- predecessors[journable_key] << journal
- end
-
- raw_journals.map do |journal|
- journable_key = [journal.journable_type, journal.journable_id]
-
- Journal::AggregatedJournal.new(journal, predecessor: predecessors[journable_key].shift)
- end
- end
-
- def preload_associations(journable, aggregated_journals, includes)
- return unless includes.length > 1
-
- journal_ids = aggregated_journals.map(&:id)
-
- customizable_journals = if includes.include?(:customizable_journals)
- Journal::CustomizableJournal
- .where(journal_id: journal_ids)
- .all
- .group_by(&:journal_id)
- end
-
- attachable_journals = if includes.include?(:customizable_journals)
- Journal::AttachableJournal
- .where(journal_id: journal_ids)
- .all
- .group_by(&:journal_id)
- end
-
- data = if includes.include?(:data)
- "Journal::#{journable.class}Journal".constantize
- .where(journal_id: journal_ids)
- .all
- .group_by(&:journal_id)
- end
-
- aggregated_journals.each do |journal|
- if includes.include?(:customizable_journals)
- journal.set_preloaded_customizable_journals customizable_journals[journal.id]
- end
- if includes.include?(:attachable_journals)
- journal.set_preloaded_attachable_journals attachable_journals[journal.id]
- end
- if includes.include?(:data)
- journal.set_preloaded_data data[journal.id].first
- end
- if journable
- journal.set_preloaded_journable journable
- end
- end
- end
-
- def belong_to_different_groups?(predecessor, successor)
- timeout = Setting.journal_aggregation_time_minutes.to_i.minutes
-
- successor.journable_type != predecessor.journable_type ||
- successor.journable_id != predecessor.journable_id ||
- successor.user_id != predecessor.user_id ||
- (successor.created_at - predecessor.created_at) <= timeout
- end
- end
-
- include JournalChanges
- include JournalFormatter
- include ::Acts::Journalized::FormatHooks
-
- register_journal_formatter :diff, OpenProject::JournalFormatter::Diff
- register_journal_formatter :attachment, OpenProject::JournalFormatter::Attachment
- register_journal_formatter :custom_field, OpenProject::JournalFormatter::CustomField
-
- alias_method :details, :get_changes
-
- delegate :journable_type,
- :journable_id,
- :journable,
- :journable=,
- :user_id,
- :user,
- :notes,
- :notes?,
- :activity_type,
- :created_at,
- :id,
- :version,
- :attributes,
- :attachable_journals,
- :attachable_journals=,
- :customizable_journals,
- :customizable_journals=,
- :editable_by?,
- :notes_id,
- :notes_version,
- :project,
- :data,
- to: :journal
-
- # Initializes a new AggregatedJournal. Allows to explicitly set a predecessor, if it is already
- # known. Providing a predecessor is only to improve efficiency, it is not required.
- # In case the predecessor is not known, it will be lazily retrieved.
- def initialize(journal, predecessor: false)
- @journal = journal
-
- # explicitly checking false to allow passing nil as "no predecessor"
- # mind that we check @predecessor with defined? below, so don't assign to it in all cases!
- unless predecessor == false
- @predecessor = predecessor
- end
- end
-
- # returns an instance of this class that is reloaded from the database
- def reloaded
- self.class.containing_journal(journal)
- end
-
- def user
- @user ||= User.find(user_id)
- end
-
- def data=(data)
- @data = data
- end
-
- def predecessor
- unless defined? @predecessor
- raw_journal = Journal
- .aggregated_journal(journable: journable)
- .where("version < ?", version)
- .except(:order)
- .order(version: :desc)
- .first
-
- @predecessor = raw_journal ? Journal::AggregatedJournal.new(raw_journal) : nil
- end
-
- @predecessor
- end
-
- def successor
- unless defined? @successor
- raw_journal = Journal
- .aggregated_journal(journable: journable)
- .where("version > ?", version)
- .except(:order)
- .order(version: :asc)
- .first
-
- @successor = raw_journal ? Journal::AggregatedJournal.new(raw_journal) : nil
- end
-
- @successor
- end
-
- def set_preloaded_customizable_journals(loaded_journals)
- self.customizable_journals = loaded_journals if loaded_journals
- customizable_journals.proxy_association.loaded!
- end
-
- def set_preloaded_attachable_journals(loaded_journals)
- self.attachable_journals = loaded_journals if loaded_journals
- attachable_journals.proxy_association.loaded!
- end
-
- def set_preloaded_data(loaded_data)
- self.data = loaded_data
- end
-
- def set_preloaded_journable(loaded_journable)
- self.journable = loaded_journable
- journal.association(:journable).loaded!
- end
-
- def initial?
- predecessor.nil?
- end
-
- # If we where to delegate here, the wrapped journal would be compared to its predecessor which is
- # not necessarily the this aggreated journal's predecessor.
- def noop?
- (!notes || notes&.empty?) && get_changes.empty?
- end
-
- private
-
- attr_reader :journal
-end
diff --git a/app/models/journal/scopes/aggregated_journal.rb b/app/models/journal/scopes/aggregated_journal.rb
deleted file mode 100644
index 2529807c695..00000000000
--- a/app/models/journal/scopes/aggregated_journal.rb
+++ /dev/null
@@ -1,362 +0,0 @@
-#-- encoding: UTF-8
-
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2021 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 docs/COPYRIGHT.rdoc for more details.
-#++
-
-# Scope to fetch all fields necessary to populated AggregatedJournal collections.
-# See the AggregatedJournal model class for a description.
-module Journal::Scopes
- module AggregatedJournal
- extend ActiveSupport::Concern
-
- class_methods do
- def aggregated_journal(journable: nil, sql: nil, until_version: nil)
- journals_preselection = raw_journals_subselect(journable, sql, until_version)
-
- # We wrap the sql with a subselect so that outside of this class,
- # The fields native to journals (e.g. id, version) can be referenced, without
- # having to also use a CASE/COALESCE statement.
- from(select_sql(journals_preselection))
- .select("DISTINCT *")
- end
-
- private
-
- # The sql used to query the database for the aggregated journals.
- # The query makes use of 4 parts (which are selected from/joined):
- # * The minimum journal version that starts an aggregation group.
- # * The maximum journal version that ends an aggregation group.
- # * Journals with notes that are within the bounds of minimum version/maximum version.
- # * Journals with notes that are within the bounds of the before mentioned journal notes and the maximum journal version.
- #
- # The maximum version are those journals, whose successor:
- # * Where created by a different user
- # * Where created after the configured aggregation period had expired (always relative to the journal under consideration).
- #
- # The minimum version then is the maximum version of the group before - 1.
- #
- # e.g. a group of 10 sequential journals might break into the following groups
- #
- # Version 10 (User A, 6 minutes after 9)
- # Version 9 (User A, 2 minutes after 8)
- # Version 8 (User A, 4 minutes after 7)
- # Version 7 (User A, 1 minute after 6)
- # Version 6 (User A, 3 minutes after 5)
- # Version 5 (User A, 1 minute after 4)
- # Version 4 (User B, 1 minute after 3)
- # Version 3 (User B, 4 minutes after 2)
- # Version 2 (User A, 1 minute after 1)
- # Version 1 (User A)
- #
- # would have the following maximum journals if the aggregation period where 5 minutes:
- #
- # Version 10 (User A, 6 minutes after 9)
- # Version 9 (User A, 2 minutes after 8)
- # Version 4 (User B, 1 minute after 3)
- # Version 2 (User A, 1 minute after 1)
- #
- # The last journal (one without a successor) of a journable will obviously also always be a maximum journal.
- #
- # If the aggregation period where to be expanded to 7 minutes, the maximum journals would be slightly different:
- #
- # Version 10 (User A, 6 minutes after 9)
- # Version 4 (User B, 1 minute after 3)
- # Version 2 (User A, 1 minute after 1)
- #
- # As we do not store the aggregated journals, and rather calculate them on reading, the aggregated journals might be tuned
- # by a user.
- #
- # The minimum version in the example with the 5 minute aggregation period would then be calculated from the maximum version:
- #
- # Version 10
- # Version 5
- # Version 3
- # Version 1
- #
- # The first version will always be included.
- #
- # Without a journal with notes (the user commented on the journable) in between, the maximum journal is returned
- # as the representation of every aggregation group. This is possible as the journals (together with their data and their
- # customizable_journals/attachable_journals) represent the complete state of the journable at the given time.
- #
- # e.g. a group of 5 sequential journals without notes, belonging to the same user and created within the configured
- # time difference between one journal and its successor
- #
- # Version 9
- # Version 8
- # Version 7
- # Version 6
- # Version 5
- #
- # would only return the last journal, Version 9.
- #
- # In case the group has one journal with notes in it, the last journal is also returned. But as we also want the note
- # to be returned, we return the note as if it would belong to the maximum journal version. This explicitly means
- # that all journals of the same group that are after the notes journal are also returned.
- #
- # e.g. a group of 5 sequential journals with only one note, belonging to the same user and created within the configured
- # time difference between one journal and its successor
- #
- # Version 9
- # Version 8
- # Version 7
- # Version 6 (note)
- # Version 5
- #
- # would only return the last journal, Version 9, but would also return the note and the id of the journal the note
- # belongs to natively.
- #
- # But as we do not want to aggregate notes, the behaviour above can no longer work if there is more than one note in the
- # same group. In such a case, a group is cut into subsets. The journals returned will then only contain all the changes
- # up until a journal with notes. The only exception to this is the last journal note which might also contain changes
- # after it up to and including the maximum journal version of the group.
-
- # e.g. a group of 5 sequential journals with only one note, belonging to the same user and created within the configured
- # time difference between one journal and its successor
- #
- # Version 9
- # Version 8 (note)
- # Version 7
- # Version 6 (note)
- # Version 5
- #
- # would return the last journal, Version 9, but with the note of Version 8 and also a reference in the form of
- # note_id pointing to Version 8. It would also return Version 6, with its note and a reference in the form of note_id
- # this time pointing to the native journal, Version 6.
- #
- # The journals that are considered for aggregation can also be reduced by providing a subselect. Doing so, one
- # can e.g. consider only the journals created after a certain time.
- def select_sql(journals_preselection)
- <<~SQL
- (#{Journal
- .from(start_group_journals_select(journals_preselection))
- .joins(end_group_journals_join(journals_preselection))
- .joins(notes_in_group_join(journals_preselection))
- .joins(additional_notes_in_group_join(journals_preselection))
- .select(projection_list).to_sql}) journals
- SQL
- end
-
- def user_or_time_group_breaking_journals_subselect(journals_preselection)
- <<~SQL
- SELECT
- predecessor.*,
- row_number() OVER (ORDER BY predecessor.journable_type, predecessor.journable_id, predecessor.version ASC) #{group_number_alias}
- FROM #{journals_preselection} predecessor
- LEFT OUTER JOIN #{journals_preselection} successor
- ON predecessor.version + 1 = successor.version
- AND predecessor.journable_type = successor.journable_type
- AND predecessor.journable_id = successor.journable_id
- WHERE (predecessor.user_id != successor.user_id
- OR #{beyond_aggregation_time_condition})
- OR successor.id IS NULL
- SQL
- end
-
- def notes_journals_subselect(journals_preselection)
- <<~SQL
- (SELECT
- notes_journals.*
- FROM #{journals_preselection} notes_journals
- WHERE notes_journals.notes != '' AND notes_journals.notes IS NOT NULL)
- SQL
- end
-
- def start_group_journals_select(journals_preselection)
- "(#{user_or_time_group_breaking_journals_subselect(journals_preselection)}) #{start_group_journals_alias}"
- end
-
- def end_group_journals_join(journals_preselection)
- group_journals_join_condition = <<~SQL
- #{start_group_journals_alias}.#{group_number_alias} = #{end_group_journals_alias}.#{group_number_alias} - 1
- AND #{start_group_journals_alias}.journable_type = #{end_group_journals_alias}.journable_type
- AND #{start_group_journals_alias}.journable_id = #{end_group_journals_alias}.journable_id
- SQL
-
- end_group_journals = <<~SQL
- RIGHT OUTER JOIN
- (#{user_or_time_group_breaking_journals_subselect(journals_preselection)}) #{end_group_journals_alias}
- ON #{group_journals_join_condition}
- SQL
-
- Arel.sql(end_group_journals)
- end
-
- def notes_in_group_join(journals_preselection)
- # As we right join on the minimum journal version, the minimum might be empty. We thus have to coalesce in such
- # case as <= will not interpret NULL as 0.
- # This also works if we do not fetch the whole set of journals starting from the first journal but rather
- # start somewhere within the set. This might take place e.g. when fetching only the journals that are
- # created after a certain point in time which is done when displaying of the last month in the activity module.
- breaking_journals_notes_join_condition = <<~SQL
- COALESCE(#{start_group_journals_alias}.version, 0) + 1 <= #{notes_in_group_alias}.version
- AND #{end_group_journals_alias}.version >= #{notes_in_group_alias}.version
- AND #{end_group_journals_alias}.journable_type = #{notes_in_group_alias}.journable_type
- AND #{end_group_journals_alias}.journable_id = #{notes_in_group_alias}.journable_id
- SQL
-
- breaking_journals_notes = <<~SQL
- LEFT OUTER JOIN
- #{notes_journals_subselect(journals_preselection)} #{notes_in_group_alias}
- ON #{breaking_journals_notes_join_condition}
- SQL
-
- Arel.sql(breaking_journals_notes)
- end
-
- def additional_notes_in_group_join(journals_preselection)
- successor_journals_notes_join_condition = <<~SQL
- #{notes_in_group_alias}.version < successor_notes.version
- AND #{end_group_journals_alias}.version >= successor_notes.version
- AND #{end_group_journals_alias}.journable_type = successor_notes.journable_type
- AND #{end_group_journals_alias}.journable_id = successor_notes.journable_id
- SQL
-
- successor_journals_notes = <<~SQL
- LEFT OUTER JOIN
- #{notes_journals_subselect(journals_preselection)} successor_notes
- ON #{successor_journals_notes_join_condition}
- SQL
-
- Arel.sql(successor_journals_notes)
- end
-
- def projection_list
- projections = <<~SQL
- #{end_group_journals_alias}.journable_type,
- #{end_group_journals_alias}.journable_id,
- #{end_group_journals_alias}.user_id,
- #{end_group_journals_alias}.activity_type,
- #{notes_projection} notes,
- #{notes_id_projection} notes_id,
- #{notes_in_group_alias}.version notes_version,
- #{version_projection} AS version,
- #{created_at_projection} created_at,
- #{updated_at_projection} updated_at,
- #{id_projection} id
- SQL
-
- Arel.sql(projections)
- end
-
- def id_projection
- attribute_projection(:id)
- end
-
- def version_projection
- attribute_projection(:version)
- end
-
- def created_at_projection
- attribute_projection(:created_at)
- end
-
- def updated_at_projection
- attribute_projection(:updated_at)
- end
-
- def attribute_projection(attribute)
- <<~SQL
- CASE
- WHEN successor_notes.version IS NOT NULL THEN #{notes_in_group_alias}.#{attribute}
- ELSE #{end_group_journals_alias}.#{attribute} END
- SQL
- end
-
- def notes_id_projection
- <<~SQL
- COALESCE(#{notes_in_group_alias}.id, #{end_group_journals_alias}.id)
- SQL
- end
-
- def notes_projection
- <<~SQL
- COALESCE(#{notes_in_group_alias}.notes, '')
- SQL
- end
-
- def raw_journals_subselect(journable, sql, until_version)
- if sql
- raise 'until_version used together with sql' if until_version
-
- "(#{sql})"
- elsif journable
- limit = until_version ? "AND journals.version <= #{until_version}" : ''
-
- <<~SQL
- (
- SELECT * from journals
- WHERE journals.journable_id = #{journable.id}
- AND journals.journable_type = '#{journable.class.name}'
- #{limit}
- )
- SQL
- else
- where = until_version ? "WHERE journals.version <= #{until_version}" : ''
-
- <<~SQL
- (SELECT * from journals #{where})
- SQL
- end
- end
-
- # Returns a SQL condition that will determine whether two entries are too far apart (temporal)
- # to be considered for aggregation. This takes the current instance settings for temporal
- # proximity into account.
- def beyond_aggregation_time_condition
- aggregation_time_seconds = Setting.journal_aggregation_time_minutes.to_i.minutes
- if aggregation_time_seconds == 0
- # if aggregation is disabled, we consider everything to be beyond aggregation time
- # even if creation dates are exactly equal
- return '(true = true)'
- end
-
- difference = "(successor.created_at - predecessor.created_at)"
- threshold = "interval '#{aggregation_time_seconds} second'"
-
- "(#{difference} > #{threshold})"
- end
-
- def start_group_journals_alias
- "start_groups_journals"
- end
-
- def end_group_journals_alias
- "end_groups_journals"
- end
-
- def group_number_alias
- "group_number"
- end
-
- def notes_in_group_alias
- "notes_in_group_journals"
- end
- end
- end
-end
diff --git a/app/services/journals/create_service.rb b/app/services/journals/create_service.rb
index 703f5332a4f..4e8eefbbc93 100644
--- a/app/services/journals/create_service.rb
+++ b/app/services/journals/create_service.rb
@@ -20,18 +20,37 @@ module Journals
end
def call(notes: '')
- journal = create_journal(notes)
+ Journal.transaction do
+ journal = create_journal(notes)
- return ServiceResult.new success: true unless journal
+ return ServiceResult.new success: true unless journal
- reload_journals
- touch_journable(journal)
+ destroy_predecessor(journal)
- ServiceResult.new success: true, result: journal
+ journal
+
+ reload_journals
+ touch_journable(journal)
+
+ ServiceResult.new success: true, result: journal
+ end
end
private
+ def destroy_predecessor(journal)
+ predecessor = journal.previous
+
+ if aggregatable?(predecessor, journal)
+ predecessor.destroy
+ if predecessor.notes.present?
+ journal.update_columns(notes: predecessor.notes, version: predecessor.version)
+ else
+ journal.update_columns(version: predecessor.version)
+ end
+ end
+ end
+
def create_journal(notes)
Rails.logger.debug "Inserting new journal for #{journable_type} ##{journable.id}"
@@ -97,10 +116,10 @@ module Journals
#{select_max_journal_sql}
), changes AS (
#{select_changed_sql}
+ ), insert_data AS (
+ #{insert_data_sql(notes)}
), inserted_journal AS (
#{insert_journal_sql(notes)}
- ), insert_data AS (
- #{insert_data_sql}
), insert_attachable AS (
#{insert_attachable_sql}
), insert_customizable AS (
@@ -112,12 +131,6 @@ module Journals
end
def insert_journal_sql(notes)
- condition = if notes.blank?
- "WHERE EXISTS (SELECT * FROM changes)"
- else
- ""
- end
-
journal_sql = <<~SQL
INSERT INTO
journals (
@@ -128,7 +141,9 @@ module Journals
user_id,
notes,
created_at,
- updated_at
+ updated_at,
+ data_id,
+ data_type
)
SELECT
:journable_id,
@@ -138,9 +153,10 @@ module Journals
:user_id,
:notes,
#{journal_timestamp_sql(notes, ':created_at')},
- #{journal_timestamp_sql(notes, ':updated_at')}
- FROM max_journals
- #{condition}
+ #{journal_timestamp_sql(notes, ':updated_at')},
+ insert_data.id,
+ :data_type
+ FROM max_journals, insert_data
RETURNING *
SQL
@@ -151,24 +167,30 @@ module Journals
journable_type: journable_type,
user_id: user.id,
created_at: journable_timestamp,
- updated_at: journable_timestamp)
+ updated_at: journable_timestamp,
+ data_type: journable.class.journal_class.name)
end
- def insert_data_sql
+ def insert_data_sql(notes)
+ condition = if notes.blank?
+ "AND EXISTS (SELECT * FROM changes)"
+ else
+ ""
+ end
+
data_sql = <<~SQL
INSERT INTO
#{data_table_name} (
- journal_id,
#{data_sink_columns}
)
SELECT
- #{id_from_inserted_journal_sql},
#{data_source_columns}
FROM #{journable_table_name}
#{journable_data_sql_addition}
WHERE
- #{only_if_created_sql}
- AND #{journable_table_name}.id = :journable_id
+ #{journable_table_name}.id = :journable_id
+ #{condition}
+ RETURNING *
SQL
::OpenProject::SqlSanitization.sanitize(data_sql,
@@ -231,7 +253,8 @@ module Journals
:journable_id journable_id,
:journable_type journable_type,
COALESCE(journals.version, fallback.version) AS version,
- COALESCE(journals.id, 0) id
+ COALESCE(journals.id, 0) id,
+ COALESCE(journals.data_id, 0) data_id
FROM
journals
RIGHT OUTER JOIN
@@ -329,7 +352,7 @@ module Journals
JOIN
#{data_table_name}
ON
- #{data_table_name}.journal_id = max_journals.id) #{data_table_name}
+ #{data_table_name}.id = max_journals.data_id) #{data_table_name}
ON
#{journable_table_name}.id = #{data_table_name}.journable_id
WHERE
@@ -434,5 +457,13 @@ module Journals
timestamps = attributes.index_with { journal.created_at }
journable.update_columns(timestamps) if timestamps.any?
end
+
+ def aggregatable?(predecessor, journal)
+ predecessor.present? &&
+ Setting.journal_aggregation_time_minutes.to_i > 0 &&
+ predecessor.created_at >= journal.created_at - Setting.journal_aggregation_time_minutes.to_i.minutes &&
+ predecessor.user_id == journal.user_id &&
+ (predecessor.notes.empty? || journal.notes.empty?)
+ end
end
end
diff --git a/app/workers/mails/work_package_job.rb b/app/workers/mails/work_package_job.rb
index c364260f29b..00f2d578649 100644
--- a/app/workers/mails/work_package_job.rb
+++ b/app/workers/mails/work_package_job.rb
@@ -37,13 +37,7 @@ class Mails::WorkPackageJob < Mails::DeliverJob
end
def render_mail(recipient:, sender:)
- return nil unless raw_journal # abort, assuming that the underlying WP was deleted
-
- journal = Journal::AggregatedJournal.with_version(raw_journal)
-
- # The caller should have ensured that the journal can't outdate anymore
- # before queuing a notification
- raise 'aggregated journal got outdated' unless journal
+ return nil unless journal # abort, assuming that the underlying WP was deleted
if journal.initial?
UserMailer.work_package_added(recipient, journal, sender)
@@ -54,11 +48,11 @@ class Mails::WorkPackageJob < Mails::DeliverJob
private
- def raw_journal
- @raw_journal ||= Journal.find_by(id: @journal_id)
+ def journal
+ @journal ||= Journal.find_by(id: @journal_id)
end
def work_package
- @work_package ||= raw_journal.journable
+ @work_package ||= journal.journable
end
end
diff --git a/app/workers/notifications/journal_completed_job.rb b/app/workers/notifications/journal_completed_job.rb
index 45d78027736..6360ab7c101 100644
--- a/app/workers/notifications/journal_completed_job.rb
+++ b/app/workers/notifications/journal_completed_job.rb
@@ -32,62 +32,23 @@ class Notifications::JournalCompletedJob < ApplicationJob
queue_with_priority :notification
def perform(journal_id, send_mails)
- # This is caused by a DJ job running as ActiveJob
- @journal_id = journal_id
- @send_mails = send_mails
+ journal = Journal.find_by(id: journal_id)
- # if the WP has been deleted the unaggregated journal will have been deleted too
- # and our job here is done
- return unless raw_journal
-
- journal = find_aggregated_journal_for(raw_journal)
-
- # If we can't find the aggregated journal, it was superseded by a journal that aggregated ours.
- # In that case a job for the new journal will have been enqueued that is now responsible for
- # sending the notification. Our job here is done.
+ # If the WP has been deleted the journal will have been deleted, too.
+ # Or the journal might have been replaced
return unless journal
- # Send the notification on behalf of the predecessor in case it could not send it on its own
- notify_for_wp_predecessor(journal)
-
- notify_for_journal(journal)
+ notify_journal_complete(journal, send_mails)
end
private
- def notify_for_journal(journal)
- # Do not deliver notifications if a follow-up journal will already have sent a notification
- # on behalf of this job.
- return if Journal::AggregatedJournal.hides_notifications?(journal.successor, journal)
-
- notify_journal_complete(journal, @send_mails)
- end
-
- def notify_for_wp_predecessor(aggregated)
- return unless Journal::AggregatedJournal.hides_notifications?(aggregated, aggregated.predecessor)
-
- aggregated_predecessor = find_aggregated_journal_for(aggregated.predecessor)
- notify_journal_complete(aggregated_predecessor, @send_mails)
- end
-
- def find_aggregated_journal_for(raw_journal)
- Journal::AggregatedJournal.with_version(raw_journal)
- end
-
def notify_journal_complete(journal, send_mails)
OpenProject::Notifications.send(notification_event_type(journal),
journal: journal,
send_mail: send_mails)
end
- def raw_journal
- @raw_journal ||= Journal.find_by(id: @journal_id)
- end
-
- def work_package
- @work_package ||= raw_journal.journable
- end
-
def notification_event_type(journal)
case journal.journable_type
when WikiContent.name
diff --git a/db/migrate/20210615150558_aggregate_journals.rb b/db/migrate/20210615150558_aggregate_journals.rb
new file mode 100644
index 00000000000..46eccbfea53
--- /dev/null
+++ b/db/migrate/20210615150558_aggregate_journals.rb
@@ -0,0 +1,392 @@
+require_relative './20200924085508_cleanup_orphaned_journal_data'
+
+class AggregateJournals < ActiveRecord::Migration[6.1]
+ def up
+ [Attachment,
+ Changeset,
+ Message,
+ News,
+ WikiContent,
+ WorkPackage,
+ Budget,
+ TimeEntry,
+ Document,
+ Meeting,
+ MeetingContent].each do |klass|
+ say_with_time "Aggregating journals for #{klass}" do
+ aggregate_journals(klass)
+ end
+ end
+
+ # Now cleanup all orphaned attachable/customizable journals
+ CleanupOrphanedJournalData.up
+ end
+
+ # The change is irreversible (aggregated journals cannot be broken down) but down will not cause database inconsistencies.
+
+ def aggregate_journals(klass)
+ klass.in_batches(of: 20) do |instances|
+ # Instantiating is faster than calculating the aggregated journals multiple times.
+ aggregated_journals = aggregated_journals_of(klass, instances).to_a
+
+ aggregated_journals
+ .reject { |journal| journal.notes_id == journal.id }
+ .each do |mismatched_journal|
+ update_journal_notes(mismatched_journal)
+ end
+
+ remove_unnecessary_journals(klass, instances, aggregated_journals)
+ end
+ end
+
+ def aggregated_journals_of(klass, instances)
+ aggregated_journal(sql: Journal.where(journable_type: klass.name,
+ journable_id: instances.pluck(:id))
+ .to_sql)
+ end
+
+ def update_journal_notes(mismatched_journal)
+ sql = <<~SQL
+ UPDATE journals
+ SET notes = :notes
+ WHERE id = :id
+ SQL
+
+ suppress_messages do
+ execute ::OpenProject::SqlSanitization.sanitize(sql, notes: mismatched_journal.notes, id: mismatched_journal.id)
+ end
+ end
+
+ def remove_unnecessary_journals(klass, instances, aggregated_journals)
+ # Only delete the journals (without callbacks as it is faster).
+ # We remove the then orphaned attachable/customizable journals later.
+ Journal
+ .where(journable_type: klass.name, journable_id: instances.pluck(:id))
+ .where.not(id: aggregated_journals.map(&:id))
+ .delete_all
+ end
+
+ def aggregated_journal(journable: nil, sql: nil, until_version: nil)
+ journals_preselection = raw_journals_subselect(journable, sql, until_version)
+
+ # We wrap the sql with a subselect so that outside of this class,
+ # The fields native to journals (e.g. id, version) can be referenced, without
+ # having to also use a CASE/COALESCE statement.
+ Journal
+ .from(select_sql(journals_preselection))
+ .select("DISTINCT *")
+ end
+
+ private
+
+ # The sql used to query the database for the aggregated journals.
+ # The query makes use of 4 parts (which are selected from/joined):
+ # * The minimum journal version that starts an aggregation group.
+ # * The maximum journal version that ends an aggregation group.
+ # * Journals with notes that are within the bounds of minimum version/maximum version.
+ # * Journals with notes that are within the bounds of the before mentioned journal notes and the maximum journal version.
+ #
+ # The maximum version are those journals, whose successor:
+ # * Where created by a different user
+ # * Where created after the configured aggregation period had expired (always relative to the journal under consideration).
+ #
+ # The minimum version then is the maximum version of the group before - 1.
+ #
+ # e.g. a group of 10 sequential journals might break into the following groups
+ #
+ # Version 10 (User A, 6 minutes after 9)
+ # Version 9 (User A, 2 minutes after 8)
+ # Version 8 (User A, 4 minutes after 7)
+ # Version 7 (User A, 1 minute after 6)
+ # Version 6 (User A, 3 minutes after 5)
+ # Version 5 (User A, 1 minute after 4)
+ # Version 4 (User B, 1 minute after 3)
+ # Version 3 (User B, 4 minutes after 2)
+ # Version 2 (User A, 1 minute after 1)
+ # Version 1 (User A)
+ #
+ # would have the following maximum journals if the aggregation period where 5 minutes:
+ #
+ # Version 10 (User A, 6 minutes after 9)
+ # Version 9 (User A, 2 minutes after 8)
+ # Version 4 (User B, 1 minute after 3)
+ # Version 2 (User A, 1 minute after 1)
+ #
+ # The last journal (one without a successor) of a journable will obviously also always be a maximum journal.
+ #
+ # If the aggregation period where to be expanded to 7 minutes, the maximum journals would be slightly different:
+ #
+ # Version 10 (User A, 6 minutes after 9)
+ # Version 4 (User B, 1 minute after 3)
+ # Version 2 (User A, 1 minute after 1)
+ #
+ # As we do not store the aggregated journals, and rather calculate them on reading, the aggregated journals might be tuned
+ # by a user.
+ #
+ # The minimum version in the example with the 5 minute aggregation period would then be calculated from the maximum version:
+ #
+ # Version 10
+ # Version 5
+ # Version 3
+ # Version 1
+ #
+ # The first version will always be included.
+ #
+ # Without a journal with notes (the user commented on the journable) in between, the maximum journal is returned
+ # as the representation of every aggregation group. This is possible as the journals (together with their data and their
+ # customizable_journals/attachable_journals) represent the complete state of the journable at the given time.
+ #
+ # e.g. a group of 5 sequential journals without notes, belonging to the same user and created within the configured
+ # time difference between one journal and its successor
+ #
+ # Version 9
+ # Version 8
+ # Version 7
+ # Version 6
+ # Version 5
+ #
+ # would only return the last journal, Version 9.
+ #
+ # In case the group has one journal with notes in it, the last journal is also returned. But as we also want the note
+ # to be returned, we return the note as if it would belong to the maximum journal version. This explicitly means
+ # that all journals of the same group that are after the notes journal are also returned.
+ #
+ # e.g. a group of 5 sequential journals with only one note, belonging to the same user and created within the configured
+ # time difference between one journal and its successor
+ #
+ # Version 9
+ # Version 8
+ # Version 7
+ # Version 6 (note)
+ # Version 5
+ #
+ # would only return the last journal, Version 9, but would also return the note and the id of the journal the note
+ # belongs to natively.
+ #
+ # But as we do not want to aggregate notes, the behaviour above can no longer work if there is more than one note in the
+ # same group. In such a case, a group is cut into subsets. The journals returned will then only contain all the changes
+ # up until a journal with notes. The only exception to this is the last journal note which might also contain changes
+ # after it up to and including the maximum journal version of the group.
+
+ # e.g. a group of 5 sequential journals with only one note, belonging to the same user and created within the configured
+ # time difference between one journal and its successor
+ #
+ # Version 9
+ # Version 8 (note)
+ # Version 7
+ # Version 6 (note)
+ # Version 5
+ #
+ # would return the last journal, Version 9, but with the note of Version 8 and also a reference in the form of
+ # note_id pointing to Version 8. It would also return Version 6, with its note and a reference in the form of note_id
+ # this time pointing to the native journal, Version 6.
+ #
+ # The journals that are considered for aggregation can also be reduced by providing a subselect. Doing so, one
+ # can e.g. consider only the journals created after a certain time.
+ def select_sql(journals_preselection)
+ <<~SQL
+ (#{Journal
+ .from(start_group_journals_select(journals_preselection))
+ .joins(end_group_journals_join(journals_preselection))
+ .joins(notes_in_group_join(journals_preselection))
+ .joins(additional_notes_in_group_join(journals_preselection))
+ .select(projection_list).to_sql}) journals
+ SQL
+ end
+
+ def user_or_time_group_breaking_journals_subselect(journals_preselection)
+ <<~SQL
+ SELECT
+ predecessor.*,
+ row_number() OVER (ORDER BY predecessor.journable_type, predecessor.journable_id, predecessor.version ASC) #{group_number_alias}
+ FROM #{journals_preselection} predecessor
+ LEFT OUTER JOIN #{journals_preselection} successor
+ ON predecessor.version + 1 = successor.version
+ AND predecessor.journable_type = successor.journable_type
+ AND predecessor.journable_id = successor.journable_id
+ WHERE (predecessor.user_id != successor.user_id
+ OR #{beyond_aggregation_time_condition})
+ OR successor.id IS NULL
+ SQL
+ end
+
+ def notes_journals_subselect(journals_preselection)
+ <<~SQL
+ (SELECT
+ notes_journals.*
+ FROM #{journals_preselection} notes_journals
+ WHERE notes_journals.notes != '' AND notes_journals.notes IS NOT NULL)
+ SQL
+ end
+
+ def start_group_journals_select(journals_preselection)
+ "(#{user_or_time_group_breaking_journals_subselect(journals_preselection)}) #{start_group_journals_alias}"
+ end
+
+ def end_group_journals_join(journals_preselection)
+ group_journals_join_condition = <<~SQL
+ #{start_group_journals_alias}.#{group_number_alias} = #{end_group_journals_alias}.#{group_number_alias} - 1
+ AND #{start_group_journals_alias}.journable_type = #{end_group_journals_alias}.journable_type
+ AND #{start_group_journals_alias}.journable_id = #{end_group_journals_alias}.journable_id
+ SQL
+
+ end_group_journals = <<~SQL
+ RIGHT OUTER JOIN
+ (#{user_or_time_group_breaking_journals_subselect(journals_preselection)}) #{end_group_journals_alias}
+ ON #{group_journals_join_condition}
+ SQL
+
+ Arel.sql(end_group_journals)
+ end
+
+ def notes_in_group_join(journals_preselection)
+ # As we right join on the minimum journal version, the minimum might be empty. We thus have to coalesce in such
+ # case as <= will not interpret NULL as 0.
+ # This also works if we do not fetch the whole set of journals starting from the first journal but rather
+ # start somewhere within the set. This might take place e.g. when fetching only the journals that are
+ # created after a certain point in time which is done when displaying of the last month in the activity module.
+ breaking_journals_notes_join_condition = <<~SQL
+ COALESCE(#{start_group_journals_alias}.version, 0) + 1 <= #{notes_in_group_alias}.version
+ AND #{end_group_journals_alias}.version >= #{notes_in_group_alias}.version
+ AND #{end_group_journals_alias}.journable_type = #{notes_in_group_alias}.journable_type
+ AND #{end_group_journals_alias}.journable_id = #{notes_in_group_alias}.journable_id
+ SQL
+
+ breaking_journals_notes = <<~SQL
+ LEFT OUTER JOIN
+ #{notes_journals_subselect(journals_preselection)} #{notes_in_group_alias}
+ ON #{breaking_journals_notes_join_condition}
+ SQL
+
+ Arel.sql(breaking_journals_notes)
+ end
+
+ def additional_notes_in_group_join(journals_preselection)
+ successor_journals_notes_join_condition = <<~SQL
+ #{notes_in_group_alias}.version < successor_notes.version
+ AND #{end_group_journals_alias}.version >= successor_notes.version
+ AND #{end_group_journals_alias}.journable_type = successor_notes.journable_type
+ AND #{end_group_journals_alias}.journable_id = successor_notes.journable_id
+ SQL
+
+ successor_journals_notes = <<~SQL
+ LEFT OUTER JOIN
+ #{notes_journals_subselect(journals_preselection)} successor_notes
+ ON #{successor_journals_notes_join_condition}
+ SQL
+
+ Arel.sql(successor_journals_notes)
+ end
+
+ def projection_list
+ projections = <<~SQL
+ #{end_group_journals_alias}.journable_type,
+ #{end_group_journals_alias}.journable_id,
+ #{end_group_journals_alias}.user_id,
+ #{end_group_journals_alias}.activity_type,
+ #{notes_projection} notes,
+ #{notes_id_projection} notes_id,
+ #{notes_in_group_alias}.version notes_version,
+ #{version_projection} AS version,
+ #{created_at_projection} created_at,
+ #{updated_at_projection} updated_at,
+ #{id_projection} id
+ SQL
+
+ Arel.sql(projections)
+ end
+
+ def id_projection
+ attribute_projection(:id)
+ end
+
+ def version_projection
+ attribute_projection(:version)
+ end
+
+ def created_at_projection
+ attribute_projection(:created_at)
+ end
+
+ def updated_at_projection
+ attribute_projection(:updated_at)
+ end
+
+ def attribute_projection(attribute)
+ <<~SQL
+ CASE
+ WHEN successor_notes.version IS NOT NULL THEN #{notes_in_group_alias}.#{attribute}
+ ELSE #{end_group_journals_alias}.#{attribute} END
+ SQL
+ end
+
+ def notes_id_projection
+ <<~SQL
+ COALESCE(#{notes_in_group_alias}.id, #{end_group_journals_alias}.id)
+ SQL
+ end
+
+ def notes_projection
+ <<~SQL
+ COALESCE(#{notes_in_group_alias}.notes, '')
+ SQL
+ end
+
+ def raw_journals_subselect(journable, sql, until_version)
+ if sql
+ raise 'until_version used together with sql' if until_version
+
+ "(#{sql})"
+ elsif journable
+ limit = until_version ? "AND journals.version <= #{until_version}" : ''
+
+ <<~SQL
+ (
+ SELECT * from journals
+ WHERE journals.journable_id = #{journable.id}
+ AND journals.journable_type = '#{journable.class.name}'
+ #{limit}
+ )
+ SQL
+ else
+ where = until_version ? "WHERE journals.version <= #{until_version}" : ''
+
+ <<~SQL
+ (SELECT * from journals #{where})
+ SQL
+ end
+ end
+
+ # Returns a SQL condition that will determine whether two entries are too far apart (temporal)
+ # to be considered for aggregation. This takes the current instance settings for temporal
+ # proximity into account.
+ def beyond_aggregation_time_condition
+ aggregation_time_seconds = Setting.journal_aggregation_time_minutes.to_i.minutes
+ if aggregation_time_seconds == 0
+ # if aggregation is disabled, we consider everything to be beyond aggregation time
+ # even if creation dates are exactly equal
+ return '(true = true)'
+ end
+
+ difference = "(successor.created_at - predecessor.created_at)"
+ threshold = "interval '#{aggregation_time_seconds} second'"
+
+ "(#{difference} > #{threshold})"
+ end
+
+ def start_group_journals_alias
+ "start_groups_journals"
+ end
+
+ def end_group_journals_alias
+ "end_groups_journals"
+ end
+
+ def group_number_alias
+ "group_number"
+ end
+
+ def notes_in_group_alias
+ "notes_in_group_journals"
+ end
+end
diff --git a/db/migrate/20210616145324_polymorphic_journal_data.rb b/db/migrate/20210616145324_polymorphic_journal_data.rb
new file mode 100644
index 00000000000..2fd8532ebc5
--- /dev/null
+++ b/db/migrate/20210616145324_polymorphic_journal_data.rb
@@ -0,0 +1,51 @@
+class PolymorphicJournalData < ActiveRecord::Migration[6.1]
+ def up
+ add_reference :journals, :data, polymorphic: true, index: true
+
+ [::Journal::ChangesetJournal,
+ ::Journal::AttachmentJournal,
+ ::Journal::MessageJournal,
+ ::Journal::NewsJournal,
+ ::Journal::WikiContentJournal,
+ ::Journal::WorkPackageJournal,
+ ::Journal::BudgetJournal,
+ ::Journal::TimeEntryJournal,
+ ::Journal::DocumentJournal,
+ ::Journal::MeetingJournal,
+ ::Journal::MeetingContentJournal].each do |journal_data|
+ execute <<~SQL
+ UPDATE journals
+ SET data_id = data.id, data_type = '#{journal_data.name}'
+ FROM #{journal_data.table_name} data
+ WHERE data.journal_id = journals.id
+ SQL
+
+ remove_column journal_data.table_name, :journal_id
+ end
+ end
+
+ def down
+ [::Journal::ChangesetJournal,
+ ::Journal::AttachmentJournal,
+ ::Journal::MessageJournal,
+ ::Journal::NewsJournal,
+ ::Journal::WikiContentJournal,
+ ::Journal::WorkPackageJournal,
+ ::Journal::BudgetJournal,
+ ::Journal::TimeEntryJournal,
+ ::Journal::DocumentJournal,
+ ::Journal::MeetingJournal,
+ ::Journal::MeetingContentJournal].each do |journal_data|
+ add_column journal_data.table_name, :journal_id, :integer, index: true
+
+ execute <<~SQL
+ UPDATE #{journal_data.table_name} data
+ SET journal_id = journals.id
+ FROM journals
+ WHERE data.id = journals.data_id AND journals.data_type = '#{journal_data.name}'
+ SQL
+ end
+
+ remove_reference :journals, :data
+ end
+end
diff --git a/lib/api/v3/activities/activities_api.rb b/lib/api/v3/activities/activities_api.rb
index 8c756aa07c7..392bfed5804 100644
--- a/lib/api/v3/activities/activities_api.rb
+++ b/lib/api/v3/activities/activities_api.rb
@@ -43,10 +43,6 @@ module API
end
helpers do
- def aggregated_activity(activity)
- Journal::AggregatedJournal.containing_journal(activity)
- end
-
def save_activity(activity)
unless activity.save
fail ::API::Errors::ErrorBase.create_and_merge_errors(activity.errors)
@@ -60,7 +56,7 @@ module API
get &::API::V3::Utilities::Endpoints::Show.new(model: ::Journal,
api_name: 'Activity',
- instance_generator: ->(*) { aggregated_activity(@activity) })
+ instance_generator: ->(*) { @activity })
.mount
params do
@@ -73,7 +69,7 @@ module API
@activity.notes = declared_params[:comment]
save_activity(@activity)
- ActivityRepresenter.new(aggregated_activity(@activity), current_user: current_user)
+ ActivityRepresenter.new(@activity, current_user: current_user)
end
end
end
diff --git a/lib/api/v3/activities/activities_by_work_package_api.rb b/lib/api/v3/activities/activities_by_work_package_api.rb
index 863e59f327c..50c3619d3f3 100644
--- a/lib/api/v3/activities/activities_by_work_package_api.rb
+++ b/lib/api/v3/activities/activities_by_work_package_api.rb
@@ -33,12 +33,14 @@ module API
module Activities
class ActivitiesByWorkPackageAPI < ::API::OpenProjectAPI
resource :activities do
- helpers ::API::V3::Activities::ActivitiesSharedHelpers
-
get do
- @activities = get_aggregated_journals
self_link = api_v3_paths.work_package_activities @work_package.id
- Activities::ActivityCollectionRepresenter.new(@activities,
+ journals = @work_package.journals.includes(:data,
+ :customizable_journals,
+ :attachable_journals,
+ :bcf_comment)
+
+ Activities::ActivityCollectionRepresenter.new(journals,
self_link: self_link,
current_user: current_user)
end
@@ -51,11 +53,17 @@ module API
raise ::API::Errors::NotFound.new
end
- comment_on_work_package(
- @work_package,
- notify: !(params.has_key?(:notify) && params[:notify] == 'false'),
- comment: params[:comment][:raw]
- )
+ result = AddWorkPackageNoteService
+ .new(user: current_user,
+ work_package: @work_package)
+ .call(params[:comment][:raw],
+ send_notifications: !(params.has_key?(:notify) && params[:notify] == 'false'))
+
+ if result.success?
+ Activities::ActivityRepresenter.new(work_package.journals.last, current_user: current_user)
+ else
+ fail ::API::Errors::ErrorBase.create_and_merge_errors(result.errors)
+ end
end
end
end
diff --git a/lib/api/v3/activities/activities_shared_helpers.rb b/lib/api/v3/activities/activities_shared_helpers.rb
deleted file mode 100644
index f188b8d1dfe..00000000000
--- a/lib/api/v3/activities/activities_shared_helpers.rb
+++ /dev/null
@@ -1,60 +0,0 @@
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2021 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 docs/COPYRIGHT.rdoc for more details.
-#++
-
-module API
- module V3
- module Activities
- module ActivitiesSharedHelpers
- def comment_on_work_package(work_package, notify:, comment:)
- result = AddWorkPackageNoteService
- .new(user: current_user,
- work_package: work_package)
- .call(comment,
- send_notifications: notify)
-
- if result.success?
- journals = ::Journal::AggregatedJournal.aggregated_journals(journable: work_package)
- Activities::ActivityRepresenter.new(journals.last, current_user: current_user)
- else
- fail ::API::Errors::ErrorBase.create_and_merge_errors(result.errors)
- end
- end
-
- def get_aggregated_journals
- ::Journal::AggregatedJournal
- .aggregated_journals(journable: @work_package,
- includes: %i[
- customizable_journals
- attachable_journals
- data
- ])
- end
- end
- end
- end
-end
diff --git a/lib/api/v3/activities/activity_representer.rb b/lib/api/v3/activities/activity_representer.rb
index aca21c395ce..31b85d9ac13 100644
--- a/lib/api/v3/activities/activity_representer.rb
+++ b/lib/api/v3/activities/activity_representer.rb
@@ -39,7 +39,6 @@ module API
include API::Decorators::FormattableProperty
self_link path: :activity,
- id_attribute: :notes_id,
title_getter: ->(*) { nil }
link :workPackage do
@@ -59,13 +58,12 @@ module API
next unless current_user_allowed_to_edit?
{
- href: api_v3_paths.activity(represented.notes_id),
+ href: api_v3_paths.activity(represented.id),
method: :patch
}
end
property :id,
- getter: ->(*) { notes_id },
render_nil: true
formattable_property :notes,
diff --git a/lib/api/v3/utilities/resource_link_generator.rb b/lib/api/v3/utilities/resource_link_generator.rb
index fae572dc5c7..0f96b6cf350 100644
--- a/lib/api/v3/utilities/resource_link_generator.rb
+++ b/lib/api/v3/utilities/resource_link_generator.rb
@@ -55,7 +55,7 @@ module API
:priority
when AnonymousUser, DeletedUser, SystemUser
:user
- when Journal, Journal::AggregatedJournal
+ when Journal
:activity
when Changeset
:revision
diff --git a/modules/backlogs/lib/open_project/backlogs/burndown/series_raw_data.rb b/modules/backlogs/lib/open_project/backlogs/burndown/series_raw_data.rb
index 3b3daef4429..9cb33443ff6 100644
--- a/modules/backlogs/lib/open_project/backlogs/burndown/series_raw_data.rb
+++ b/modules/backlogs/lib/open_project/backlogs/burndown/series_raw_data.rb
@@ -91,7 +91,8 @@ module OpenProject::Backlogs::Burndown
FROM
work_package_journals
JOIN journals AS id_journals
- ON work_package_journals.journal_id = id_journals.id
+ ON work_package_journals.id = id_journals.data_id
+ AND id_journals.data_type = '#{Journal::WorkPackageJournal.name}'
AND #{version_query}
AND #{project_id_query}
AND #{type_id_query}
@@ -137,7 +138,8 @@ module OpenProject::Backlogs::Burndown
journals
JOIN
work_package_journals
- ON journals.id = work_package_journals.journal_id
+ ON work_package_journals.id = journals.data_id
+ AND journals.data_type = '#{Journal::WorkPackageJournal.name}'
AND #{version_query}
AND #{project_id_query}
AND #{type_id_query}
diff --git a/modules/bim/lib/open_project/bim/bcf_xml/issue_reader.rb b/modules/bim/lib/open_project/bim/bcf_xml/issue_reader.rb
index 90727378d25..5def85e3d9b 100644
--- a/modules/bim/lib/open_project/bim/bcf_xml/issue_reader.rb
+++ b/modules/bim/lib/open_project/bim/bcf_xml/issue_reader.rb
@@ -159,7 +159,7 @@ module OpenProject::Bim::BcfXml
journal.update_columns(created_at: created_at,
user_id: author.id)
- wp_journal = ::Journal::WorkPackageJournal.find_by(journal_id: journal.id)
+ wp_journal = journal.data
wp_journal.update_columns author_id: author.id
end
diff --git a/modules/bim/lib/open_project/bim/engine.rb b/modules/bim/lib/open_project/bim/engine.rb
index fa51df1745b..e47cf9ec516 100644
--- a/modules/bim/lib/open_project/bim/engine.rb
+++ b/modules/bim/lib/open_project/bim/engine.rb
@@ -103,8 +103,6 @@ module OpenProject::Bim
patch_with_namespace :OpenProject, :CustomStyles, :ColorThemes
patch_with_namespace :API, :V3, :Activities, :ActivityRepresenter
- patch_with_namespace :Journal, :AggregatedJournal
- patch_with_namespace :API, :V3, :Activities, :ActivitiesSharedHelpers
patch_with_namespace :API, :V3, :WorkPackages, :EagerLoading, :Checksum
patch_with_namespace :DemoData, :QueryBuilder
diff --git a/modules/bim/lib/open_project/bim/patches/activities_shared_helpers_patch.rb b/modules/bim/lib/open_project/bim/patches/activities_shared_helpers_patch.rb
deleted file mode 100644
index d522f2d80f7..00000000000
--- a/modules/bim/lib/open_project/bim/patches/activities_shared_helpers_patch.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2021 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 docs/COPYRIGHT.rdoc for more details.
-#++
-
-module OpenProject::Bim::Patches::ActivitiesSharedHelpersPatch
- def self.included(base) # :nodoc:
- base.prepend ModuleMethods
- end
-
- module ModuleMethods
- def get_aggregated_journals
- ::Journal::AggregatedJournal
- .aggregated_journals(journable: @work_package,
- includes: %i[
- customizable_journals
- attachable_journals
- data
- bcf_comment
- ])
- end
- end
-end
diff --git a/modules/bim/lib/open_project/bim/patches/aggregated_journal_patch.rb b/modules/bim/lib/open_project/bim/patches/aggregated_journal_patch.rb
deleted file mode 100644
index d0b52d3f927..00000000000
--- a/modules/bim/lib/open_project/bim/patches/aggregated_journal_patch.rb
+++ /dev/null
@@ -1,66 +0,0 @@
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2021 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 docs/COPYRIGHT.rdoc for more details.
-#++
-
-module OpenProject::Bim::Patches::AggregatedJournalPatch
- def self.included(base)
- base.class_exec do
- delegate :bcf_comment,
- :bcf_comment=,
- to: :journal
- end
-
- # base.singleton_class.prepend ClassMethods
- base.prepend InstanceMethods
- end
-
- module ClassMethods
- def preload_associations(journable, aggregated_journals, includes)
- aggregated_journals = super(journable, aggregated_journals, includes)
- if includes.include?(:bcf_comments)
- bcf_comments = if includes.include?(:bcf_comment)
- ::Bim::Bcf::Comment
- .where(journal_id: journal_ids)
- .all
- .group_by(&:journal_id)
- end
-
- aggregated_journals.each do |aggregated_journal|
- # Preload bcf_comment and its viewpoint.
- aggregated_journal.set_preloaded_bcf_comment(bcf_comments[aggregated_journal.id].first)
- end
- end
- end
- end
-
- module InstanceMethods
- def set_preloaded_bcf_comment(loaded_bcf_comment)
- journal.bcf_comment = loaded_bcf_comment
- journal.association(:bcf_comment).loaded!
- end
- end
-end
diff --git a/modules/bim/spec/api/v3/activities/activity_representer_spec.rb b/modules/bim/spec/api/v3/activities/activity_representer_spec.rb
index 1206cbd3d80..307ab1ee8a9 100644
--- a/modules/bim/spec/api/v3/activities/activity_representer_spec.rb
+++ b/modules/bim/spec/api/v3/activities/activity_representer_spec.rb
@@ -47,9 +47,6 @@ describe ::API::V3::Activities::ActivityRepresenter do
end
let(:journal) do
FactoryBot.build_stubbed(:work_package_journal).tap do |journal|
- allow(journal)
- .to receive(:notes_id)
- .and_return(journal.id)
allow(journal)
.to receive(:get_changes)
.and_return(changes)
diff --git a/spec/controllers/messages_controller_spec.rb b/spec/controllers/messages_controller_spec.rb
index 2c79aa1bbfd..5507c95de81 100644
--- a/spec/controllers/messages_controller_spec.rb
+++ b/spec/controllers/messages_controller_spec.rb
@@ -28,7 +28,7 @@
require 'spec_helper'
-describe MessagesController, type: :controller do
+describe MessagesController, type: :controller, with_settings: { journal_aggregation_time_minutes: 0 } do
let(:user) { FactoryBot.create(:user) }
let(:project) { FactoryBot.create(:project) }
let(:role) { FactoryBot.create(:role) }
diff --git a/spec/controllers/work_packages/bulk_controller_spec.rb b/spec/controllers/work_packages/bulk_controller_spec.rb
index 99fe99e7d49..7ca7a26efbc 100644
--- a/spec/controllers/work_packages/bulk_controller_spec.rb
+++ b/spec/controllers/work_packages/bulk_controller_spec.rb
@@ -28,7 +28,7 @@
require 'spec_helper'
-describe WorkPackages::BulkController, type: :controller do
+describe WorkPackages::BulkController, type: :controller, with_settings: { journal_aggregation_time_minutes: 0 } do
let(:user) { FactoryBot.create(:user) }
let(:user2) { FactoryBot.create(:user) }
let(:custom_field_value) { '125' }
diff --git a/spec/controllers/work_packages/moves_controller_spec.rb b/spec/controllers/work_packages/moves_controller_spec.rb
index f7fd424a402..dc7dc47ae85 100644
--- a/spec/controllers/work_packages/moves_controller_spec.rb
+++ b/spec/controllers/work_packages/moves_controller_spec.rb
@@ -28,7 +28,7 @@
require 'spec_helper'
-describe WorkPackages::MovesController, type: :controller do
+describe WorkPackages::MovesController, type: :controller, with_settings: { journal_aggregation_time_minutes: 0 } do
let(:user) { FactoryBot.create(:user) }
let(:role) do
FactoryBot.create :role,
diff --git a/spec/factories/journal_factory.rb b/spec/factories/journal_factory.rb
index 0d96f5fdd86..b2ea307bced 100644
--- a/spec/factories/journal_factory.rb
+++ b/spec/factories/journal_factory.rb
@@ -32,18 +32,10 @@ FactoryBot.define do
created_at { Time.now }
sequence(:version, 1)
- callback(:after_create) do |journal, evaluator|
- data = evaluator.data
- data.journal = journal
- data.save
- end
-
factory :work_package_journal, class: 'Journal' do
journable_type { 'WorkPackage' }
activity_type { 'work_packages' }
- transient do
- data { FactoryBot.build(:journal_work_package_journal) }
- end
+ data { FactoryBot.build(:journal_work_package_journal) }
callback(:after_stub) do |journal, options|
journal.journable ||= options.journable || FactoryBot.build_stubbed(:work_package)
@@ -53,19 +45,13 @@ FactoryBot.define do
factory :wiki_content_journal, class: 'Journal' do
journable_type { 'WikiContent' }
activity_type { 'wiki_edits' }
-
- transient do
- data { FactoryBot.build(:journal_wiki_content_journal) }
- end
+ data { FactoryBot.build(:journal_wiki_content_journal) }
end
factory :message_journal, class: 'Journal' do
journable_type { 'Message' }
activity_type { 'messages' }
-
- transient do
- data { FactoryBot.build(:journal_message_journal) }
- end
+ data { FactoryBot.build(:journal_message_journal) }
end
end
end
diff --git a/spec/features/activities/wiki_activity_spec.rb b/spec/features/activities/wiki_activity_spec.rb
index 02a02d3b4b3..80a0e3e2c18 100644
--- a/spec/features/activities/wiki_activity_spec.rb
+++ b/spec/features/activities/wiki_activity_spec.rb
@@ -55,6 +55,9 @@ feature 'Wiki activities' do
click_button 'Save'
expect(page).to have_text("Successful creation")
+ # We mock letting some time pass by altering the timestamps
+ Journal.last.update_columns(created_at: Time.now - 5.days, updated_at: Time.now - 5.days)
+
# alter the page
SeleniumHubWaiter.wait
click_link 'Edit'
diff --git a/spec/features/wiki/adding_editing_history_spec.rb b/spec/features/wiki/adding_editing_history_spec.rb
index ed0797d3aff..5add2539d14 100644
--- a/spec/features/wiki/adding_editing_history_spec.rb
+++ b/spec/features/wiki/adding_editing_history_spec.rb
@@ -28,7 +28,7 @@
require 'spec_helper'
-describe 'wiki pages', type: :feature, js: true do
+describe 'wiki pages', type: :feature, js: true, with_settings: { journal_aggregation_time_minutes: 0 } do
let(:project) do
FactoryBot.create(:project, enabled_module_names: [:news])
end
diff --git a/spec/features/work_packages/edit_work_package_spec.rb b/spec/features/work_packages/edit_work_package_spec.rb
index ceed2f6fa14..5bdcaeb398e 100644
--- a/spec/features/work_packages/edit_work_package_spec.rb
+++ b/spec/features/work_packages/edit_work_package_spec.rb
@@ -55,7 +55,7 @@ describe 'edit work package', js: true do
created_at: 5.days.ago.to_date.to_s(:db))
note_journal = work_package.journals.last
- note_journal.update(created_at: 5.days.ago.to_date.to_s)
+ note_journal.update_column(:created_at, 5.days.ago.to_date.to_s(:db))
work_package
end
diff --git a/spec/lib/api/v3/activities/activity_representer_spec.rb b/spec/lib/api/v3/activities/activity_representer_rendering_spec.rb
similarity index 61%
rename from spec/lib/api/v3/activities/activity_representer_spec.rb
rename to spec/lib/api/v3/activities/activity_representer_rendering_spec.rb
index 12a970660b2..803f6cc2185 100644
--- a/spec/lib/api/v3/activities/activity_representer_spec.rb
+++ b/spec/lib/api/v3/activities/activity_representer_rendering_spec.rb
@@ -28,7 +28,9 @@
require 'spec_helper'
-describe ::API::V3::Activities::ActivityRepresenter do
+describe ::API::V3::Activities::ActivityRepresenter, 'rendering' do
+ include ::API::V3::Utilities::PathHelper
+
let(:current_user) do
FactoryBot.build_stubbed(:user).tap do |u|
allow(u)
@@ -41,10 +43,7 @@ describe ::API::V3::Activities::ActivityRepresenter do
let(:work_package) { journal.journable }
let(:notes) { "My notes" }
let(:journal) do
- FactoryBot.build_stubbed(:work_package_journal, notes: notes).tap do |journal|
- allow(journal)
- .to receive(:notes_id)
- .and_return(journal.id)
+ FactoryBot.build_stubbed(:work_package_journal, notes: notes, user: other_user).tap do |journal|
allow(journal)
.to receive(:get_changes)
.and_return(changes)
@@ -58,37 +57,53 @@ describe ::API::V3::Activities::ActivityRepresenter do
login_as(current_user)
end
- context 'generation' do
- subject(:generated) { representer.to_json }
+ subject(:generated) { representer.to_json }
+ describe 'properties' do
describe 'type' do
- it { is_expected.to be_json_eql('Activity::Comment'.to_json).at_path('_type') }
+ context 'with notes' do
+ let(:notes) { 'Some notes' }
+
+ it_behaves_like 'property', :_type do
+ let(:value) { 'Activity::Comment' }
+ end
+ end
- context 'if notes are empty' do
+ context 'with empty notes' do
let(:notes) { '' }
- it { is_expected.to be_json_eql('Activity'.to_json).at_path('_type') }
+ it_behaves_like 'property', :_type do
+ let(:value) { 'Activity' }
+ end
end
- context 'if notes and changes are empty' do
+ context 'with empty notes and empty changes' do
let(:notes) { '' }
let(:changes) { {} }
- it { is_expected.to be_json_eql('Activity::Comment'.to_json).at_path('_type') }
+ it_behaves_like 'property', :_type do
+ let(:value) { 'Activity::Comment' }
+ end
end
end
- it { is_expected.to have_json_type(Object).at_path('_links') }
- it 'should link to self' do
- expect(subject).to have_json_path('_links/self/href')
+ describe 'id' do
+ it_behaves_like 'property', :id do
+ let(:value) { journal.id }
+ end
end
- it { is_expected.to have_json_path('id') }
- it { is_expected.to have_json_path('version') }
+ describe 'createdAt' do
+ it_behaves_like 'has UTC ISO 8601 date and time' do
+ let(:date) { journal.created_at }
+ let(:json_path) { 'createdAt' }
+ end
+ end
- it_behaves_like 'has UTC ISO 8601 date and time' do
- let(:date) { journal.created_at }
- let(:json_path) { 'createdAt' }
+ describe 'version' do
+ it_behaves_like 'property', :version do
+ let(:value) { journal.version }
+ end
end
describe 'comment' do
@@ -115,7 +130,7 @@ describe ::API::V3::Activities::ActivityRepresenter do
it { is_expected.to have_json_size(journal.details.count).at_path('details') }
- it 'should render all details as formattable' do
+ it 'renders all details as formattable' do
(0..journal.details.count - 1).each do |x|
is_expected.to be_json_eql('custom'.to_json).at_path("details/#{x}/format")
is_expected.to have_json_path("details/#{x}/raw")
@@ -123,33 +138,45 @@ describe ::API::V3::Activities::ActivityRepresenter do
end
end
end
+ end
- it 'should link to work package' do
- expect(subject).to have_json_path('_links/workPackage/href')
+ describe '_links' do
+ describe 'self' do
+ it_behaves_like 'has an untitled link' do
+ let(:link) { 'self' }
+ let(:href) { api_v3_paths.activity journal.id }
+ end
end
- it 'should link to user' do
- expect(subject).to have_json_path('_links/user/href')
+ describe 'workPackage' do
+ it_behaves_like 'has a titled link' do
+ let(:link) { 'workPackage' }
+ let(:href) { api_v3_paths.work_package work_package.id }
+ let(:title) { work_package.subject }
+ end
end
- it 'should link to update' do
- expect(subject).to have_json_path('_links/update/href')
+ describe 'user' do
+ it_behaves_like 'has an untitled link' do
+ let(:link) { 'user' }
+ let(:href) { api_v3_paths.user other_user.id }
+ end
end
- context 'for a non own journal' do
- context 'when having edit_work_package_notes' do
- it 'should link to update' do
- expect(subject).to have_json_path('_links/update/href')
- end
+ describe 'update' do
+ let(:link) { 'update' }
+ let(:href) { api_v3_paths.activity(journal.id) }
+
+ it_behaves_like 'has an untitled link'
+
+ context 'with a non own journal having edit_work_package_notes permission' do
+ it_behaves_like 'has an untitled link'
end
- context 'when only having edit_own_work_package_notes' do
+ context 'with a non own journal having only edit_own work_package_notes permission' do
let(:permissions) { %i(edit_own_work_package_notes) }
- it 'has no update link' do
- expect(subject)
- .not_to have_json_path('_links/update/href')
- end
+ it_behaves_like 'has no link'
end
end
end
diff --git a/spec/models/journal/aggregated_journal_spec.rb b/spec/models/journal/aggregated_journal_spec.rb
deleted file mode 100644
index 9c7547c723f..00000000000
--- a/spec/models/journal/aggregated_journal_spec.rb
+++ /dev/null
@@ -1,427 +0,0 @@
-#-- encoding: UTF-8
-
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2021 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 docs/COPYRIGHT.rdoc for more details.
-#++require 'rspec'
-
-require 'spec_helper'
-
-RSpec::Matchers.define :be_equivalent_to_journal do |expected|
- ignored_attributes = %i[notes_id notes_version]
-
- match do |actual|
- expected_attributes = get_normalized_attributes expected
- actual_attributes = get_normalized_attributes actual
-
- expected_attributes.except(*ignored_attributes) == actual_attributes.except(*ignored_attributes)
- end
-
- failure_message do |actual|
- expected_attributes = get_normalized_attributes expected
- actual_attributes = actual.attributes.symbolize_keys
- ["expected attributes: #{display_sorted_hash(expected_attributes.except(*ignored_attributes))}",
- "actual attributes: #{display_sorted_hash(actual_attributes.except(*ignored_attributes))}"]
- .join($/)
- end
-
- def get_normalized_attributes(journal)
- result = journal.attributes.symbolize_keys
- if result[:created_at]
- # µs are not stored in all DBMS
- result[:created_at] = result[:created_at].change(usec: 0)
- end
-
- result
- end
-
- def display_sorted_hash(hash)
- '{ ' + hash.sort.map { |k, v| "#{k.inspect}=>#{v.inspect}" }.join(', ') + ' }'
- end
-end
-
-describe Journal::AggregatedJournal, type: :model do
- let(:project) { FactoryBot.create(:project) }
- let(:work_package) do
- FactoryBot.build(:work_package, project: project)
- end
- let(:user1) { FactoryBot.create(:user) }
- let(:user2) { FactoryBot.create(:user) }
- let(:initial_author) { user1 }
-
- subject { described_class.aggregated_journals }
-
- before do
- login_as(initial_author)
- work_package.save!
- end
-
- it 'returns the one and only journal' do
- expect(subject.count).to eql 1
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- end
-
- it 'also indicates its ID via notes_id' do
- expect(subject.first.notes_id).to eql work_package.journals.first.id
- end
-
- it 'is the initial journal' do
- expect(subject.first.initial?).to be_truthy
- end
-
- it 'has no successor' do
- expect(subject.first.successor).to be_nil
- end
-
- it 'forwards project to the journable' do
- expect(subject.first.project).to eq(work_package.project)
- end
-
- context 'WP updated immediately after uncommented change' do
- let(:notes) { nil }
-
- before do
- changes = { status: FactoryBot.build(:status) }
- changes[:journal_notes] = notes if notes
-
- allow(User).to receive(:current).and_return(new_author)
-
- work_package.attributes = changes
- work_package.save!
- end
-
- context 'by author of last change' do
- let(:new_author) { initial_author }
-
- it 'returns a single aggregated journal' do
- expect(subject.count).to eql 1
- expect(subject.first).to be_equivalent_to_journal work_package.journals.second
- end
-
- it 'is the initial journal' do
- expect(subject.first.initial?).to be_truthy
- end
-
- it 'has no successor' do
- expect(subject.first.successor).to be_nil
- end
-
- it 'returns the single journal for both original journals' do
- expect(described_class.containing_journal(work_package.journals.first))
- .to be_equivalent_to_journal subject.first
-
- expect(described_class.containing_journal(work_package.journals.second))
- .to be_equivalent_to_journal subject.first
- end
-
- context 'with a comment' do
- let(:notes) { 'This is why I changed it.' }
-
- it 'returns a single aggregated journal' do
- expect(subject.count).to eql 1
- expect(subject.first).to be_equivalent_to_journal work_package.journals.second
- end
-
- context 'adding a second comment' do
- let(:notes) { 'Another comment, unrelated to the first one.' }
-
- before do
- work_package.add_journal(new_author, notes)
- work_package.save!
- end
-
- it 'returns two journals' do
- expect(subject.count).to eql 2
- expect(subject.first).to be_equivalent_to_journal work_package.journals.second
- expect(subject.second).to be_equivalent_to_journal work_package.journals.last
- end
-
- it 'has one initial journal and one non-initial journal' do
- expect(subject.first.initial?).to be_truthy
- expect(subject.second.initial?).to be_falsey
- end
-
- it 'has the first as predecessor of the second journal' do
- expect(subject.second.predecessor).to be_equivalent_to_journal subject.first
- end
-
- it 'has the second as successor of the first journal' do
- expect(subject.first.successor).to be_equivalent_to_journal subject.second
- end
-
- it 'returns the same aggregated journal for the first two originals' do
- expect(described_class.containing_journal(work_package.journals.first))
- .to be_equivalent_to_journal subject.first
-
- expect(described_class.containing_journal(work_package.journals.second))
- .to be_equivalent_to_journal subject.first
- end
-
- it 'returns a different aggregated journal for the last original' do
- expect(described_class.containing_journal(work_package.journals.last))
- .to be_equivalent_to_journal subject.second
- end
- end
-
- context 'adding another change without comment' do
- before do
- work_package.reload # need to update the lock_version, avoiding StaleObjectError
- changes = { subject: 'foo' }
-
- work_package.attributes = changes
- work_package.save!
- end
-
- it 'returns a single journal' do
- expect(subject.count).to eql 1
- end
-
- it 'combines the notes of the earlier journal with attributes of the later journal' do
- expected_journal = work_package.journals.last
- expected_journal.notes = work_package.journals.second.notes
-
- expect(subject.first).to be_equivalent_to_journal expected_journal
- end
-
- it 'indicates the ID of the earlier journal via notes_id' do
- expect(subject.first.notes_id).to eql work_package.journals.second.id
- end
-
- it 'is the initial journal' do
- expect(subject.first.initial?).to be_truthy
- end
-
- it 'has no predecessor' do
- expect(subject.first.predecessor).to be_nil
- end
-
- it 'has no successor' do
- expect(subject.first.successor).to be_nil
- end
- end
- end
- end
-
- context 'by a different author' do
- let(:new_author) { user2 }
-
- it 'returns both journals' do
- expect(subject.count).to eql 2
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- expect(subject.second).to be_equivalent_to_journal work_package.journals.second
- end
-
- it 'has the first as predecessor of the second journal' do
- expect(subject.second.predecessor).to be_equivalent_to_journal subject.first
- end
- end
- end
-
- context 'WP updated after aggregation timeout expired' do
- let(:delay) { (Setting.journal_aggregation_time_minutes.to_i + 1).minutes }
-
- before do
- work_package.status = FactoryBot.build(:status)
- work_package.save!
- second_journal = work_package.journals.second
- second_journal.update_column(:created_at, second_journal.created_at + delay)
- end
-
- it 'returns both journals' do
- expect(subject.count).to eql 2
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- expect(subject.second).to be_equivalent_to_journal work_package.journals.second
- end
- end
-
- context 'aggregation is disabled' do
- before do
- allow(Setting).to receive(:journal_aggregation_time_minutes).and_return(0)
- end
-
- context 'WP updated within milliseconds' do
- let(:delay) { 0.001.seconds }
-
- before do
- work_package.status = FactoryBot.build(:status)
- work_package.save!
- work_package.journals.second.created_at = work_package.journals.first.created_at + delay
- work_package.journals.second.save!
- end
-
- it 'returns both journals' do
- expect(subject.count).to eql 2
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- expect(subject.second).to be_equivalent_to_journal work_package.journals.second
- end
- end
- end
-
- context 'different WP updated immediately after change' do
- let(:other_wp) { FactoryBot.build(:work_package) }
- let(:delay) { 0.001.seconds }
-
- before do
- other_wp.save!
- # The delay is necessary to ensure the correct order of the journals.
- # Otherwise travis would create two journals with the exact same timestamp
- # resulting in a somewhere random ordering.
- other_wp.journals.first.created_at = work_package.journals.first.created_at + delay
- other_wp.journals.first.save!
- end
-
- it 'returns both journals' do
- expect(subject.count).to eql 2
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- expect(subject.second).to be_equivalent_to_journal other_wp.journals.first
- end
- end
-
- context 'passing a journable as parameter' do
- subject { described_class.aggregated_journals(journable: work_package) }
- let(:other_wp) { FactoryBot.build(:work_package) }
- let(:new_author) { initial_author }
-
- before do
- other_wp.save!
-
- changes = { subject: 'a new subject!' }
-
- work_package.attributes = changes
- work_package.save!
- end
-
- it 'only returns the journals for the requested work package' do
- expect(subject.count).to eq 1
- expect(subject.first).to be_equivalent_to_journal work_package.journals.last
- end
-
- context 'specifying a maximum version' do
- subject do
- described_class.aggregated_journals(journable: work_package, until_version: version)
- end
-
- context 'equal to the latest version' do
- let(:version) { work_package.journals.last.version }
-
- it 'returns the same as for no specified version' do
- expect(subject.count).to eq 1
- expect(subject.first).to be_equivalent_to_journal work_package.journals.last
- end
- end
-
- context 'equal to the first version' do
- let(:version) { work_package.journals.first.version }
-
- it 'does not aggregate the second journal' do
- expect(subject.count).to eq 1
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- end
- end
- end
- end
-
- context 'passing a filtering sql' do
- let!(:other_work_package) { FactoryBot.create(:work_package) }
- let(:sql) do
- <<~SQL
- SELECT journals.*
- FROM journals
- JOIN work_package_journals
- ON work_package_journals.journal_id = journals.id
- AND work_package_journals.project_id = #{project.id}
- SQL
- end
- subject { described_class.aggregated_journals(sql: sql) }
-
- it 'returns the journal of the work package in the project filtered for' do
- expect(subject.count).to eql 1
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- end
-
- context 'with a sql filtering out every journal' do
- let(:sql) do
- <<~SQL
- SELECT journals.*
- FROM journals
- JOIN work_package_journals
- ON work_package_journals.journal_id = journals.id
- AND work_package_journals.project_id = #{project.id}
- WHERE journals.created_at < '#{Date.yesterday}'
- SQL
- end
-
- it 'returns no journal' do
- expect(subject.count).to eql 0
- end
- end
-
- context 'with a sql filtering out the first journal and having 3 journals' do
- let(:sql) do
- <<~SQL
- SELECT journals.*
- FROM journals
- JOIN work_package_journals
- ON work_package_journals.journal_id = journals.id
- WHERE journals.version > 1
- SQL
- end
-
- context 'with the first of the remaining journals having a comment' do
- before do
- other_work_package.add_journal(initial_author, 'some other notes')
- other_work_package.save!
- work_package.add_journal(initial_author, 'some notes')
- work_package.save!
- work_package.subject = 'A new subject'
- work_package.save!
- end
-
- it 'returns one journal per work package' do
- expect(subject.count).to eql 2
- end
- end
- end
-
- context 'with an sql filtering for both projects' do
- let(:sql) do
- <<~SQL
- SELECT journals.*
- FROM journals
- JOIN work_package_journals
- ON work_package_journals.journal_id = journals.id
- AND work_package_journals.project_id IN (#{project.id}, #{other_work_package.project_id})
- SQL
- end
-
- it 'returns no journal' do
- expect(subject.count).to eql 2
- expect(subject.first).to be_equivalent_to_journal work_package.journals.first
- expect(subject.last).to be_equivalent_to_journal other_work_package.journals.first
- end
- end
- end
-end
diff --git a/spec/models/work_package/work_package_acts_as_journalized_spec.rb b/spec/models/work_package/work_package_acts_as_journalized_spec.rb
index c2db393ce14..3f687182629 100644
--- a/spec/models/work_package/work_package_acts_as_journalized_spec.rb
+++ b/spec/models/work_package/work_package_acts_as_journalized_spec.rb
@@ -42,7 +42,8 @@ describe WorkPackage, type: :model do
project_id: project.id,
type: type,
description: 'Description',
- priority: priority)
+ priority: priority,
+ status: status)
end
let(:current_user) { FactoryBot.create(:user) }
@@ -96,7 +97,7 @@ describe WorkPackage, type: :model do
it { expect(Journal.all.count).to eq(1) }
end
- context 'different newlines' do
+ context 'different newlines', with_settings: { journal_aggregation_time_minutes: 0 } do
let(:description) { "Description\n\nwith newlines\n\nembedded" }
let(:changed_description) { description.gsub("\n", "\r\n") }
let!(:work_package_1) do
@@ -153,7 +154,7 @@ describe WorkPackage, type: :model do
end
end
- context 'on work package change' do
+ context 'on work package change', with_settings: { journal_aggregation_time_minutes: 0 } do
let(:parent_work_package) do
FactoryBot.create(:work_package,
project_id: project.id,
@@ -270,7 +271,7 @@ describe WorkPackage, type: :model do
end
end
- context 'attachments' do
+ context 'attachments', with_settings: { journal_aggregation_time_minutes: 0 } do
let(:attachment) { FactoryBot.build :attachment }
let(:attachment_id) { "attachments_#{attachment.id}" }
@@ -312,7 +313,7 @@ describe WorkPackage, type: :model do
end
end
- context 'custom values' do
+ context 'custom values', with_settings: { journal_aggregation_time_minutes: 0 } do
let(:custom_field) { FactoryBot.create :work_package_custom_field }
let(:custom_value) do
FactoryBot.build :custom_value,
@@ -456,6 +457,147 @@ describe WorkPackage, type: :model do
.to eql(work_package.reload.updated_at)
end
end
+
+ context 'updated within aggregation time' do
+ subject(:journals) { work_package.journals }
+
+ let(:current_user) { user1 }
+
+ let(:notes) { nil }
+ let(:user1) { FactoryBot.create(:user) }
+ let(:user2) { FactoryBot.create(:user) }
+ let(:new_status) { FactoryBot.build(:status) }
+ let(:changes) do
+ {
+ status: new_status,
+ journal_notes: notes
+ }.compact
+ end
+
+ before do
+ login_as(new_author)
+
+ work_package.attributes = changes
+ work_package.save!
+ end
+
+ context 'by author of last change' do
+ let(:new_author) { user1 }
+
+ it 'leads to a single journal' do
+ expect(subject.count).to eql 1
+ end
+
+ it 'is the initial journal' do
+ expect(subject.first.initial?).to be_truthy
+ end
+
+ it 'contains the changes of both updates with the later overwriting the former' do
+ expect(subject.first.data.status_id)
+ .to eql changes[:status].id
+
+ expect(subject.first.data.type_id)
+ .to eql work_package.type_id
+ end
+
+ context 'with a comment' do
+ let(:notes) { 'This is why I changed it.' }
+
+ it 'leads to a single journal with the comment' do
+ expect(subject.count).to eql 1
+ expect(subject.first.notes)
+ .to eql notes
+ end
+
+ context 'when adding a second comment' do
+ let(:second_notes) { 'Another comment, unrelated to the first one.' }
+
+ before do
+ work_package.add_journal(new_author, second_notes)
+ work_package.save!
+ end
+
+ it 'returns two journals' do
+ expect(subject.count).to eql 2
+ expect(subject.first.notes).to eql notes
+ expect(subject.second.notes).to eql second_notes
+ end
+
+ it 'has one initial journal and one non-initial journal' do
+ expect(subject.first.initial?).to be_truthy
+ expect(subject.second.initial?).to be_falsey
+ end
+ end
+
+ context 'when adding another change without comment' do
+ before do
+ work_package.reload # need to update the lock_version, avoiding StaleObjectError
+ changes = { subject: 'foo' }
+
+ work_package.attributes = changes
+ work_package.save!
+ end
+
+ it 'leads to a single journal with the comment of the replaced journal and the state of the second' do
+ expect(subject.count).to eql 1
+
+ expect(subject.first.notes)
+ .to eql notes
+
+ expect(subject.first.data.subject)
+ .to eql 'foo'
+ end
+ end
+ end
+ end
+
+ context 'by a different author' do
+ let(:new_author) { user2 }
+
+ it 'leads to two journals' do
+ expect(subject.count).to eql 2
+ expect(subject.first.user)
+ .to eql current_user
+
+ expect(subject.second.user)
+ .to eql new_author
+
+ expect(subject.second.get_changes)
+ .to eql("status_id" => [status.id, new_status.id])
+ end
+ end
+ end
+
+ context 'updated after aggregation timeout expired', with_settings: { journal_aggregation_time_minutes: 1 } do
+ subject(:journals) { work_package.journals }
+
+ before do
+ work_package.journals.last.update_columns(created_at: Time.now - 2.minutes,
+ updated_at: Time.now - 2.minutes)
+
+ work_package.status = FactoryBot.build(:status)
+ work_package.save!
+ end
+
+ it 'creates a new journal' do
+ expect(journals.count).to eql 2
+ end
+ end
+
+ context 'updating with aggregation disabled', with_settings: { journal_aggregation_time_minutes: 0 } do
+ subject(:journals) { work_package.journals }
+
+ context 'WP updated within milliseconds' do
+ before do
+ work_package.status = FactoryBot.build(:status)
+ work_package.save!
+ end
+
+ it 'creates a new journal' do
+ expect(journals.count).to eql 2
+ end
+ end
+ end
end
context 'on #destroy' do
@@ -489,7 +631,7 @@ describe WorkPackage, type: :model do
end
it 'removes the journal data' do
- expect(Journal::WorkPackageJournal.find_by(journal_id: journal.id))
+ expect(Journal::WorkPackageJournal.find_by(id: journal.data_id))
.to be_nil
end
diff --git a/spec/requests/api/v3/activities_api_spec.rb b/spec/requests/api/v3/activities_api_spec.rb
index a4f4d583bfc..9fa46d7ce85 100644
--- a/spec/requests/api/v3/activities_api_spec.rb
+++ b/spec/requests/api/v3/activities_api_spec.rb
@@ -166,19 +166,6 @@ describe API::V3::Activities::ActivitiesAPI, type: :request, content_type: :json
it_behaves_like 'valid activity request', 'Activity::Comment'
end
- context 'for an aggregated journal when requesting by the notes_id (which is not the aggregated journal`s id)`' do
- let(:activity) do
- work_package.journals.first.tap do |journal|
- journal.update_column(:notes, comment)
-
- work_package.subject = 'A new subject'
- work_package.save!
- end
- end
-
- it_behaves_like 'valid activity request', 'Activity::Comment'
- end
-
context 'requesting nonexistent activity' do
let(:get_path) { api_v3_paths.activity 9999 }
diff --git a/spec/services/attachments/create_service_integration_spec.rb b/spec/services/attachments/create_service_integration_spec.rb
index 135f23d3a7f..d683efde03e 100644
--- a/spec/services/attachments/create_service_integration_spec.rb
+++ b/spec/services/attachments/create_service_integration_spec.rb
@@ -29,7 +29,7 @@
require 'spec_helper'
-describe Attachments::CreateService, 'integration' do
+describe Attachments::CreateService, 'integration', with_settings: { journal_aggregation_time_minutes: 0 } do
let(:user) { FactoryBot.create(:user) }
let(:description) { 'a fancy description' }
diff --git a/spec/services/attachments/delete_service_integration_spec.rb b/spec/services/attachments/delete_service_integration_spec.rb
index 394e6ca9637..13328e99492 100644
--- a/spec/services/attachments/delete_service_integration_spec.rb
+++ b/spec/services/attachments/delete_service_integration_spec.rb
@@ -29,7 +29,7 @@
require 'spec_helper'
-describe Attachments::DeleteService, 'integration' do
+describe Attachments::DeleteService, 'integration', with_settings: { journal_aggregation_time_minutes: 0 } do
subject(:call) { described_class.new(model: attachment, user: user).call }
let(:user) do
diff --git a/spec/services/notifications/journal_wp_mail_service_spec.rb b/spec/services/notifications/journal_wp_mail_service_spec.rb
index 60dea6a19d2..df32c7af927 100644
--- a/spec/services/notifications/journal_wp_mail_service_spec.rb
+++ b/spec/services/notifications/journal_wp_mail_service_spec.rb
@@ -29,7 +29,7 @@
#++
require 'spec_helper'
-describe Notifications::JournalWpMailService do
+describe Notifications::JournalWpMailService, with_settings: { journal_aggregation_time_minutes: 0 } do
let(:project) { FactoryBot.create(:project_with_types) }
let(:role) { FactoryBot.create(:role, permissions: [:view_work_packages]) }
let(:author) do
diff --git a/spec/services/principals/replace_references_service_call_integration_spec.rb b/spec/services/principals/replace_references_service_call_integration_spec.rb
index e3edeaa5671..4fe0bc86ee6 100644
--- a/spec/services/principals/replace_references_service_call_integration_spec.rb
+++ b/spec/services/principals/replace_references_service_call_integration_spec.rb
@@ -50,10 +50,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
context 'with a Journal' do
let!(:journal) do
FactoryBot.create(:work_package_journal,
- user_id: user_id,
- data: instance_double(Journal::WorkPackageJournal,
- 'journal=': nil,
- save: true))
+ user_id: user_id)
end
context 'with the replaced user' do
@@ -153,7 +150,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_attachment_journal,
:author_id do
let(:attributes) do
- { journal_id: 1 }
+ {}
end
end
end
@@ -202,8 +199,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_changeset_journal,
:user_id do
let(:attributes) do
- { journal_id: 1,
- repository_id: 1,
+ { repository_id: 1,
revision: 1,
committed_on: "date '2012-02-02'" }
end
@@ -223,8 +219,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_message_journal,
:author_id do
let(:attributes) do
- { journal_id: 1,
- forum_id: 1 }
+ { forum_id: 1 }
end
end
end
@@ -254,7 +249,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_meeting_content_journal,
:author_id do
let(:attributes) do
- { journal_id: 1 }
+ {}
end
end
end
@@ -279,7 +274,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_news_journal,
:author_id do
let(:attributes) do
- { journal_id: 1 }
+ {}
end
end
end
@@ -298,8 +293,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_wiki_content_journal,
:author_id do
let(:attributes) do
- { journal_id: 1,
- page_id: 1 }
+ { page_id: 1 }
end
end
end
@@ -317,7 +311,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_work_package_journal,
:assigned_to_id do
let(:attributes) do
- { journal_id: 1 }
+ {}
end
end
@@ -325,7 +319,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_work_package_journal,
:responsible_id do
let(:attributes) do
- { journal_id: 1 }
+ {}
end
end
end
@@ -349,8 +343,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_time_entry_journal,
:user_id do
let(:attributes) do
- { journal_id: 1,
- project_id: 1,
+ { project_id: 1,
hours: 5,
activity_id: 1,
spent_on: "date '2012-02-02'",
@@ -377,8 +370,7 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
:journal_budget_journal,
:author_id do
let(:attributes) do
- { journal_id: 1,
- project_id: 1,
+ { project_id: 1,
subject: "'abc'",
fixed_date: "date '2012-02-02'" }
end
@@ -402,7 +394,6 @@ describe Principals::ReplaceReferencesService, '#call', type: :model do
serialized: "'cde'" }
end
end
-
end
end
end
diff --git a/spec/workers/mails/work_package_job_spec.rb b/spec/workers/mails/work_package_job_spec.rb
index aee3005a36c..761723a563d 100644
--- a/spec/workers/mails/work_package_job_spec.rb
+++ b/spec/workers/mails/work_package_job_spec.rb
@@ -55,7 +55,7 @@ describe Mails::WorkPackageJob, type: :model do
it 'sends a mail' do
expect(UserMailer)
.to receive(:work_package_added)
- .with(recipient, an_instance_of(Journal::AggregatedJournal), author)
+ .with(recipient, an_instance_of(Journal), author)
subject
end
@@ -114,8 +114,8 @@ describe Mails::WorkPackageJob, type: :model do
subject
end
- it 'sends a mail for the aggregated journal' do
- expected = Journal::AggregatedJournal.aggregated_journals(journable: work_package).last
+ it 'sends a mail for the journal' do
+ expected = Journal.last
expect(UserMailer).to receive(:work_package_updated) do |_recipient, journal, _author|
expect(journal.id).to eq expected.id
expect(journal.notes_id).to eq expected.notes_id
diff --git a/spec/workers/notifications/journal_completed_job_integration_spec.rb b/spec/workers/notifications/journal_completed_job_integration_spec.rb
index 05d2e2a6d5c..5868e8b040f 100644
--- a/spec/workers/notifications/journal_completed_job_integration_spec.rb
+++ b/spec/workers/notifications/journal_completed_job_integration_spec.rb
@@ -66,7 +66,7 @@ describe Notifications::JournalCompletedJob, type: :model do
expect(OpenProject::Notifications)
.to receive(:send)
.with(OpenProject::Events::AGGREGATED_WORK_PACKAGE_JOURNAL_READY,
- journal: an_instance_of(Journal::AggregatedJournal),
+ journal: an_instance_of(Journal),
send_mail: send_mail)
subject
@@ -92,16 +92,6 @@ describe Notifications::JournalCompletedJob, type: :model do
it_behaves_like 'sends no notification'
end
- context 'outdated journal' do
- before do
- # make sure there is a later journal, that supersedes the original one
- work_package.subject = 'changed subject'
- work_package.save!
- end
-
- it_behaves_like 'sends no notification'
- end
-
describe 'journal creation' do
context 'work_package_created' do
before do
@@ -130,129 +120,6 @@ describe Notifications::JournalCompletedJob, type: :model do
it_behaves_like 'sends notification'
end
end
-
- describe 'mail suppressing aggregation' do
- # business logic of whether to send or not to send a mail is mainly driven by the presence
- # of an aggregated journal. However, there is an edge case that could lead to a notification
- # getting lost. Sadly this is very implementation specific, so I'll describe it:
- # Journal 1: comment
- # Journal 2: change (this can also be multiple journals)
- # Journal 3: comment
- #
- # The Job for the first journal will not send any mail, because Journal 2 supersedes it.
- # However, after adding Journal 3, the aggregation will look like (1), (2, 3). Therefore the
- # job for Journal 2 will not send a notification. Finally the job for Journal 3 will send a
- # notification, but only containing the changes of 2 and 3. The comment of journal 1 is lost.
- # Therefore two things have to happen:
- # - someone needs to send notifications for the hidden journal
- # (done by JournalNotificationMailer)
- # - in case a journal is hidden, its Job is not allowed to enqueue a mail for it
- # (because someone else will do it on behalf)
- # This is important since late exec of a Job might cause it to _not_ skip notifications
-
- before do
- change = { subject: 'new subject' }
- note = { journal_notes: 'a comment' }
-
- allow(WorkPackages::UpdateContract).to receive(:new).and_return(NoopContract.new)
- service = WorkPackages::UpdateService.new(user: author, model: work_package)
-
- expect(service.call(**note)).to be_success
- expect(service.call(**change)).to be_success
- expect(service.call(**note)).to be_success
- end
-
- let(:timeout) { Setting.journal_aggregation_time_minutes.to_i.minutes }
- let(:journal_1) { work_package.journals[1] }
- let(:journal_2) { work_package.journals[2] }
- let(:journal_3) { work_package.journals[3] }
-
- context 'all changes happen within the timeout of journal 1' do
- # The job for 1 will know, that Journal 3 took its addition.
- # The job for 2 will know, that it has become part of Journal 3.
- # -> no special behaviour required
-
- context 'for journal 1' do
- let(:journal) { journal_1 }
-
- it_behaves_like 'sends notification' # for journal 1
- end
-
- context 'for journal 2' do
- let(:journal) { journal_2 }
-
- it_behaves_like 'sends no notification'
- end
-
- context 'for journal 3' do
- let(:journal) { journal_3 }
-
- it_behaves_like 'sends notification' # for journals 2 and 3
- end
- end
-
- context 'journal 3 created after timeout of 1, but inside of timeout for 2' do
- # Job 1 will not send a mail because it does not know about journal 3
- # (thinking 2 will take its mail)
- # The mail of Job 1 is taken over by the JournalNotificationMailer for Journal 3
- # Even if Job 1 knew of journal 3 (due to late execution), it was not allowed to send a mail
- # (that would cause a duplicate mail delivery)
-
- before do
- journal_2.created_at = journal_1.created_at + (timeout / 2)
- journal_3.created_at = journal_1.created_at + timeout + 5.seconds
- journal_2.save!
- journal_3.save!
- end
-
- context 'for journal 1' do
- let(:journal) { journal_1 }
-
- it_behaves_like 'sends no notification'
- end
-
- context 'for journal 2' do
- let(:journal) { journal_2 }
-
- it_behaves_like 'sends no notification'
- end
-
- context 'for journal 3' do
- let(:journal) { journal_3 }
-
- it_behaves_like 'sends notification' # for journals 1, 2 and 3
- end
- end
-
- context 'journal 3 created after timeout of 1 and 2' do
- # This is a normal case again, ensuring nobody takes responsibility when not necessary.
-
- before do
- journal_2.created_at = journal_1.created_at + (timeout / 2)
- journal_3.created_at = journal_2.created_at + timeout + 5.seconds
- journal_2.save!
- journal_3.save!
- end
-
- context 'for journal 1' do
- let(:journal) { journal_1 }
-
- it_behaves_like 'sends no notification'
- end
-
- context 'for journal 2' do
- let(:journal) { journal_2 }
-
- it_behaves_like 'sends notification' # for journals 1 and 2
- end
-
- context 'for journal 3' do
- let(:journal) { journal_3 }
-
- it_behaves_like 'sends notification' # for journal 3
- end
- end
- end
end
context 'for wiki page content' do
@@ -275,7 +142,7 @@ describe Notifications::JournalCompletedJob, type: :model do
expect(OpenProject::Notifications)
.to receive(:send)
.with(OpenProject::Events::AGGREGATED_WIKI_JOURNAL_READY,
- journal: an_instance_of(Journal::AggregatedJournal),
+ journal: an_instance_of(Journal),
send_mail: send_mail)
subject