OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
rewrite acts as journalized to create journals in sql
ulferts983709db8983
diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rbindex 74c6224cf3b..9fae33c548a 100644--- a/app/controllers/journals_controller.rb+++ b/app/controllers/journals_controller.rb@@ -1,4 +1,5 @@#-- encoding: UTF-8+#-- copyright# OpenProject is an open source project management software.# Copyright (C) 2012-2020 the OpenProject GmbH@@ -101,7 +102,7 @@ class JournalsController < ApplicationControllerenddef valid_diff?- return false unless valid_field?(params[:field])- @journal.journable.class == WorkPackage+ valid_field?(params[:field]) &&+ @journal.journable.class == WorkPackageendenddiff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex cf0e80e0ff5..494707fc59c 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -79,18 +79,16 @@ class UsersController < ApplicationControllerevents = Activities::Fetcher.new(User.current, author: @user).events(nil, nil, limit: 10)@events_by_day = events.group_by { |e| e.event_datetime.to_date }- unless User.current.admin?- if !(@user.active? ||- @user.registered?) ||- (@user != User.current && @memberships.empty? && events.empty?)- render_404- return+ if !User.current.admin? &&+ (!(@user.active? ||+ @user.registered?) ||+ (@user != User.current && @memberships.empty? && events.empty?))+ render_404+ else+ respond_to do |format|+ format.html { render layout: 'no_menu' }endend-- respond_to do |format|- format.html { render layout: 'no_menu' }- endenddef newdiff --git a/app/models/activities/base_activity_provider.rb b/app/models/activities/base_activity_provider.rbindex 00b41db8ca7..70129b4e2af 100644--- a/app/models/activities/base_activity_provider.rb+++ b/app/models/activities/base_activity_provider.rb@@ -293,7 +293,7 @@ class Activities::BaseActivityProviderenddef activity_journals_table- @activity_journals_table ||= JournalManager.journal_class(activitied_type).arel_table+ @activity_journals_table ||= activitied_type.journal_class.arel_tableenddef activity_journal_projection_statement(column, name)diff --git a/app/models/journal.rb b/app/models/journal.rbindex d597bd6e8d7..87013a39a3c 100644--- a/app/models/journal.rb+++ b/app/models/journal.rb@@ -32,7 +32,7 @@ class Journal < ApplicationRecordinclude ::JournalChangesinclude ::JournalFormatter- include ::Redmine::Acts::Journalized::FormatHooks+ include ::Acts::Journalized::FormatHooksregister_journal_formatter :diff, OpenProject::JournalFormatter::Diffregister_journal_formatter :attachment, OpenProject::JournalFormatter::Attachment@@ -47,22 +47,10 @@ class Journal < ApplicationRecordhas_many :attachable_journals, class_name: 'Journal::AttachableJournal', dependent: :destroyhas_many :customizable_journals, class_name: 'Journal::CustomizableJournal', dependent: :destroy- after_create :save_data, if: :data- after_save :save_data, :touch_journable-# Scopes to all journals excluding the initial journal - useful for change# logs like the history on issue#showscope :changing, -> { where(['version > 1']) }- def changed_data=(changed_attributes)- attributes = changed_attributes-- if attributes.is_a? Hash and attributes.values.first.is_a? Array- attributes.each { |k, v| attributes[k] = v[1] }- end- data.update attributes- end-# TODO: check if this can be removed# Overrides the +user=+ method created by the polymorphic +belongs_to+ user association.# Based on the class of the object given, either the +user+ association columns or the@@ -109,9 +97,6 @@ class Journal < ApplicationRecordget_changesend- # TODO Evaluate whether this can be removed without disturbing any migrations- alias_method :changed_data, :details-def new_value_for(prop)details[prop].last if details.keys.include? propend@@ -124,10 +109,6 @@ class Journal < ApplicationRecord@data ||= "Journal::#{journable_type}Journal".constantize.find_by(journal_id: id)end- def data=(data)- @data = data- end-def previouspredecessorend@@ -138,23 +119,6 @@ class Journal < ApplicationRecordprivate- def save_data- data.journal_id = id if data.new_record?- data.save!- end-- def touch_journable- if journable && !journable.changed?- # Not using touch here on purpose,- # as to avoid changing lock versions on the journables for this change- time = journable.send(:current_time_from_proper_timezone)- attributes = journable.send(:timestamp_attributes_for_update_in_model)-- timestamps = Hash[attributes.map { |column| [column, time] }]- journable.update_columns(timestamps) if timestamps.any?- end- 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.rbindex 796363c9be9..53848899687 100644--- a/app/models/journal/aggregated_journal.rb+++ b/app/models/journal/aggregated_journal.rb@@ -174,7 +174,7 @@ class Journal::AggregatedJournalinclude JournalChangesinclude JournalFormatter- include Redmine::Acts::Journalized::FormatHooks+ include ::Acts::Journalized::FormatHooksregister_journal_formatter :diff, OpenProject::JournalFormatter::Diffregister_journal_formatter :attachment, OpenProject::JournalFormatter::Attachment@@ -204,7 +204,6 @@ class Journal::AggregatedJournal:notes_version,:project,:data,- :data=,to: :journal# Initializes a new AggregatedJournal. Allows to explicitly set a predecessor, if it is already@@ -229,6 +228,10 @@ class Journal::AggregatedJournal@user ||= User.find(user_id)end+ def data=(data)+ @data = data+ end+def predecessorunless defined? @predecessorraw_journal = Journal::Scopes::AggregatedJournal.fetch(journable: journable)diff --git a/app/models/journal/attachment_journal.rb b/app/models/journal/attachment_journal.rbindex c9d7209578a..1416bb82006 100644--- a/app/models/journal/attachment_journal.rb+++ b/app/models/journal/attachment_journal.rb@@ -1,4 +1,5 @@#-- encoding: UTF-8+#-- copyright# OpenProject is an open source project management software.# Copyright (C) 2012-2020 the OpenProject GmbHdiff --git a/app/models/journal/base_journal.rb b/app/models/journal/base_journal.rbindex 391c818c89d..f5c7260a3d4 100644--- a/app/models/journal/base_journal.rb+++ b/app/models/journal/base_journal.rb@@ -41,7 +41,7 @@ class Journal::BaseJournal < ApplicationRecordenddef self.excluded_attributes- [primary_key.to_sym, inheritance_column.to_sym, :journal_id, :lock_version, :created_at, :root_id, :lft, :rgt]+ [primary_key.to_sym, inheritance_column.to_sym, :journal_id]endprivate_class_method :excluded_attributesenddiff --git a/app/models/journal_manager.rb b/app/models/journal_manager.rbdeleted file mode 100644index 6c1e5340bc9..00000000000--- a/app/models/journal_manager.rb+++ /dev/null@@ -1,344 +0,0 @@-#-- encoding: UTF-8-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2020 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-2017 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.-#++--class JournalManager- class << self- def changes_on_association(current, predecessor, association, key, value)- merged_journals = merge_reference_journals_by_id(current, predecessor, key.to_s, value.to_s)-- changes = added_references(merged_journals)- .merge(removed_references(merged_journals))- .merge(changed_references(merged_journals))-- to_changes_format(changes, association.to_s)- end-- private-- def merge_reference_journals_by_id(new_journals, old_journals, id_key, value)- all_associated_journal_ids = new_journals.map { |j| j[id_key] } | old_journals.map { |j| j[id_key] }-- all_associated_journal_ids.each_with_object({}) do |id, result|- result[id] = [select_and_combine(old_journals, id, id_key, value),- select_and_combine(new_journals, id, id_key, value)]- end- end-- def added_references(merged_references)- merged_references- .select { |_, (old_value, new_value)| old_value.nil? && new_value.present? }- end-- def removed_references(merged_references)- merged_references- .select { |_, (old_value, new_value)| old_value.present? && new_value.nil? }- end-- def changed_references(merged_references)- merged_references- .select { |_, (old_value, new_value)| old_value.present? && new_value.present? && old_value.strip != new_value.strip }- end-- def to_changes_format(references, key)- references.each_with_object({}) do |(id, (old_value, new_value)), result|- result["#{key}_#{id}"] = [old_value, new_value]- end- end-- def journable_details(journable)- calculated_proc = journable.class.vestal_journals_options[:calculate]-- attributes = journable.attributes.symbolize_keys-- if calculated_proc- attributes- .merge!(journable.instance_exec(&calculated_proc))- end-- attributes- end-- def journal_class_name(type)- "#{base_class_name(type)}Journal"- end-- def base_class(type)- type.base_class- end-- def base_class_name(type)- base_class(type).name- end-- def create_association_data(journable, journal)- create_attachment_data journable, journal if journable.respond_to? :attachments- create_custom_field_data journable, journal if journable.respond_to? :custom_values- end-- def create_attachment_data(journable, journal)- journable.attachments.each do |a|- journal.attachable_journals.build attachment: a, filename: a.filename- end- end-- def create_custom_field_data(journable, journal)- journable.custom_values.group_by(&:custom_field).each do |custom_field, custom_values|- # Consider only custom values with non-blank values. Otherwise,- # non-existing custom values are different to custom values with an empty- # value.- # Mind that false.present? == false, but we don't consider false this being "blank"...- # This does not matter when we use stringly typed values (as in the database),- # but it matters when we use real types- valid_values = custom_values.select { |cv| cv.value.present? || cv.value == false }-- if custom_field.multi_value? && valid_values.any?- build_multi_value_custom_field_journal! journal, custom_field, valid_values- elsif valid_values.any?- build_custom_field_journal! journal, custom_field, valid_values.first- end- end- end-- def build_multi_value_custom_field_journal!(journal, custom_field, custom_values)- value = custom_values.map(&:value).join(",") # comma separated custom option IDs-- journal.customizable_journals.build custom_field_id: custom_field.id, value: value- end-- def build_custom_field_journal!(journal, custom_field, custom_value)- journal.customizable_journals.build custom_field_id: custom_field.id, value: custom_value.value- end-- def select_and_combine(journals, id, key, value)- selected_journals = journals.select { |j| j[key] == id }.map { |j| j[value] }-- if selected_journals.empty?- nil- else- selected_journals.join(',')- end- end- end-- def self.journalized?(obj)- not obj.nil? and obj.respond_to? :journals- end-- def self.changed?(journable)- if (journable.journals.loaded? ? journable.journals.size : journable.journals.count) > 0- changed = attributes_changed? journable- changed ||= association_changed? journable, 'attachable', :attachments, :id, :attachment_id, :filename- changed ||= association_changed? journable, 'customizable', :custom_values, :custom_field_id, :custom_field_id, :value-- changed- else- true- end- end-- def self.attributes_changed?(journable)- type = base_class(journable.class)- current = valid_journal_attributes type, journable.attributes- predecessor = journable.journals.last.data.journaled_attributes-- current = normalize_newlines(current)- predecessor = normalize_newlines(predecessor)-- # we generally ignore changes from blank to blank- predecessor- .any? { |k, v| current[k.to_s] != v && (v.present? || current[k.to_s].present?) }- end-- def self.association_changed?(journable, journal_association, association, id, key, value)- if journable.respond_to? association- journal_assoc_name = "#{journal_association}_journals"- current = journable.send(association).map { |a| { key.to_s => a.send(id), value.to_s => a.send(value) } }- predecessor = journable.journals.last.send(journal_assoc_name).map(&:attributes)-- current = remove_empty_associations(current, value.to_s)-- changes = JournalManager.changes_on_association(current, predecessor, association, key, value)-- !changes.empty?- else- false- end- end-- # associations have value attributes ('value' for custom values and 'filename'- # for attachments). This method ensures that blank value attributes are- # treated like non-existing associations. Thus, this prevents that- # non-existing associations (nil) are different to blank associations ("").- # This would lead to false change information, otherwise.- # We need to be careful though, because we want to accept false (and false.blank? == true)- def self.remove_empty_associations(associations, value)- associations.reject do |association|- association.has_key?(value) &&- association[value].blank? &&- association[value] != false- end- end-- def self.recreate_initial_journal(type, journal, changed_data)- if journal.data.nil?- journal.data = create_journal_data journal.id, type, changed_data.except(:id)- else- journal.changed_data = changed_data- journal.attachable_journals.delete_all- journal.customizable_journals.delete_all- end-- create_association_data journal.journable, journal-- journal.save!- journal.reload- end-- def self.add_journal!(journable, user = User.current, notes = '')- return unless journalized?(journable)-- # Ensure a version exists for this journable type- # since no version is changed here, in case of concurrency, one- # of the calls is allowed to fail- journable_type = base_class_name(journable.class)- ::JournalVersion.find_or_create_by(journable_type: journable_type, journable_id: journable.id)-- version = increment_version!(journable_type, journable.id)-- Rails.logger.debug "Inserting new journal for #{journable_type} ##{journable.id} @ #{version}"-- journal_attributes = { journable_id: journable.id,- journable_type: journal_class_name(journable.class),- version: version,- activity_type: journable.send(:activity_type),- details: journable_details(journable) }-- journal = create_journal journable, journal_attributes, user, notes-- # FIXME: this is required for the association to be correctly saved...- journable.journals.select(&:new_record?)-- journal.save!-- journal- end-- def self.increment_version!(journable_type, journable_id)- sql = <<~SQL- UPDATE #{JournalVersion.table_name}- SET version = version + 1- WHERE journable_type = :journable_type AND :journable_id = journable_id- RETURNING version- SQL-- sanitized = ::OpenProject::SqlSanitization.sanitize(sql, journable_type: journable_type, journable_id: journable_id)- ::JournalVersion- .connection- .execute(sanitized)- .first['version']- end-- def self.create_journal(journable, journal_attributes, user = User.current, notes = '')- type = base_class(journable.class)- extended_journal_attributes = journal_attributes- .merge(journable_type: type.to_s)- .merge(notes: notes)- .except(:details)- .except(:id)-- unless extended_journal_attributes.has_key? :user_id- extended_journal_attributes[:user_id] = user.id- end-- journal_attributes[:details] = normalize_newlines(journal_attributes[:details])-- journal = journable.journals.build extended_journal_attributes- journal.data = create_journal_data journal.id,- type,- valid_journal_attributes(type, journal_attributes[:details])-- create_association_data journable, journal-- journal- end-- def self.valid_journal_attributes(type, changed_data)- journal_class = journal_class type- journal_class_attributes = journal_class.columns.map(&:name)-- valid_journal_attributes = changed_data.select { |k, _v| journal_class_attributes.include?(k.to_s) }- valid_journal_attributes.except :id, :updated_at, :updated_on- end-- def self.create_journal_data(_journal_id, type, changed_data)- journal_class = journal_class type- new_data = Hash[changed_data.map { |k, v| [k, (v.is_a? Array) ? v.last : v] }]-- journal_class.new new_data- end-- def self.update_user_references(current_user_id, substitute_id)- foreign_keys = ['author_id', 'user_id', 'assigned_to_id', 'responsible_id']-- Journal::BaseJournal.subclasses.each do |klass|- foreign_keys.each do |foreign_key|- if klass.column_names.include? foreign_key- klass.where(foreign_key => current_user_id).update_all(foreign_key => substitute_id)- end- end- end- end-- def self.journal_class(type)- namespace = type.name.deconstantize-- if namespace == 'Journal'- type- else- "Journal::#{journal_class_name(type)}".constantize- end- end-- def self.journaled_class(journal_type)- namespace = journal_type.name.deconstantize-- if namespace == 'Journal'- class_name = journal_type.name.demodulize- class_name.gsub('Journal', '').constantize- else- journal_type- end- end-- def self.normalize_newlines(data)- data.each_with_object({}) do |e, h|- h[e[0]] = (e[1].is_a?(String) ? e[1].gsub(/\r\n/, "\n") : e[1])- end- end-enddiff --git a/app/models/user.rb b/app/models/user.rbindex f003f61e4ce..91009a955d3 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -795,11 +795,13 @@ class User < Principalklass.where(['author_id = ?', id]).update_all ['author_id = ?', substitute.id]end- [TimeEntry, Journal, ::Query].each do |klass|+ [TimeEntry, ::Query].each do |klass|klass.where(['user_id = ?', id]).update_all ['user_id = ?', substitute.id]end- JournalManager.update_user_references id, substitute.id+ Journals::UserReferenceUpdateService+ .new(self)+ .call(substitute)enddef delete_associated_private_queriesdiff --git a/app/models/work_package.rb b/app/models/work_package.rbindex 5bd34a5d71d..f8c67c340cb 100644--- a/app/models/work_package.rb+++ b/app/models/work_package.rb@@ -379,7 +379,7 @@ class WorkPackage < ApplicationRecordend# check if user is allowed to edit WorkPackage Journals.- # see Redmine::Acts::Journalized::Permissions#journal_editable_by+ # see Acts::Journalized::Permissions#journal_editable_bydef editable_by?(user)project = self.projectuser.allowed_to?(:edit_work_package_notes, project, global: project.present?) ||@@ -694,8 +694,8 @@ class WorkPackage < ApplicationRecorddef override_last_journal_notes_and_user_of!(other_work_package)journal = other_work_package.journals.last# Same user and notes- journal.user = current_journal.user- journal.notes = current_journal.notes+ journal.user = last_journal.user+ journal.notes = last_journal.notesjournal.saveenddiff --git a/app/models/work_package/journalized.rb b/app/models/work_package/journalized.rbindex b234c590b0d..66d9c1bd7b9 100644--- a/app/models/work_package/journalized.rb+++ b/app/models/work_package/journalized.rb@@ -32,7 +32,16 @@ module WorkPackage::Journalizedextend ActiveSupport::Concernincluded do- acts_as_journalized calculate: -> { { parent_id: parent && parent.id } }+ acts_as_journalized data_sql: ->(journable) do+ <<~SQL+ LEFT OUTER JOIN+ (+ #{Relation.hierarchy.direct.where(to_id: journable.id).limit(1).select('from_id parent_id, to_id').to_sql}+ ) parent_relation+ ON+ #{journable.class.table_name}.id = parent_relation.to_id+ SQL+ end# This one is here only to ease readingmodule JournalizedProcsdiff --git a/app/services/attachments/create_service.rb b/app/services/attachments/create_service.rbindex c4715c027fc..1775e144084 100644--- a/app/services/attachments/create_service.rb+++ b/app/services/attachments/create_service.rb@@ -42,7 +42,7 @@ class Attachments::CreateServicedef call(uploaded_file:, description:)if container.nil?create_attachment(uploaded_file, description)- elsif JournalManager.journalized?(container)+ elsif container.class.journaled?create_journalized(uploaded_file, description)elsecreate_unjournalized(uploaded_file, description)diff --git a/app/services/journals/create_service.rb b/app/services/journals/create_service.rbnew file mode 100644index 00000000000..1e1086c9c99--- /dev/null+++ b/app/services/journals/create_service.rb@@ -0,0 +1,433 @@+# Will create journals for a journable (e.g. WorkPackage and Meeting)+# As a journal is basically a copy of the current state of the database, consisting of the journable as well as its+# custom values and attachments, those entries are copied in the database.+# Copying and thereby creation only takes place if a change of the current state and the last journal is identified.+# Note, that the adequate creation of a journal which represents the state that is generated by a single user action depends on+# no other user/action altering the current state at the same time especially in a multi proccess/thread setup.+# Therefore, the whole update of a journable needs to be safeguarded by a mutex. In our implementation, we use+#+# OpenProject::Mutex.with_advisory_lock_transaction(journable)+#+# for this purpose.++module Journals+ class CreateService+ attr_accessor :journable, :user++ def initialize(journable, user)+ self.user = user+ self.journable = journable+ end++ def call(notes: '')+ journal = create_journal(notes)++ return ServiceResult.new success: true unless journal++ reload_journals+ touch_journable(journal)++ ServiceResult.new success: true, result: journal+ end++ private++ def create_journal(notes)+ Rails.logger.debug "Inserting new journal for #{journable_type} ##{journable.id}"++ create_sql = create_journal_sql(notes)++ # We need to ensure that the result is genuine. Otherwise,+ # calling the service repeatedly for the same journable+ # could e.g. return a (query cached) journal creation+ # that then e.g. leads to the later code thinking that a journal was+ # created.+ result = Journal.connection.uncached do+ ::Journal+ .connection+ .select_one(create_sql)+ end++ Journal.instantiate(result) if result+ end++ # The sql necessary for creating the journal inside the database.+ # It consists of a couple of parts that are kept as individual queries (as CTEs) but+ # are all executed within a single database call.+ #+ # The first CTEs (`max_journals`) responsibility is to fetch the latests journal and have that available for later queries+ # (i.e. when determining the latest state of the journable and when getting the current version number).+ #+ # The second CTE (`changes`) determines whether a change as occurred so that a new journal needs to be created. The next CTE,+ # that will insert new data, will only do so if the changes CTE returns an entry. The only exception to this check is that+ # if a note is provided, a journal will be created regardless of whether any changes are detected. To determine whether a+ # change is worthy of being journalized, the current and the latest journalized state are compared in three aspects:+ # * the journable's table columns are compared to the columns in the journable's journal data table+ # (e.g. work_package_journals for WorkPackages). Only columns that exist in the journable's journal data table are considered+ # (and some columns like the primary key `id` is ignored). Therefore, to add an attribute to be journalized, it needs to+ # be added to that table.+ # * the journable's attachments are compared to the attachable_journals entries being associated with the most recent journal.+ # * the journable's custom values are compared to the customizable_journals entries being associated with the most+ # recent journal.+ # When comparing text based values, newlines are normalized as otherwise users having a different OS might change a text value+ # without intending to.+ #+ # Only if a change has been identified (or if a note is present) is a journal inserted by the third CTE (`insert_journal`).+ # Its creation timestamp will be updated_at value of the journable as this is the logical creation time. If a note is present,+ # however, the current time is taken as it signifies an action in itself and there might not be a change at all. In such a+ # case, the journable will later on receive the creation date of the journal as its updated_at value. The update timestamp of+ # a journable and the creation date of its most recent journal should always be in sync.+ #+ # Both cases (having a note or a change) can at this point be identified by a journal having been created. Therefore, the+ # return value of that insert statement is further on used to identify whether the next statements (`insert_data`,+ # `insert_attachable` and `insert_customizable`) should actually insert data. It is additionally used as the values returned+ # by the overall SQL statement so that an AR instance can be instantiated with it.+ #+ # If a journal is created, all columns that also exist in the journable's data table are inserted as a new entry into+ # to the data table with a reference to the newly created journal. Again, newlines are normalized.+ #+ # If a journal is created, all entries in the attachments table associated to the journable are recreated as entries+ # in the attachable_journals table.+ #+ # If a journal is created, all entries in the custom_values table associated to the journable are recreated as entries+ # in the customizable_journals table. Again, newlines are normalized.+ def create_journal_sql(notes)+ <<~SQL+ WITH max_journals AS (+ #{select_max_journal_sql}+ ), changes AS (+ #{select_changed_sql}+ ), inserted_journal AS (+ #{insert_journal_sql(notes)}+ ), insert_data AS (+ #{insert_data_sql}+ ), insert_attachable AS (+ #{insert_attachable_sql}+ ), insert_customizable AS (+ #{insert_customizable_sql}+ )++ SELECT * from inserted_journal+ SQL+ end++ def insert_journal_sql(notes)+ condition = if notes.blank?+ "WHERE EXISTS (SELECT * FROM changes)"+ else+ ""+ end++ timestamp = if notes.blank? && journable_timestamp+ ':created_at'+ else+ 'now()'+ end++ journal_sql = <<~SQL+ INSERT INTO+ journals (+ journable_id,+ journable_type,+ version,+ activity_type,+ user_id,+ notes,+ created_at+ )+ SELECT+ :journable_id,+ :journable_type,+ COALESCE(max_journals.version, 0) + 1,+ :activity_type,+ :user_id,+ :notes,+ #{timestamp}+ FROM max_journals+ #{condition}+ RETURNING *+ SQL++ ::OpenProject::SqlSanitization.sanitize(journal_sql,+ notes: notes,+ journable_id: journable.id,+ activity_type: journable.activity_type,+ journable_type: journable_type,+ user_id: user.id,+ created_at: journable_timestamp)+ end++ def insert_data_sql+ 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+ SQL++ ::OpenProject::SqlSanitization.sanitize(data_sql,+ journable_id: journable.id)+ end++ def insert_attachable_sql+ attachable_sql = <<~SQL+ INSERT INTO+ attachable_journals (+ journal_id,+ attachment_id,+ filename+ )+ SELECT+ #{id_from_inserted_journal_sql},+ attachments.id,+ attachments.file+ FROM attachments+ WHERE+ #{only_if_created_sql}+ AND attachments.container_id = :journable_id+ AND attachments.container_type = :journable_class_name+ SQL++ ::OpenProject::SqlSanitization.sanitize(attachable_sql,+ journable_id: journable.id,+ journable_class_name: journable.class.name)+ end++ def insert_customizable_sql+ customizable_sql = <<~SQL+ INSERT INTO+ customizable_journals (+ journal_id,+ custom_field_id,+ value+ )+ SELECT+ #{id_from_inserted_journal_sql},+ custom_values.custom_field_id,+ #{normalize_newlines_sql('custom_values.value')}+ FROM custom_values+ WHERE+ #{only_if_created_sql}+ AND custom_values.customized_id = :journable_id+ AND custom_values.customized_type = :journable_class_name+ AND custom_values.value IS NOT NULL+ AND custom_values.value != ''+ SQL++ ::OpenProject::SqlSanitization.sanitize(customizable_sql,+ journable_id: journable.id,+ journable_class_name: journable.class.name)+ end++ def select_max_journal_sql+ max_journal_sql = <<~SQL+ SELECT+ :journable_id journable_id,+ :journable_type journable_type,+ COALESCE(journals.version, fallback.version) AS version,+ COALESCE(journals.id, 0) id+ FROM+ journals+ RIGHT OUTER JOIN+ (SELECT 0 AS version) fallback+ ON+ journals.journable_id = :journable_id+ AND journals.journable_type = :journable_type+ AND journals.version IN (SELECT MAX(version) FROM journals WHERE journable_id = :journable_id AND journable_type = :journable_type)+ SQL++ ::OpenProject::SqlSanitization.sanitize(max_journal_sql,+ journable_id: journable.id,+ journable_type: journable_type)+ end++ def select_changed_sql+ <<~SQL+ SELECT+ *+ FROM+ (#{data_changes_sql}) data_changes+ FULL JOIN+ (#{customizable_changes_sql}) customizable_changes+ ON+ customizable_changes.journable_id = data_changes.journable_id+ FULL JOIN+ (#{attachable_changes_sql}) attachable_changes+ ON+ attachable_changes.journable_id = data_changes.journable_id+ SQL+ end++ def attachable_changes_sql+ attachable_changes_sql = <<~SQL+ SELECT+ max_journals.journable_id+ FROM+ max_journals+ LEFT OUTER JOIN+ attachable_journals+ ON+ attachable_journals.journal_id = max_journals.id+ FULL JOIN+ (SELECT *+ FROM attachments+ WHERE attachments.container_id = :journable_id AND attachments.container_type = :container_type) attachments+ ON+ attachments.id = attachable_journals.attachment_id+ WHERE+ (attachments.id IS NULL AND attachable_journals.attachment_id IS NOT NULL)+ OR (attachable_journals.attachment_id IS NULL AND attachments.id IS NOT NULL)+ SQL++ ::OpenProject::SqlSanitization.sanitize(attachable_changes_sql,+ journable_id: journable.id,+ container_type: journable.class.name)+ end++ def customizable_changes_sql+ customizable_changes_sql = <<~SQL+ SELECT+ max_journals.journable_id+ FROM+ max_journals+ LEFT OUTER JOIN+ customizable_journals+ ON+ customizable_journals.journal_id = max_journals.id+ FULL JOIN+ (SELECT *+ FROM custom_values+ WHERE custom_values.customized_id = :journable_id AND custom_values.customized_type = :customized_type) custom_values+ ON+ custom_values.custom_field_id = customizable_journals.custom_field_id+ WHERE+ (custom_values.value IS NULL AND customizable_journals.value IS NOT NULL)+ OR (customizable_journals.value IS NULL AND custom_values.value IS NOT NULL AND custom_values.value != '')+ OR (#{normalize_newlines_sql('customizable_journals.value')} !=+ #{normalize_newlines_sql('custom_values.value')})+ SQL++ ::OpenProject::SqlSanitization.sanitize(customizable_changes_sql,+ customized_type: journable.class.name,+ journable_id: journable.id)+ end++ def data_changes_sql+ data_changes_sql = <<~SQL+ SELECT+ #{journable_table_name}.id journable_id+ FROM+ (SELECT * FROM #{journable_table_name} #{journable_data_sql_addition}) #{journable_table_name}+ LEFT JOIN+ (SELECT * FROM max_journals+ JOIN+ #{data_table_name}+ ON+ #{data_table_name}.journal_id = max_journals.id) #{data_table_name}+ ON+ #{journable_table_name}.id = #{data_table_name}.journable_id+ WHERE+ #{journable_table_name}.id = :journable_id AND (#{data_changes_condition_sql})+ SQL++ ::OpenProject::SqlSanitization.sanitize(data_changes_sql,+ journable_id: journable.id)+ end++ def only_if_created_sql+ "EXISTS (SELECT * from inserted_journal)"+ end++ def id_from_inserted_journal_sql+ "(SELECT id FROM inserted_journal)"+ end++ def data_changes_condition_sql+ data_table = data_table_name+ journable_table = journable_table_name++ data_changes = (journable.journaled_columns_names - text_column_names).map do |column_name|+ <<~SQL+ (#{journable_table}.#{column_name} != #{data_table}.#{column_name})+ OR (#{journable_table}.#{column_name} IS NULL AND #{data_table}.#{column_name} IS NOT NULL)+ OR (#{journable_table}.#{column_name} IS NOT NULL AND #{data_table}.#{column_name} IS NULL)+ SQL+ end++ data_changes += text_column_names.map do |column_name|+ <<~SQL+ #{normalize_newlines_sql("#{journable_table}.#{column_name}")} !=+ #{normalize_newlines_sql("#{data_table}.#{column_name}")}+ SQL+ end++ data_changes.join(' OR ')+ end++ def data_sink_columns+ text_columns = text_column_names+ (journable.journaled_columns_names - text_columns + text_columns).join(', ')+ end++ def data_source_columns+ text_columns = text_column_names+ normalized_text_columns = text_columns.map { |column| normalize_newlines_sql(column) }+ (journable.journaled_columns_names - text_columns + normalized_text_columns).join(', ')+ end++ def journable_data_sql_addition+ journable.class.vestal_journals_options[:data_sql]&.call(journable) || ''+ end++ def text_column_names+ journable.class.columns_hash.select { |_, v| v.type == :text }.keys.map(&:to_sym) & journable.journaled_columns_names+ end++ def journable_timestamp+ journable.respond_to?(:updated_at) && journable.updated_at || journable.respond_to?(:updated_on) && journable.updated_on+ end++ def journable_type+ journable.class.base_class.name+ end++ def journable_table_name+ journable.class.table_name+ end++ def data_table_name+ journable.class.journal_class.table_name+ end++ def normalize_newlines_sql(column)+ "REGEXP_REPLACE(COALESCE(#{column},''), '\\r\\n', '\n', 'g')"+ end++ # Because we added the journal via bare metal sql, rails does not yet+ # know of the journal. If the journable has the journals loaded already,+ # the caller might expect the journals to also be updated so we do it for him.+ def reload_journals+ journable.journals.reload if journable.journals.loaded?+ end++ def touch_journable(journal)+ return unless journal.notes.present?++ # Not using touch here on purpose,+ # as to avoid changing lock versions on the journables for this change+ attributes = journable.send(:timestamp_attributes_for_update_in_model)++ timestamps = attributes.index_with { journal.created_at }+ journable.update_columns(timestamps) if timestamps.any?+ end+ end+enddiff --git a/app/services/journals/user_reference_update_service.rb b/app/services/journals/user_reference_update_service.rbnew file mode 100644index 00000000000..eb9d25dc3b5--- /dev/null+++ b/app/services/journals/user_reference_update_service.rb@@ -0,0 +1,33 @@+module Journals+ class UserReferenceUpdateService+ attr_accessor :original_user++ def initialize(original_user)+ self.original_user = original_user+ end++ def call(substitute_user)+ journal_classes.each do |klass|+ foreign_keys.each do |foreign_key|+ if klass.column_names.include? foreign_key+ klass+ .where(foreign_key => original_user.id)+ .update_all(foreign_key => substitute_user.id)+ end+ end+ end++ ServiceResult.new success: true+ end++ private++ def journal_classes+ [Journal] + Journal::BaseJournal.subclasses+ end++ def foreign_keys+ %w[author_id user_id assigned_to_id responsible_id]+ end+ end+enddiff --git a/app/services/notifications/journal_notification_service.rb b/app/services/notifications/journal_notification_service.rbindex 594595ed6de..b3a38e39875 100644--- a/app/services/notifications/journal_notification_service.rb+++ b/app/services/notifications/journal_notification_service.rb@@ -34,27 +34,12 @@ class Notifications::JournalNotificationServicedef call(journal, send_mails)if journal.journable_type == 'WorkPackage'- handle_work_package_journal(journal, send_mails)+ enqueue_work_package_notification(journal, send_mails)endendprivate- def handle_work_package_journal(journal, send_mails)- notify_for_wp_predecessor(journal, send_mails)- enqueue_work_package_notification(journal, send_mails)- end-- # Send the notification on behalf of the predecessor in case it could not send it on its own- def notify_for_wp_predecessor(journal, send_mails)- aggregated = find_aggregated_journal_for(journal)-- if Journal::AggregatedJournal.hides_notifications?(aggregated, aggregated.predecessor)- aggregated_predecessor = find_aggregated_journal_for(aggregated.predecessor)- notify_journal_complete(aggregated_predecessor, send_mails)- end- end-def enqueue_work_package_notification(journal, send_mails)EnqueueWorkPackageNotificationJob.set(wait_until: delivery_time)diff --git a/app/workers/enqueue_work_package_notification_job.rb b/app/workers/enqueue_work_package_notification_job.rbindex c25761daa4b..ccbda53c8ba 100644--- a/app/workers/enqueue_work_package_notification_job.rb+++ b/app/workers/enqueue_work_package_notification_job.rb@@ -49,6 +49,15 @@ class EnqueueWorkPackageNotificationJob < ApplicationJob# sending the notification. Our job here is done.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)+ 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)@@ -56,7 +65,12 @@ class EnqueueWorkPackageNotificationJob < ApplicationJobnotify_journal_complete(journal, @send_mails)end- private+ 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)+ enddef raw_journal@raw_journal ||= Journal.find_by(id: @journal_id)diff --git a/db/migrate/20200522131255_splash_multi_list_customizable_journals.rb b/db/migrate/20200522131255_splash_multi_list_customizable_journals.rbnew file mode 100644index 00000000000..3342852261e--- /dev/null+++ b/db/migrate/20200522131255_splash_multi_list_customizable_journals.rb@@ -0,0 +1,99 @@+class SplashMultiListCustomizableJournals < ActiveRecord::Migration[6.0]+ def up+ # First get all customizable_journals entries that belong to a multi list custom field and that have more than one+ # value (a comma separated list). Return the values, splashed using unnest(string_to_array(...)). E.g. `1,2,3` will+ # be returned as three rows with the value_part `1`, `2` and `3` respectively.+ # Those are then inserted into the journals table.+ # Lastly, the entries with the unsplashed values are deleted.+ execute <<~SQL+ WITH existing_journals AS (+ SELECT *+ FROM (+ SELECT customizable_journals.* FROM customizable_journals+ JOIN custom_fields+ ON custom_fields.id = customizable_journals.custom_field_id AND field_format = 'list' AND multi_value = true+ ) customizable_journals+ , unnest(string_to_array(customizable_journals.value, ',')) value_part+ WHERE customizable_journals.value LIKE '%,%'+ ),+ splash_journals AS (+ INSERT INTO+ customizable_journals (+ journal_id,+ custom_field_id,+ value+ )+ SELECT+ journal_id,+ custom_field_id,+ value_part+ FROM existing_journals+ RETURNING *+ ),+ delete_journals AS (+ DELETE+ FROM+ customizable_journals+ WHERE id IN (SELECT id from existing_journals)+ )++ SELECT * FROM splash_journals;+ SQL+ end++ # Group all customizable_journals by journal_id and custom_field_id and return those, for which+ # two or more are returned. That way, we get all the once we need to aggregate again. We aggregate+ # to a comma separated list within the same query.+ # That query then serves to return all data that we need to insert into the customizable_journals again.+ # Lastly, all customizable_journals entries that where not just created and that belong to a group of more than one+ # value per journal and custom field are deleted.+ def down+ execute <<~SQL+ WITH aggregated_value AS (+ SELECT+ journal_id,+ custom_field_id,+ string_agg(value, ',') AS value+ FROM+ customizable_journals+ GROUP BY+ journal_id,+ custom_field_id+ HAVING COUNT(value) > 1+ ),+ insert_aggregated AS (+ INSERT INTO+ customizable_journals (+ journal_id,+ custom_field_id,+ value+ )+ SELECT+ journal_id,+ custom_field_id,+ value+ FROM+ aggregated_value+ RETURNING *+ )+++ DELETE FROM+ customizable_journals+ WHERE+ id IN (+ SELECT+ id+ FROM+ customizable_journals+ JOIN aggregated_value+ ON+ customizable_journals.custom_field_id = aggregated_value.custom_field_id+ AND customizable_journals.journal_id = aggregated_value.journal_id+ )+ AND id NOT IN (+ SELECT id FROM insert_aggregated+ )+ SQL+ end+enddiff --git a/db/migrate/20200522140244_remove_journal_versions_table.rb b/db/migrate/20200522140244_remove_journal_versions_table.rbnew file mode 100644index 00000000000..bcf17c57ad9--- /dev/null+++ b/db/migrate/20200522140244_remove_journal_versions_table.rb@@ -0,0 +1,11 @@+require_relative './20190724093332_add_journal_versions_table'++class RemoveJournalVersionsTable < ActiveRecord::Migration[6.0]+ def up+ ::AddJournalVersionsTable.down+ end++ def down+ ::AddJournalVersionsTable.up+ end+enddiff --git a/db/migrate/migration_utils/utils.rb b/db/migrate/migration_utils/utils.rbindex e5611c73f21..22669094fcd 100644--- a/db/migrate/migration_utils/utils.rb+++ b/db/migrate/migration_utils/utils.rb@@ -44,9 +44,5 @@ module Migrationremove_index table_name, name: index_nameendend-- def postgres?- ActiveRecord::Base.connection.instance_values['config'][:adapter] == 'postgresql'- endendenddiff --git a/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rb b/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rbindex 10af2405596..370ec990001 100644--- a/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rb+++ b/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rb@@ -53,7 +53,8 @@ module Redminesend :include, Redmine::Acts::Customizable::InstanceMethodsbefore_save :ensure_custom_values_complete- after_save :reset_custom_values_change_tracker+ after_save :touch_customizable,+ :reset_custom_values_change_trackerendend@@ -87,8 +88,6 @@ module Redminedef custom_field_values=(values)return unless values.is_a?(Hash) && values.any?- @custom_field_values_changed = true-values.with_indifferent_access.each do |custom_field_id, val|existing_custom_values = custom_values_for_custom_field id: custom_field_idnew_values = Array(val)@@ -159,10 +158,6 @@ module Redminecustom_field_values.select(&:visible?)end- def custom_field_values_changed?- @custom_field_values_changed == true- end-def custom_value_for(c)field_id = (c.is_a?(CustomField) ? c.id : c.to_i)values = custom_field_values.select { |v| v.custom_field_id == field_id }@@ -203,13 +198,11 @@ module Redmineenddef reset_custom_values_change_tracker- @custom_field_values_changed = false@custom_field_values = nilenddef reset_custom_values!@custom_field_values = nil- @custom_field_values_changed = truecustom_values.each { |cv| cv.destroy unless custom_field_values.include?(cv) }end@@ -320,6 +313,10 @@ module Redmineendend+ def touch_customizable+ touch if !saved_changes? && custom_values.loaded? && custom_values.any?(&:saved_changes?)+ end+module ClassMethodsdef available_custom_fields(_model)RequestStore.fetch(:"#{name.underscore}_custom_fields") dodiff --git a/lib/plugins/acts_as_journalized/init.rb b/lib/plugins/acts_as_journalized/init.rbindex 142b76b1d68..f91cfd28a24 100644--- a/lib/plugins/acts_as_journalized/init.rb+++ b/lib/plugins/acts_as_journalized/init.rb@@ -27,17 +27,6 @@#++#-- encoding: UTF-8-require 'acts_as_journalized'-ActiveRecord::Base.send(:include, Redmine::Acts::Journalized)--Rails.configuration.to_prepare do- # Model- require 'journal'- # this is for compatibility with current trunk- # once the plugin is part of the core, this will not be needed- # patches should then be ported onto the core- # require File.dirname(__FILE__) + '/lib/acts_as_journalized/journal_patch'- # require File.dirname(__FILE__) + '/lib/acts_as_journalized/journal_observer_patch'- # require File.dirname(__FILE__) + '/lib/acts_as_journalized/activity_fetcher_patch'-end+require 'acts_as_journalized'+ActiveRecord::Base.include(Acts::Journalized)diff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/creation.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/creation.rbsimilarity index 55%rename from lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/creation.rbrename to lib/plugins/acts_as_journalized/lib/acts/journalized/creation.rbindex 25e1b7e0c60..4abc754eb04 100644--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/creation.rb+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/creation.rb@@ -65,7 +65,7 @@# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-module Redmine::Acts::Journalized+module Acts::Journalized# Adds the functionality necessary to control journal creation on a journaled instance of# ActiveRecord::Base.module Creation@@ -82,7 +82,7 @@ module Redmine::Acts::Journalized# Class methods added to ActiveRecord::Base to facilitate the creation of new journals.module ClassMethods# Overrides the basal +prepare_journaled_options+ method defined in VestalVersions::Options- # to extract the <tt>:only</tt> and <tt>:except</tt> options into +vestal_journals_options+.+ # to extract the <tt>:calculate</tt> option into +vestal_journals_options+.def prepare_journaled_options(options)result = super(options)@@ -96,93 +96,16 @@ module Redmine::Acts::Journalizedendend- assign_vestal.call(:only, true)- assign_vestal.call(:except, true)- assign_vestal.call(:calculate, false)+ assign_vestal.call(:data_sql, false)resultendend- # Instance methods that determine whether to save a journal and actually perform the save.module InstanceMethods- # Recreates the initial journal used to track the beginning state- # of the object. Useful for objects that didn't have an initial journal- # created (e.g. legacy data)- def recreate_initial_journal!- new_journal = journals.find_by(version: 1)- new_journal ||= journals.build-- initial_changes = {}-- JournalManager.journal_class(self.class).journaled_attributes.each do |name|- # Set the current attributes as initial attributes- # This works as a fallback if no prior change is found- initial_changes[name] = send(name)-- # Try to find the real initial values- unless journals.empty?- journals[1..-1].each do |journal|- unless journal.details[name].nil?- # Found the first change in journals- # Copy the first value as initial change value- initial_changes[name] = journal.details[name].first- break- end- end- end- end-- fill_object = self.class.new-- # Force the gathered attributes onto the fill object- # FIX ME: why not just call the method directly on fill_object?- attributes_setter = ActiveRecord::Base.instance_method(:assign_attributes)- attributes_setter = attributes_setter.bind(fill_object)-- attributes_setter.call(initial_changes)-- # Get the changed attributes- changed_data = fill_object.changes.reject do |_, change|- change[0].blank? && change[1].blank?- end.slice(*journaled_columns)-- new_journal.version = 1- new_journal.activity_type = activity_type-- if respond_to?(:author)- new_journal.user_id = author.id- elsif respond_to?(:user)- new_journal.user_id = user.id- end-- # Ensure journal version exists- ::JournalVersion.find_or_create_by(journable_type: self.class.name, journable_id: id, version: 1)- JournalManager.recreate_initial_journal self.class, new_journal, changed_data-- # Backdate journal- if respond_to?(:created_at)- new_journal.update_attribute(:created_at, created_at)- elsif respond_to?(:created_on)- new_journal.update_attribute(:created_at, created_on)- end- new_journal- end-- private-- # Returns an array of column names that should be included in the changes of created- # journals. If <tt>vestal_journals_options[:only]</tt> is specified, only those columns- # will be journaled. Otherwise, if <tt>vestal_journals_options[:except]</tt> is specified,- # all columns will be journaled other than those specified. Without either option, the- # default is to journal all columns. At any rate, the four "automagic" timestamp columns- # maintained by Rails are never journaled.- def journaled_columns- case- when vestal_journals_options[:only] then self.class.column_names & vestal_journals_options[:only]- when vestal_journals_options[:except] then self.class.column_names - vestal_journals_options[:except]- else self.class.column_names- end - %w(created_at updated_at)+ # Returns an array of column names that are journaled.+ def journaled_columns_names+ self.class.journal_class.journaled_attributesend# Returns the activity type. Should be overridden in the journalized class to offerdiff --git a/lib/plugins/acts_as_journalized/lib/acts/journalized/data_class.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/data_class.rbnew file mode 100644index 00000000000..3f68855be77--- /dev/null+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/data_class.rb@@ -0,0 +1,29 @@+module Acts::Journalized+ module DataClass+ def self.included(base) # :nodoc:+ base.class_eval do+ class << self+ prepend ClassMethods+ end+ end+ end++ module ClassMethods+ def journal_class+ namespace = name.deconstantize++ if namespace == 'Journal'+ self+ else+ "Journal::#{journal_class_name}".constantize+ end+ end++ private++ def journal_class_name+ "#{base_class.name}Journal"+ end+ end+ end+enddiff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/format_hooks.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/format_hooks.rbsimilarity index 97%rename from lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/format_hooks.rbrename to lib/plugins/acts_as_journalized/lib/acts/journalized/format_hooks.rbindex 69ab197b464..07b79f1745f 100644--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/format_hooks.rb+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/format_hooks.rb@@ -27,6 +27,7 @@#++#-- encoding: UTF-8+# This file is part of the acts_as_journalized plugin for the redMine# project management software#@@ -46,7 +47,7 @@# along with this program; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.-module Redmine::Acts::Journalized+module Acts::Journalizedmodule FormatHooksdef self.included(base)base.extend ClassMethods@@ -56,7 +57,7 @@ module Redmine::Acts::Journalized# Shortcut to register a formatter for a number of fieldsdef register_on_journal_formatter(formatter, *field_names)formatter = formatter.to_sym- journal_class = JournalManager.journal_class self+ journal_class = self.journal_classfield_names.each do |field|JournalFormatter.register_formatted_field(journal_class.name.to_sym, field, formatter)enddiff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/journalized.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/journalized.rbsimilarity index 99%rename from lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/journalized.rbrename to lib/plugins/acts_as_journalized/lib/acts/journalized/journalized.rbindex 14ec65190eb..ef1cbc7ae36 100644--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/journalized.rb+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/journalized.rb@@ -27,6 +27,7 @@#++#-- encoding: UTF-8+# This file included as part of the acts_as_journalized plugin for# the redMine project management software; You can redistribute it# and/or modify it under the terms of the GNU General Public License@@ -64,7 +65,7 @@# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-module Redmine::Acts::Journalized+module Acts::Journalized# Simply adds a flag to determine whether a model class if journaled.module Journalizeddef self.extended(base) # :nodoc:diff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/options.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/options.rbsimilarity index 96%rename from lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/options.rbrename to lib/plugins/acts_as_journalized/lib/acts/journalized/options.rbindex 74e938810d9..01c143ec121 100644--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/options.rb+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/options.rb@@ -27,6 +27,7 @@#++#-- encoding: UTF-8+# This file included as part of the acts_as_journalized plugin for# the redMine project management software; You can redistribute it# and/or modify it under the terms of the GNU General Public License@@ -64,7 +65,7 @@# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-module Redmine::Acts::Journalized+module Acts::Journalized# Provides +journaled+ options conjournal and cleanup.module Optionsdef self.included(base) # :nodoc:@@ -105,9 +106,6 @@ module Redmine::Acts::Journalizeddef options_with_defaults(options)journal_options = split_option_hashes(options)- journal_options[:except] ||= []- journal_options[:except] += [primary_key, inheritance_column, :updated_on, :updated_at, :lock_version, :lft, :rgt]-result_options = journal_options.symbolize_keysresult_options.reverse_merge!(class_name: Journal.name,diff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/permissions.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/permissions.rbsimilarity index 98%rename from lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/permissions.rbrename to lib/plugins/acts_as_journalized/lib/acts/journalized/permissions.rbindex 0413184cc9e..a28166f6935 100644--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/permissions.rb+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/permissions.rb@@ -27,6 +27,7 @@#++#-- encoding: UTF-8+# This file is part of the acts_as_journalized plugin for the redMine# project management software#@@ -46,7 +47,7 @@# along with this program; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.-module Redmine::Acts::Journalized+module Acts::Journalizedmodule Permissions# Default implementation of journal editing permission# Is overridden if defined in the journalized model directlydiff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/reversion.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/reversion.rbsimilarity index 98%rename from lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/reversion.rbrename to lib/plugins/acts_as_journalized/lib/acts/journalized/reversion.rbindex 42135f509a7..a06e55f0901 100644--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/reversion.rb+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/reversion.rb@@ -65,7 +65,7 @@# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-module Redmine::Acts::Journalized+module Acts::Journalized# Enables versioned ActiveRecord::Base instances to revert to a previously saved version.module Reversiondef self.included(base) # :nodoc:@@ -88,7 +88,7 @@ module Redmine::Acts::Journalized# because some logic is based on this eager loading bug/featuredef last_loaded_journalif journals.loaded?- journals.sort_by(&:version).last+ journals.max_by(&:version)endenddiff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/save_hooks.rb b/lib/plugins/acts_as_journalized/lib/acts/journalized/save_hooks.rbsimilarity index 78%rename from lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/save_hooks.rbrename to lib/plugins/acts_as_journalized/lib/acts/journalized/save_hooks.rbindex ab7abbc7797..5c8c8c34486 100644--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/save_hooks.rb+++ b/lib/plugins/acts_as_journalized/lib/acts/journalized/save_hooks.rb@@ -49,59 +49,47 @@# These hooks make sure journals are properly created and updated with Redmine user detail,# notes and associated custom fields-module Redmine::Acts::Journalized+module Acts::Journalizedmodule SaveHooksdef self.included(base)- base.extend ClassMethods-base.class_eval doafter_save :save_journals- after_destroy :remove_journal_versionattr_accessor :journal_notes, :journal_userendend- def remove_journal_version- ::JournalVersion- .where(journable_type: self.class.name, journable_id: id)- .delete_all- end-def save_journalswith_ensured_journal_attributes do- add_journal = journals.empty? || JournalManager.changed?(self) || !@journal_notes.empty?-- if add_journal- journal = JournalManager.add_journal!(self, @journal_user, @journal_notes)+ create_call = Journals::CreateService+ .new(self, @journal_user)+ .call(notes: @journal_notes)+ if create_call.success? && create_call.resultOpenProject::Notifications.send('journal_created',- journal: journal,+ journal: create_call.result,send_notification: Journal::NotificationConfiguration.active?)-- trueend++ create_call.success?endenddef add_journal(user = User.current, notes = '')- @journal_user ||= user- @journal_notes ||= notes+ self.journal_user ||= user+ self.journal_notes ||= notesendprivatedef with_ensured_journal_attributes- @journal_user ||= User.current- @journal_notes ||= ''+ self.journal_user ||= User.current+ self.journal_notes ||= ''yieldensure- @journal_user = nil- @journal_notes = nil- end-- module ClassMethods+ self.journal_user = nil+ self.journal_notes = nilendendenddiff --git a/lib/plugins/acts_as_journalized/lib/acts_as_journalized.rb b/lib/plugins/acts_as_journalized/lib/acts_as_journalized.rbindex 6f30e622042..22e18e0f0b9 100644--- a/lib/plugins/acts_as_journalized/lib/acts_as_journalized.rb+++ b/lib/plugins/acts_as_journalized/lib/acts_as_journalized.rb@@ -49,51 +49,47 @@require 'journal_changes'require 'journal_formatter'-Dir[File.expand_path('../redmine/acts/journalized/*.rb', __FILE__)].each { |f| require f }-Dir[File.expand_path('../acts/journalized/*.rb', __FILE__)].each { |f| require f }-module Redmine- module Acts- module Journalized- def self.included(base)- base.extend ClassMethods- base.extend Journalized- end+module Acts+end++Dir[File.expand_path('../acts/journalized/*.rb', __FILE__)].sort.each { |f| require f }- module ClassMethods- def plural_name- name.underscore.pluralize- end+module Acts+ module Journalized+ def self.included(base)+ base.extend ClassMethods+ base.extend Journalized+ end- # This call will add an activity and, if neccessary, start the journaling and- # add an event callback on the model.- # Versioning and acting as an Event may only be applied once.- # To apply more than on activity, use acts_as_activity- def acts_as_journalized(options = {}, &block)- return if journaled?+ module ClassMethods+ def plural_name+ name.underscore.pluralize+ end- include_aaj_modules+ # This call will start journaling the model.+ def acts_as_journalized(options = {})+ return if journaled?- journal_hash = prepare_journaled_options(options)+ include_aaj_modules- has_many :journals, -> {- order("#{Journal.table_name}.version ASC")- }, journal_hash, &block- end+ journal_hash = prepare_journaled_options(options)- private+ has_many :journals, -> {+ order("#{Journal.table_name}.version ASC")+ }, journal_hash+ end- def include_aaj_modules- include Options- include Creation- include Reversion- include Permissions- include SaveHooks- include FormatHooks+ private- # FIXME: When the transition to the new API is complete, remove me- include Deprecated- end+ def include_aaj_modules+ include Options+ include Creation+ include Reversion+ include Permissions+ include SaveHooks+ include FormatHooks+ include DataClassendendenddiff --git a/lib/plugins/acts_as_journalized/lib/journal_changes.rb b/lib/plugins/acts_as_journalized/lib/journal_changes.rbindex f0e316048d4..23ff1a5e465 100644--- a/lib/plugins/acts_as_journalized/lib/journal_changes.rb+++ b/lib/plugins/acts_as_journalized/lib/journal_changes.rb@@ -33,33 +33,39 @@ module JournalChangesreturn @changes if @changesreturn {} if data.nil?- @changes = HashWithIndifferentAccess.new-- if predecessor.nil?- @changes = data- .journaled_attributes- .reject { |_, new_value| new_value.nil? }- .inject({}) do |result, (attribute, new_value)|- result[attribute] = [nil, new_value]- result- end- else- normalized_new_data = JournalManager.normalize_newlines(data.journaled_attributes)- normalized_old_data = JournalManager.normalize_newlines(predecessor.data.journaled_attributes)-- normalized_new_data.select { |attribute, new_value|- # we dont record changes for changes from nil to empty strings and vice versa- old_value = normalized_old_data[attribute]- new_value != old_value && (new_value.present? || old_value.present?)- }.each do |attribute, new_value|- @changes[attribute] = [normalized_old_data[attribute], new_value]- end- end+ @changes = if predecessor.nil?+ initial_journal_data_changes+ else+ subsequent_journal_data_changes+ end@changes.merge!(get_association_changes(predecessor, 'attachable', 'attachments', :attachment_id, :filename))@changes.merge!(get_association_changes(predecessor, 'customizable', 'custom_fields', :custom_field_id, :value))end+ private++ def initial_journal_data_changes+ data+ .journaled_attributes+ .reject { |_, new_value| new_value.nil? }+ .inject({}) do |result, (attribute, new_value)|+ result[attribute] = [nil, new_value]+ result+ end+ end++ def subsequent_journal_data_changes+ normalized_new_data = normalize_newlines(data.journaled_attributes)+ normalized_old_data = normalize_newlines(predecessor.data.journaled_attributes)++ normalized_new_data+ .select { |attribute, new_value| no_nil_to_empty_strings?(normalized_old_data, attribute, new_value) }+ .map { |attribute, new_value| [attribute, [normalized_old_data[attribute], new_value]] }+ .to_h+ .with_indifferent_access+ end+def get_association_changes(predecessor, journal_association, association, key, value)journal_assoc_name = "#{journal_association}_journals"@@ -73,7 +79,68 @@ module JournalChangesnew_journals = send(journal_assoc_name).map(&:attributes)old_journals = predecessor.send(journal_assoc_name).map(&:attributes)- JournalManager.changes_on_association(new_journals, old_journals, association, key, value)+ changes_on_association(new_journals, old_journals, association, key, value)endend++ def changes_on_association(current, predecessor, association, key, value)+ merged_journals = merge_reference_journals_by_id(current, predecessor, key.to_s, value.to_s)++ changes = added_references(merged_journals)+ .merge(removed_references(merged_journals))+ .merge(changed_references(merged_journals))++ to_changes_format(changes, association.to_s)+ end++ def added_references(merged_references)+ merged_references+ .select { |_, (old_value, new_value)| old_value.nil? && new_value.present? }+ end++ def removed_references(merged_references)+ merged_references+ .select { |_, (old_value, new_value)| old_value.present? && new_value.nil? }+ end++ def changed_references(merged_references)+ merged_references+ .select { |_, (old_value, new_value)| old_value.present? && new_value.present? && old_value.strip != new_value.strip }+ end++ def to_changes_format(references, key)+ references.each_with_object({}) do |(id, (old_value, new_value)), result|+ result["#{key}_#{id}"] = [old_value, new_value]+ end+ end++ def merge_reference_journals_by_id(new_journals, old_journals, id_key, value)+ all_associated_journal_ids = new_journals.map { |j| j[id_key] } | old_journals.map { |j| j[id_key] }++ all_associated_journal_ids.each_with_object({}) do |id, result|+ result[id] = [select_and_combine_journals(old_journals, id, id_key, value),+ select_and_combine_journals(new_journals, id, id_key, value)]+ end+ end++ def select_and_combine_journals(journals, id, key, value)+ selected_journals = journals.select { |j| j[key] == id }.map { |j| j[value] }++ if selected_journals.empty?+ nil+ else+ selected_journals.sort.join(',')+ end+ end++ def normalize_newlines(data)+ data.each_with_object({}) do |e, h|+ h[e[0]] = (e[1].is_a?(String) ? e[1].gsub(/\r\n/, "\n") : e[1])+ end+ end++ def no_nil_to_empty_strings?(normalized_old_data, attribute, new_value)+ old_value = normalized_old_data[attribute]+ new_value != old_value && (new_value.present? || old_value.present?)+ endenddiff --git a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/deprecated.rb b/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/deprecated.rbdeleted file mode 100644index 6b9ee40f4ad..00000000000--- a/lib/plugins/acts_as_journalized/lib/redmine/acts/journalized/deprecated.rb+++ /dev/null@@ -1,98 +0,0 @@-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2020 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-2017 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.-#++--#-- encoding: UTF-8-# This file is part of the acts_as_journalized plugin for the redMine-# project management software-#-# Copyright (C) 2010 Finn GmbH, http://finn.de-#-# 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.--# These hooks make sure journals are properly created and updated with Redmine user detail,-# notes and associated custom fields--module Redmine::Acts::Journalized- module Deprecated- # Old mailer API- def recipients- notified = []- notified = project.notified_users if project- notified.select { |user| visible?(user) }- end-- def current_journal- last_journal- end-- # FIXME: When the new API is settled, remove me- Redmine::Acts::Event::InstanceMethods.instance_methods(false).each do |m|- if m.to_s.start_with? 'event_'- class_eval(<<-RUBY, __FILE__, __LINE__)- def #{m}- if last_journal.nil?- begin- JournalManager.add_journal self- save!- reset_journal_changes- reset_journal- true- rescue Exception => e # FIXME: What to do? This likely means that the parent record is invalid!- p e- p e.message- p e.backtrace- false- end- journals.reload- end- return last_journal.data.#{m}- end- RUBY- end- end-- def event_url(options = {})- last_journal.data.event_url(options)- end-- # deprecate recipients: "use #last_journal.recipients"- # deprecate current_journal: "use #last_journal"- end-enddiff --git a/modules/backlogs/app/controllers/work_package_boxes_controller.rb b/modules/backlogs/app/controllers/work_package_boxes_controller.rbindex cbc5cdb90c1..a5e5ee84d94 100644--- a/modules/backlogs/app/controllers/work_package_boxes_controller.rb+++ b/modules/backlogs/app/controllers/work_package_boxes_controller.rb@@ -51,7 +51,7 @@ class WorkPackageBoxesController < WorkPackagesControllerupdate_work_package_from_paramsload_journals- @journal = @work_package.current_journal+ @journal = @work_package.last_journalrespond_to do |format|format.js { render partial: 'edit' }@@ -68,7 +68,7 @@ class WorkPackageBoxesController < WorkPackagesControllerformat.js { render partial: 'show' }endelse- @journal = @work_package.current_journal+ @journal = @work_package.last_journalrespond_to do |format|format.js { render partial: 'edit' }enddiff --git a/modules/backlogs/spec/models/burndown_spec.rb b/modules/backlogs/spec/models/burndown_spec.rbindex b5d3efe1db1..3c2bdba1621 100644--- a/modules/backlogs/spec/models/burndown_spec.rb+++ b/modules/backlogs/spec/models/burndown_spec.rb@@ -33,7 +33,7 @@ describe Burndown, type: :model dostory.reloadstory.send(attribute, value)story.save!- story.current_journal.update(created_at: day)+ story.last_journal.update(created_at: day)endlet(:user) { @user ||= FactoryBot.create(:user) }@@ -123,7 +123,7 @@ describe Burndown, type: :model dobefore(:each) do@story.story_points = 9@story.save!- @story.current_journal.update_attribute(:created_at, @story.created_at)+ @story.last_journal.update_attribute(:created_at, @story.created_at)enddescribe 'WITH the story being closed and opened again within the sprint duration' do@@ -169,7 +169,7 @@ describe Burndown, type: :model dopriority: issue_priority,created_at: Date.today - (20 - i).days,updated_at: Date.today - (20 - i).days)- @stories[i].current_journal.update_attribute(:created_at, @stories[i].created_at)+ @stories[i].last_journal.update_attribute(:created_at, @stories[i].created_at)endenddiff --git a/modules/costs/spec/models/user_deletion_spec.rb b/modules/costs/spec/models/user_deletion_spec.rbindex 292293725cc..f08788f8d3a 100644--- a/modules/costs/spec/models/user_deletion_spec.rb+++ b/modules/costs/spec/models/user_deletion_spec.rb@@ -69,15 +69,15 @@ describe User, '#destroy', type: :model doendendit { expect(associated_instance.journals.first.user).to eq(user2) }- it 'should update first journal changed_data' do+ it 'should update first journal details' doassociations.each do |association|- expect(associated_instance.journals.first.changed_data["#{association}_id".to_sym].last).to eq(user2.id)+ expect(associated_instance.journals.first.details["#{association}_id".to_sym].last).to eq(user2.id)endendit { expect(associated_instance.journals.last.user).to eq(substitute_user) }- it 'should update second journal changed_data' do+ it 'should update second journal details' doassociations.each do |association|- expect(associated_instance.journals.last.changed_data["#{association}_id".to_sym].last).to eq(substitute_user.id)+ expect(associated_instance.journals.last.details["#{association}_id".to_sym].last).to eq(substitute_user.id)endendend@@ -110,14 +110,14 @@ describe User, '#destroy', type: :model doit { expect(associated_instance.journals.first.user).to eq(substitute_user) }it 'should update the first journal' doassociations.each do |association|- expect(associated_instance.journals.first.changed_data["#{association}_id".to_sym].last).to eq(substitute_user.id)+ expect(associated_instance.journals.first.details["#{association}_id".to_sym].last).to eq(substitute_user.id)endendit { expect(associated_instance.journals.last.user).to eq(user2) }it 'should update the last journal' doassociations.each do |association|- expect(associated_instance.journals.last.changed_data["#{association}_id".to_sym].first).to eq(substitute_user.id)- expect(associated_instance.journals.last.changed_data["#{association}_id".to_sym].last).to eq(user2.id)+ expect(associated_instance.journals.last.details["#{association}_id".to_sym].first).to eq(substitute_user.id)+ expect(associated_instance.journals.last.details["#{association}_id".to_sym].last).to eq(user2.id)endendenddiff --git a/modules/costs/spec/models/variable_cost_object_spec.rb b/modules/costs/spec/models/variable_cost_object_spec.rbindex 4f31aac2732..4c34501f792 100644--- a/modules/costs/spec/models/variable_cost_object_spec.rb+++ b/modules/costs/spec/models/variable_cost_object_spec.rb@@ -34,20 +34,6 @@ describe VariableCostObject, type: :model dolet(:project) { FactoryBot.create(:project_with_types) }let(:user) { FactoryBot.create(:user) }- describe 'recreate initial journal' do- before do- allow(User).to receive(:current).and_return(user)-- @variable_cost_object = FactoryBot.create(:variable_cost_object, project: project,- author: user)-- @initial_journal = @variable_cost_object.journals.first- @recreated_journal = @variable_cost_object.recreate_initial_journal!- end-- it { expect(@initial_journal).to be_identical(@recreated_journal) }- end-describe 'initialization' dolet(:cost_object) { VariableCostObject.new }diff --git a/modules/documents/spec/models/document_spec.rb b/modules/documents/spec/models/document_spec.rbindex 8176cbec9c2..3af173aab12 100644--- a/modules/documents/spec/models/document_spec.rb+++ b/modules/documents/spec/models/document_spec.rb@@ -27,26 +27,22 @@#++require File.dirname(__FILE__) + '/../spec_helper'-describe Document do-let(:documentation_category) { FactoryBot.create :document_category, name: 'User documentation'}let(:project) { FactoryBot.create :project}let(:user) { FactoryBot.create(:user)}let(:admin) { FactoryBot.create(:admin)}- let(:mail) do+ let(:mail) domock = Object.newallow(mock).to receive(:deliver_now)mockendcontext "validation" do-it { is_expected.to validate_presence_of :project}it { is_expected.to validate_presence_of :title}it { is_expected.to validate_presence_of :category}-enddescribe "create with a valid document" do@@ -82,7 +78,7 @@ describe Document doexpect(document.category).to eql default_categoryexpect{document.save- }.to change{Document.count}.by 1+ }.to change { Document.count }.by 1endit "with attachments should change the updated_on-date on the document to the attachment's date" dodiff --git a/modules/meeting/app/models/activities/meeting_activity_provider.rb b/modules/meeting/app/models/activities/meeting_activity_provider.rbindex 3928a092331..e9c823cce4d 100644--- a/modules/meeting/app/models/activities/meeting_activity_provider.rb+++ b/modules/meeting/app/models/activities/meeting_activity_provider.rb@@ -78,9 +78,9 @@ class Activities::MeetingActivityProvider < Activities::BaseActivityProviderdef activity_journals_table@activity_journals_table ||= case activitywhen :meeting- JournalManager.journal_class(Meeting).arel_table+ Meeting.journal_class.arel_tableelse- JournalManager.journal_class(MeetingContent).arel_table+ MeetingContent.journal_class.arel_tableendend@@ -102,8 +102,11 @@ class Activities::MeetingActivityProvider < Activities::BaseActivityProviderdef event_title(event)case activitywhen :meeting- start_time = event['meeting_start_time'].is_a?(String) ? DateTime.parse(event['meeting_start_time'])- : event['meeting_start_time']+ start_time = if event['meeting_start_time'].is_a?(String)+ DateTime.parse(event['meeting_start_time'])+ else+ event['meeting_start_time']+ endend_time = start_time + event['meeting_duration'].to_f.hours"#{l :label_meeting}: #{event['meeting_title']} (#{format_date start_time} #{format_time start_time, false}-#{format_time end_time, false})"diff --git a/modules/meeting/app/views/meeting_contents/history.html.erb b/modules/meeting/app/views/meeting_contents/history.html.erbindex 07233ba451f..ca614ecef68 100644--- a/modules/meeting/app/views/meeting_contents/history.html.erb+++ b/modules/meeting/app/views/meeting_contents/history.html.erb@@ -100,7 +100,7 @@ See docs/COPYRIGHT.rdoc for more details.<% @content_versions.each_with_index do |content_version,index| %><tr><td class="id -short">- <%= content_version.version == @content.current_journal.version ?+ <%= content_version.version == @content.last_journal.version ?link_to(content_version.version, tab_meeting_path(@meeting, :tab => @content_type.sub(/^meeting_/, '')), id: "version-#{content_version.version}") :link_to(content_version.version, send(:"#{@content_type}_version_path", @meeting, content_version.version), id: "version-#{content_version.version}") %></td>diff --git a/modules/meeting/spec/factories/meeting_journal_factory.rb b/modules/meeting/spec/factories/meeting_journal_factory.rbindex 12c2f203549..84cfdc2228d 100644--- a/modules/meeting/spec/factories/meeting_journal_factory.rb+++ b/modules/meeting/spec/factories/meeting_journal_factory.rb@@ -34,7 +34,6 @@ FactoryBot.define dofactory :meeting_content_journal, class: Journal dojournable_type { 'MeetingContent' }activity_type { 'meetings' }- data { FactoryBot.build(:journal_meeting_content_journal) }endendenddiff --git a/modules/meeting/spec/models/meeting_spec.rb b/modules/meeting/spec/models/meeting_spec.rbindex bfb95286018..b8f5dbb1db3 100644--- a/modules/meeting/spec/models/meeting_spec.rb+++ b/modules/meeting/spec/models/meeting_spec.rb@@ -108,22 +108,6 @@ describe Meeting, type: :model doendend- describe 'Journalized Objects' do- before(:each) do- @project ||= FactoryBot.create(:project_with_types)- @current = FactoryBot.create(:user, login: 'user1', mail: '[email protected]')- allow(User).to receive(:current).and_return(@current)- end-- it 'should work with meeting' do- @meeting ||= FactoryBot.create(:meeting, title: 'Test', project: @project, author: @current)-- initial_journal = @meeting.journals.first- recreated_journal = @meeting.recreate_initial_journal!- expect(initial_journal.identical?(recreated_journal)).to be true- end- end-describe 'all_changeable_participants' dodescribe 'WITH a user having the view_meetings permission' dobefore dodiff --git a/modules/meeting/spec/models/user_deletion_spec.rb b/modules/meeting/spec/models/user_deletion_spec.rbindex d3c5072f9b4..7bf7f90696e 100644--- a/modules/meeting/spec/models/user_deletion_spec.rb+++ b/modules/meeting/spec/models/user_deletion_spec.rb@@ -29,28 +29,24 @@require File.dirname(__FILE__) + '/../spec_helper'describe User, '#destroy', type: :model do- let(:user) { FactoryBot.create(:user) }- let(:user2) { FactoryBot.create(:user) }+ let!(:user) { FactoryBot.create(:user) }+ let!(:user2) { FactoryBot.create(:user) }let(:substitute_user) { DeletedUser.first }let(:project) do- project = FactoryBot.create(:valid_project)- project+ FactoryBot.create(:valid_project)end- let(:meeting) {- FactoryBot.create(:meeting, project: project,- author: user2)- }- let(:participant) {- FactoryBot.create(:meeting_participant, user: user,- meeting: meeting,- invited: true,- attended: true)- }-- before do- user- user2+ let(:meeting) do+ FactoryBot.create(:meeting,+ project: project,+ author: user2)+ end+ let(:participant) do+ FactoryBot.create(:meeting_participant,+ user: user,+ meeting: meeting,+ invited: true,+ attended: true)endshared_examples_for 'updated journalized associated object' do@@ -81,13 +77,13 @@ describe User, '#destroy', type: :model doit { expect(associated_instance.journals.first.user).to eq(user2) }it 'should update first journal changes' doassociations.each do |association|- expect(associated_instance.journals.first.changed_data[(association.to_s + '_id').to_sym].last).to eq(user2.id)+ expect(associated_instance.journals.first.details[(association.to_s + '_id').to_sym].last).to eq(user2.id)endendit { expect(associated_instance.journals.last.user).to eq(substitute_user) }it 'should update second journal changes' doassociations.each do |association|- expect(associated_instance.journals.last.changed_data[(association.to_s + '_id').to_sym].last).to eq(substitute_user.id)+ expect(associated_instance.journals.last.details[(association.to_s + '_id').to_sym].last).to eq(substitute_user.id)endendend@@ -120,14 +116,14 @@ describe User, '#destroy', type: :model doit { expect(associated_instance.journals.first.user).to eq(substitute_user) }it 'should update the first journal' doassociations.each do |association|- expect(associated_instance.journals.first.changed_data[(association.to_s + '_id').to_sym].last).to eq(substitute_user.id)+ expect(associated_instance.journals.first.details[(association.to_s + '_id').to_sym].last).to eq(substitute_user.id)endendit { expect(associated_instance.journals.last.user).to eq(user2) }it 'should update the last journal' doassociations.each do |association|- expect(associated_instance.journals.last.changed_data[(association.to_s + '_id').to_sym].first).to eq(substitute_user.id)- expect(associated_instance.journals.last.changed_data[(association.to_s + '_id').to_sym].last).to eq(user2.id)+ expect(associated_instance.journals.last.details[(association.to_s + '_id').to_sym].first).to eq(substitute_user.id)+ expect(associated_instance.journals.last.details[(association.to_s + '_id').to_sym].last).to eq(user2.id)endendend@@ -150,10 +146,10 @@ describe User, '#destroy', type: :model dodescribe 'WHEN the user created a meeting agenda' dolet(:associations) { [:author] }- let(:associated_instance) {+ let(:associated_instance) doFactoryBot.build(:meeting_agenda, meeting: meeting,text: 'lorem')- }+ endlet(:associated_class) { MeetingAgenda }it_should_behave_like 'created journalized associated object'@@ -161,10 +157,10 @@ describe User, '#destroy', type: :model dodescribe 'WHEN the user updated a meeting agenda' dolet(:associations) { [:author] }- let(:associated_instance) {+ let(:associated_instance) doFactoryBot.build(:meeting_agenda, meeting: meeting,text: 'lorem')- }+ endlet(:associated_class) { MeetingAgenda }it_should_behave_like 'updated journalized associated object'@@ -172,10 +168,11 @@ describe User, '#destroy', type: :model dodescribe 'WHEN the user created a meeting minutes' dolet(:associations) { [:author] }- let(:associated_instance) {- FactoryBot.build(:meeting_minutes, meeting: meeting,- text: 'lorem')- }+ let(:associated_instance) do+ FactoryBot.build(:meeting_minutes,+ meeting: meeting,+ text: 'lorem')+ endlet(:associated_class) { MeetingMinutes }it_should_behave_like 'created journalized associated object'@@ -183,10 +180,11 @@ describe User, '#destroy', type: :model dodescribe 'WHEN the user updated a meeting minutes' dolet(:associations) { [:author] }- let(:associated_instance) {- FactoryBot.build(:meeting_minutes, meeting: meeting,- text: 'lorem')- }+ let(:associated_instance) do+ FactoryBot.build(:meeting_minutes,+ meeting: meeting,+ text: 'lorem')+ endlet(:associated_class) { MeetingMinutes }it_should_behave_like 'updated journalized associated object'diff --git a/modules/meeting/spec/spec_helper.rb b/modules/meeting/spec/spec_helper.rbindex ed75ee02ebd..e80132be360 100644--- a/modules/meeting/spec/spec_helper.rb+++ b/modules/meeting/spec/spec_helper.rb@@ -28,4 +28,3 @@# -- load spec_helper from OpenProject corerequire 'spec_helper'-require File.dirname(__FILE__) + '/support/plugin_spec_helper'diff --git a/modules/meeting/spec/support/plugin_spec_helper.rb b/modules/meeting/spec/support/plugin_spec_helper.rbdeleted file mode 100644index 9d6b04335dd..00000000000--- a/modules/meeting/spec/support/plugin_spec_helper.rb+++ /dev/null@@ -1,48 +0,0 @@-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2020 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-2017 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 PluginSpecHelper- shared_examples_for 'customized journal class' do- describe '#save' do- let(:text) { 'Lorem ipsum' }- let(:changed_data) { { text: [nil, text] } }-- describe 'WITHOUT compression' do- before do- # we have to save here because changed_data will update (and save) attributes and miss an ID- journal.save!- journal.changed_data = changed_data-- journal.reload- end-- it { expect(journal.changed_data[:text][1]).to eq(text) }- end- end- end-enddiff --git a/spec/controllers/messages_controller_spec.rb b/spec/controllers/messages_controller_spec.rbindex 785e35fba67..27d737c1781 100644--- a/spec/controllers/messages_controller_spec.rb+++ b/spec/controllers/messages_controller_spec.rb@@ -66,35 +66,6 @@ describe MessagesController, type: :controller doendend- describe '#create' do- context 'attachments' do- let(:attachment) { FactoryBot.create(:attachment, container: nil, author: user) }- # see ticket #2464 on OpenProject.org- context 'new attachment on new messages' do- before do- expect(controller).to receive(:authorize).and_return(true)-- allow_any_instance_of(Attachment).to receive(:filename).and_return(filename)-- post 'create', params: { forum_id: forum.id,- message: { subject: 'Test created message',- content: 'Messsage body' },- attachments: { '0' => { 'id' => attachment.id } } }- end-- describe '#journal' do- let(:attachment_id) { "attachments_#{Message.last.attachments.first.id}" }-- subject { Message.last.journals.last.details }-- it { is_expected.to have_key attachment_id }-- it { expect(subject[attachment_id]).to eq([nil, filename]) }- end- end- end- end-describe '#update' dolet(:message) { FactoryBot.create :message, forum: forum }let(:other_forum) { FactoryBot.create :forum, project: project }@@ -122,8 +93,6 @@ describe MessagesController, type: :controller dodescribe 'add' dobefore doallow_any_instance_of(Message).to receive(:editable_by?).and_return(true)-- allow_any_instance_of(Attachment).to receive(:filename).and_return(filename)endcontext 'journal' do@@ -142,7 +111,7 @@ describe MessagesController, type: :controller dodescribe '#value' dosubject { message.journals.last.details[attachment_id].last }- it { is_expected.to eq(filename) }+ it { is_expected.to eq(attachment.filename) }endendenddiff --git a/spec/factories/journal_factory.rb b/spec/factories/journal_factory.rbindex 3ec5e0da077..df8b6665797 100644--- a/spec/factories/journal_factory.rb+++ b/spec/factories/journal_factory.rb@@ -32,10 +32,18 @@ FactoryBot.define docreated_at { Time.now }sequence(:version) { |n| n + 1 }+ callback(:after_create) do |journal, evaluator|+ data = evaluator.data+ data.journal = journal+ data.save+ end+factory :work_package_journal, class: Journal dojournable_type { 'WorkPackage' }activity_type { 'work_packages' }- data { FactoryBot.build(:journal_work_package_journal) }+ transient do+ data { FactoryBot.build(:journal_work_package_journal) }+ endcallback(:after_stub) do |journal, options|journal.journable ||= options.journable || FactoryBot.build_stubbed(:work_package)@@ -45,13 +53,19 @@ FactoryBot.define dofactory :wiki_content_journal, class: Journal dojournable_type { 'WikiContent' }activity_type { 'wiki_edits' }- data { FactoryBot.build(:journal_wiki_content_journal) }++ transient do+ data { FactoryBot.build(:journal_wiki_content_journal) }+ endendfactory :message_journal, class: Journal dojournable_type { 'Message' }activity_type { 'messages' }- data { FactoryBot.build(:journal_message_journal) }++ transient do+ data { FactoryBot.build(:journal_message_journal) }+ endendendenddiff --git a/spec/lib/acts_as_journalized/journaled_spec.rb b/spec/lib/acts_as_journalized/journaled_spec.rbindex 7e92c7dfcc4..2577b85f125 100644--- a/spec/lib/acts_as_journalized/journaled_spec.rb+++ b/spec/lib/acts_as_journalized/journaled_spec.rb@@ -29,98 +29,23 @@require 'spec_helper'describe 'Journalized Objects' do- before(:each) do- @project ||= FactoryBot.create(:project_with_types)- @type ||= @project.types.first- @current = FactoryBot.create(:user, login: 'user1', mail: '[email protected]')- allow(User).to receive(:current).and_return(@current)- end-- it 'should work with work packages' do- @status_open ||= FactoryBot.create(:status, name: 'Open', is_default: true)- @work_package ||= FactoryBot.create(:work_package, project: @project, status: @status_open, type: @type, author: @current)-- initial_journal = @work_package.journals.first- recreated_journal = @work_package.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-- it 'should work with news' do- @news ||= FactoryBot.create(:news, project: @project, author: @current, title: 'Test', summary: 'Test', description: 'Test')-- initial_journal = @news.journals.first- recreated_journal = @news.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-- it 'should work with wiki content' do- @wiki_content ||= FactoryBot.create(:wiki_content, author: @current)-- initial_journal = @wiki_content.journals.first- recreated_journal = @wiki_content.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-- it 'should work with messages' do- @message ||= FactoryBot.create(:message, content: 'Test', subject: 'Test', author: @current)-- initial_journal = @message.journals.first- recreated_journal = @message.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-- it 'should work with time entries' do- @status_open ||= FactoryBot.create(:status, name: 'Open', is_default: true)- @work_package ||= FactoryBot.create(:work_package, project: @project, status: @status_open, type: @type, author: @current)-- @time_entry ||= FactoryBot.create(:time_entry, work_package: @work_package, project: @project, spent_on: Time.now, hours: 5, user: @current, activity: FactoryBot.create(:time_entry_activity))-- initial_journal = @time_entry.journals.first- recreated_journal = @time_entry.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-- it 'should work with attachments' do- @attachment ||= FactoryBot.create(:attachment, container: FactoryBot.create(:work_package), author: @current)-- initial_journal = @attachment.journals.first- recreated_journal = @attachment.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-- it 'should work with changesets' do- Setting.enabled_scm = ['subversion']- @repository ||= FactoryBot.create(:repository_subversion, url: 'http://svn.test.com')- @changeset ||= FactoryBot.create(:changeset, committer: @current.login, repository: @repository)-- initial_journal = @changeset.journals.first- recreated_journal = @changeset.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-describe 'journal_editable_by?' docontext 'when the journable is a work package' dolet!(:user) { FactoryBot.create(:user) }let!(:project) { FactoryBot.create(:project_with_types) }let!(:role) { FactoryBot.create(:role, permissions: [:edit_work_packages]) }- let!(:member) {+ let!(:member) doFactoryBot.create(:member, project: project,- roles: [role],- principal: user)- }- let!(:work_package) {- FactoryBot.build(:work_package, type: project.types.first,- author: user,- project: project,- description: '')- }+ roles: [role],+ principal: user)+ end+ let!(:work_package) do+ FactoryBot.build(:work_package,+ type: project.types.first,+ author: user,+ project: project,+ description: '')+ endsubject { work_package.journal_editable_by?(user) }diff --git a/spec/mailers/user_mailer_spec.rb b/spec/mailers/user_mailer_spec.rbindex 336f6662fa1..d30d697b05b 100644--- a/spec/mailers/user_mailer_spec.rb+++ b/spec/mailers/user_mailer_spec.rb@@ -32,11 +32,17 @@ require 'spec_helper'describe UserMailer, type: :mailer dolet(:type_standard) { FactoryBot.build_stubbed(:type_standard) }let(:user) { FactoryBot.build_stubbed(:user) }- let(:journal) { FactoryBot.build_stubbed(:work_package_journal) }- let(:work_package) {+ let(:journal) do+ FactoryBot.build_stubbed(:work_package_journal).tap do |j|+ allow(j)+ .to receive(:data)+ .and_return(FactoryBot.build_stubbed(:journal_work_package_journal))+ end+ end+ let(:work_package) doFactoryBot.build_stubbed(:work_package,type: type_standard)- }+ endlet(:recipient) { FactoryBot.build_stubbed(:user) }@@ -81,9 +87,9 @@ describe UserMailer, type: :mailer doendshared_examples_for 'does only send mails to author if permitted' do- let(:user_preference) {+ let(:user_preference) doFactoryBot.build(:user_preference, others: { no_self_notified: true })- }+ endlet(:user) { FactoryBot.build_stubbed(:user, preference: user_preference) }context 'mail is for another user' do@@ -431,10 +437,10 @@ describe UserMailer, type: :mailer dodescribe 'custom field' dolet(:expected_text_1) { 'original, unchanged text' }let(:expected_text_2) { 'modified, new text' }- let(:custom_field) {+ let(:custom_field) doFactoryBot.create :work_package_custom_field,field_format: 'text'- }+ endbefore doallow(journal).to receive(:details).and_return("custom_fields_#{custom_field.id}" => [expected_text_1, expected_text_2])@@ -501,11 +507,11 @@ describe UserMailer, type: :mailer doenddescribe 'html mail' do- let(:expected_translation) {+ let(:expected_translation) doI18n.t(:done_ratio, scope: [:activerecord,:attributes,:work_package])- }+ endlet(:expected_prefix) { "<li><strong>#{expected_translation}</strong>" }before dodiff --git a/spec/models/journal/aggregated_journal_spec.rb b/spec/models/journal/aggregated_journal_spec.rbindex fa943e7b31d..e1c773f5099 100644--- a/spec/models/journal/aggregated_journal_spec.rb+++ b/spec/models/journal/aggregated_journal_spec.rb@@ -246,8 +246,8 @@ describe Journal::AggregatedJournal, type: :model dobefore dowork_package.status = FactoryBot.build(:status)work_package.save!- work_package.journals.second.created_at += delay- work_package.journals.second.save!+ second_journal = work_package.journals.second+ second_journal.update_column(:created_at, second_journal.created_at + delay)endit 'returns both journals' dodiff --git a/spec/models/journal_manager_spec.rb b/spec/models/journal_manager_spec.rbdeleted file mode 100644index a0ec25c0353..00000000000--- a/spec/models/journal_manager_spec.rb+++ /dev/null@@ -1,163 +0,0 @@-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2020 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-2017 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 'spec_helper'--describe JournalManager, type: :model do- describe '#self.changed?' do- let(:journable) do- FactoryBot.create(:work_package, description: old).tap do |journable|- # replace newline character and apply another change- journable.assign_attributes description: changed- end- end-- context 'when only the newline character representation has changed' do- let(:old) { "Description\nContains newline character" }- let(:changed) { old.gsub("\n", "\r\n") }-- subject { JournalManager.changed? journable }-- it { is_expected.to be_falsey }- end-- context 'when old value is nil and changed value is an empty string' do- let(:old) { nil }- let(:changed) { '' }-- subject { JournalManager.changed? journable }-- it { is_expected.to be_falsey }- end-- context 'when changed value is nil and old value is an empty string' do- let(:old) { '' }- let(:changed) { nil }-- subject { JournalManager.changed? journable }-- it { is_expected.to be_falsey }- end-- context 'when changed value has a value and old value is an empty string' do- let(:old) { '' }- let(:changed) { 'Changed text' }-- subject { JournalManager.changed? journable }-- it { is_expected.to be_truthy }- end-- context 'when changed value has a value and old value is nil' do- let(:old) { nil }- let(:changed) { 'Changed text' }-- subject { JournalManager.changed? journable }-- it { is_expected.to be_truthy }- end-- context 'when changed value is nil and old value was some text' do- let(:old) { 'Old text' }- let(:changed) { nil }-- subject { JournalManager.changed? journable }-- it { is_expected.to be_truthy }- end-- context 'when changed value is an empty string and old value was some text' do- let(:old) { 'Old text' }- let(:changed) { '' }-- subject { JournalManager.changed? journable }-- it { is_expected.to be_truthy }- end- end-- describe '.update_user_references' do- let!(:work_package) { FactoryBot.create :work_package }- let!(:doomed_user) { work_package.author }- let!(:data1) do- FactoryBot.build(:journal_work_package_journal,- subject: work_package.subject,- status_id: work_package.status_id,- type_id: work_package.type_id,- author_id: doomed_user.id,- project_id: work_package.project_id)- end- let!(:data2) do- FactoryBot.build(:journal_work_package_journal,- subject: work_package.subject,- status_id: work_package.status_id,- type_id: work_package.type_id,- author_id: doomed_user.id,- project_id: work_package.project_id)- end- let!(:doomed_user_journal) do- FactoryBot.create :work_package_journal,- notes: '1',- user: doomed_user,- journable_id: work_package.id,- data: data1- end- let!(:some_other_journal) do- FactoryBot.create :work_package_journal,- notes: '2',- journable_id: work_package.id,- data: data2- end-- before do- doomed_user.destroy- end-- it "should mark the user's journal as deleted" do- expect(doomed_user_journal.reload.user.is_a?(DeletedUser)).to be_truthy- end-- it "should not mark an unrelated journal's user as deleted" do- expect(some_other_journal.reload.user.is_a?(DeletedUser)).to be_falsey- end- end-- describe '.changes_on_association' do- context 'with one of the values having a newline' do- let(:current) { { id: 2, value: 'some value', custom_field_id: 123 }.with_indifferent_access }- let(:predecessor) { { id: 1, value: "some value\n", custom_field_id: 123 }.with_indifferent_access }-- it 'does not identify a change' do- changes = JournalManager.changes_on_association([current], [predecessor], 'custom_fields', :custom_field_id, :value)-- expect(changes)- .to be_empty- end- end- end-enddiff --git a/modules/meeting/spec/models/meeting_content_journal_spec.rb b/spec/models/journal_spec.rbsimilarity index 81%rename from modules/meeting/spec/models/meeting_content_journal_spec.rbrename to spec/models/journal_spec.rbindex 17ca1d0065f..94ac13a1068 100644--- a/modules/meeting/spec/models/meeting_content_journal_spec.rb+++ b/spec/models/journal_spec.rb@@ -1,3 +1,5 @@+#-- encoding: UTF-8+#-- copyright# OpenProject is an open source project management software.# Copyright (C) 2012-2020 the OpenProject GmbH@@ -25,15 +27,14 @@## See docs/COPYRIGHT.rdoc for more details.#+++require 'spec_helper'-require File.dirname(__FILE__) + '/../spec_helper'--require 'journal/meeting_content_journal'--describe Journal, type: :model do- include PluginSpecHelper-- let(:journal) { FactoryBot.build(:meeting_content_journal) }-- it_should_behave_like 'customized journal class'+describe Journal,+ type: :model do+ describe '#journable' do+ it 'raises no error on a new journal without a journable' do+ expect(Journal.new.journable)+ .to be_nil+ end+ endenddiff --git a/spec/models/journal_version_spec.rb b/spec/models/journal_version_spec.rbdeleted file mode 100644index 0c36e257f03..00000000000--- a/spec/models/journal_version_spec.rb+++ /dev/null@@ -1,73 +0,0 @@-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2020 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-2017 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 'spec_helper'--describe JournalVersion, type: :model do- let!(:work_package) do- wp = FactoryBot.build(:work_package)- wp.journal_notes = 'foobar!'-- wp.save!- wp- end-- subject { ::JournalVersion.find_by!(journable_type: 'WorkPackage', journable_id: work_package.id) }-- before do- work_package- subject- end-- it 'is created when the work package is created' do- expect(subject.version).to eq 1- end-- it 'is incremented when the work package is journaled' do- work_package.subject = 'Foobar!'- work_package.journal_notes = 'My comment'- work_package.save!-- work_package.reload-- expect(work_package.journals.count).to eq 2- expect(work_package.journals.first.version).to eq 1- expect(work_package.journals.last.version).to eq 2-- subject.reload- expect(subject.version).to eq 2- end-- it 'is removed when the work package is removed' do- expect(subject).to be_present-- work_package.destroy!-- expect { subject.reload }.to raise_error ActiveRecord::RecordNotFound- end-enddiff --git a/modules/documents/spec/lib/acts_as_journalized/journaled_spec.rb b/spec/models/messages/acts_as_journalized_spec.rbsimilarity index 60%rename from modules/documents/spec/lib/acts_as_journalized/journaled_spec.rbrename to spec/models/messages/acts_as_journalized_spec.rbindex 2e57028968e..0451e4b3ac0 100644--- a/modules/documents/spec/lib/acts_as_journalized/journaled_spec.rb+++ b/spec/models/messages/acts_as_journalized_spec.rb@@ -28,20 +28,28 @@require 'spec_helper'-describe "Journalized Objects" do- before(:each) do- @type ||= FactoryBot.create(:type_feature)- @project ||= FactoryBot.create(:project_with_types)- @current = FactoryBot.create(:user, login: "user1", mail: "[email protected]")- allow(User).to receive(:current).and_return @current+describe Message, 'acts_as_journalized', type: :model do+ let(:user) { FactoryBot.create(:user) }+ let(:project) { FactoryBot.create(:project) }+ let!(:forum) do+ FactoryBot.create(:forum,+ project: project)end+ let(:attachment) { FactoryBot.create(:attachment, container: nil, author: user) }- it 'should work with documents' do- @document ||= FactoryBot.create(:document)+ context 'on creation' do+ context 'attachments' do+ before do+ Message.create! forum: forum, subject: 'Test message', content: 'Message body', attachments: [attachment]+ end+ let(:attachment_id) { "attachments_#{attachment.id}" }+ let(:filename) { attachment.filename }- initial_journal = @document.journals.first- recreated_journal = @document.recreate_initial_journal!+ subject { Message.last.journals.last.details }- expect(initial_journal).to be_identical(recreated_journal)+ it { is_expected.to have_key attachment_id }++ it { expect(subject[attachment_id]).to eq([nil, filename]) }+ endendenddiff --git a/spec/models/work_package/work_package_acts_as_journalized_spec.rb b/spec/models/work_package/work_package_acts_as_journalized_spec.rbindex ae527fbda9e..5ea6c15ada5 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@@ -47,7 +47,7 @@ describe WorkPackage, type: :model dolet(:current_user) { FactoryBot.create(:user) }before do- allow(User).to receive(:current).and_return current_user+ login_as(current_user)work_packageend@@ -73,6 +73,14 @@ describe WorkPackage, type: :model doexpect(Journal.first.details[:description]).to match_array [nil, work_package.description]end++ it 'has the timestamp of the work package update time for created_at' do+ # This seemingly unnecessary reload leads to the updated_at having the same+ # precision as the created_at of the Journal. It is database dependent, so it would work without+ # reload on PG 12 but does not work on PG 9.+ expect(Journal.first.created_at)+ .to eql(work_package.reload.updated_at)+ endendcontext 'nothing is changed' do@@ -83,17 +91,6 @@ describe WorkPackage, type: :model doit { expect(Journal.all.count).to eq(1) }end- context 'when the journal manager does not detect a change to be tracked' do- before do- allow(JournalManager).to receive(:changed?).with(work_package).and_return false- work_package.assign_attributes subject: "#{work_package.subject} with changes"- end-- it 'is not created' do- expect { work_package.save! }.not_to(change { work_package.journals.reload.length })- end- end-context 'different newlines' dolet(:description) { "Description\n\nwith newlines\n\nembedded" }let(:changed_description) { description.gsub("\n", "\r\n") }@@ -241,6 +238,14 @@ describe WorkPackage, type: :model doexpect(last_journal.data.description).to eql('description v4')endend++ it 'has the timestamp of the work package update time for created_at' do+ # This seemingly unnecessary reload leads to the updated_at having the same+ # precision as the created_at of the Journal. It is database dependent, so it would work without+ # reload on PG 12 but does not work on PG 9.+ expect(work_package.journals.order(:id).last.created_at)+ .to eql(work_package.reload.updated_at)+ endendcontext 'attachments' do@@ -389,8 +394,6 @@ describe WorkPackage, type: :model doinclude_context 'work package with custom value'it { expect(work_package.journals.reload.last.customizable_journals).to be_empty }-- it { expect(JournalManager.changed?(work_package)).to be_falsey }enddescribe 'empty values handled as non existing' do@@ -400,6 +403,37 @@ describe WorkPackage, type: :model doendendend++ context 'on only journal notes adding' do+ before do+ work_package.add_journal(User.current, 'some notes')+ work_package.save+ end++ it 'has the timestamp of the work package update time for created_at' do+ # This seemingly unnecessary reload leads to the updated_at having the same+ # precision as the created_at of the Journal. It is database dependent, so it would work without+ # reload on PG 12 but does not work on PG 9.+ expect(work_package.journals.last.created_at)+ .to eql(work_package.reload.updated_at)+ end+ end++ context 'on mixed journal notes and attribute adding' do+ before do+ work_package.add_journal(User.current, 'some notes')+ work_package.subject = 'blubs'+ work_package.save+ end++ it 'has the timestamp of the work package update time for created_at' do+ # This seemingly unnecessary reload leads to the updated_at having the same+ # precision as the created_at of the Journal. It is database dependent, so it would work without+ # reload on PG 12 but does not work on PG 9.+ expect(work_package.journals.last.created_at)+ .to eql(work_package.reload.updated_at)+ end+ endenddescribe 'Acts as journalized' do@@ -448,57 +482,5 @@ describe WorkPackage, type: :model do@issue.save!endend-- describe 'Acts as journalized recreate initial journal' do- it 'should not include certain attributes' do- recreated_journal = @issue.recreate_initial_journal!-- expect(recreated_journal.details.include?('lock_version')).to eq(false)- expect(recreated_journal.details.include?('updated_at')).to eq(false)- expect(recreated_journal.details.include?('updated_on')).to eq(false)- expect(recreated_journal.details.include?('id')).to eq(false)- expect(recreated_journal.details.include?('type')).to eq(false)- end-- it 'should not include useless transitions' do- recreated_journal = @issue.recreate_initial_journal!-- recreated_journal.details.values.each do |change|- expect(change.first).not_to eq(change.last)- end- end-- it 'should not be different from the initially created journal by aaj' do- # Creating four journals total- @issue.status = @status_resolved- @issue.assigned_to = @user2- @issue.save!- @issue.reload-- @issue.priority = @priority_high- @issue.save!- @issue.reload-- @issue.status = @status_rejected- @issue.priority = @priority_low- @issue.estimated_hours = 3- @issue.save!-- initial_journal = @issue.journals.first- recreated_journal = @issue.recreate_initial_journal!-- expect(initial_journal).to be_identical(recreated_journal)- end-- it 'should not validate with oddly set estimated_hours' do- @issue.estimated_hours = 'this should not work'- expect(@issue).not_to be_valid- end-- it 'should validate with sane estimated_hours' do- @issue.estimated_hours = '13h'- expect(@issue).to be_valid- end- endendenddiff --git a/spec/models/work_package/work_package_custom_fields_spec.rb b/spec/models/work_package/work_package_custom_fields_spec.rbindex 0ac31be1e52..211d3099cbe 100644--- a/spec/models/work_package/work_package_custom_fields_spec.rb+++ b/spec/models/work_package/work_package_custom_fields_spec.rb@@ -34,18 +34,20 @@ describe WorkPackage, type: :model dolet(:project) { FactoryBot.create(:project, types: [type]) }let(:work_package) doFactoryBot.build(:work_package,- project: project,- type: type)+ project: project,+ type: type)end- let (:custom_field) do+ let(:custom_field) doFactoryBot.create(:work_package_custom_field,- name: 'Database',- field_format: 'list',- possible_values: %w(MySQL PostgreSQL Oracle),- is_required: true)+ name: 'Database',+ field_format: 'list',+ possible_values: %w(MySQL PostgreSQL Oracle),+ is_required: cf_required)end- shared_context 'project with required custom field' do+ let(:cf_required) { true }++ shared_context 'project with custom field' dobefore doproject.work_package_custom_fields << custom_fieldtype.custom_fields << custom_field@@ -69,8 +71,74 @@ describe WorkPackage, type: :model doit { is_expected.to include(custom_field) }end+ context 'touch on save' do+ include_context 'project with custom field'+ let(:cf_required) { false }++ before do+ work_package.update_columns(updated_at: 3.days.ago)+ end++ context 'creating a cf value' do+ it 'updates the updated_at attribute' do+ expect { change_custom_field_value(work_package, custom_field.possible_values.first) }+ .to change { work_package.updated_at }+ end++ it 'updates the lock_version attribute' do+ expect { change_custom_field_value(work_package, custom_field.possible_values.first) }+ .to change { work_package.lock_version }.by(1)+ end+ end++ context 'deleting a cf value' do+ before do+ change_custom_field_value(work_package, custom_field.possible_values.first)+ end++ it 'updates the updated_at attribute' do+ expect { change_custom_field_value(work_package, nil) }+ .to change { work_package.updated_at }+ end++ it 'updates the lock_version attribute' do+ expect { change_custom_field_value(work_package, nil) }+ .to change { work_package.lock_version }.by(1)+ end+ end++ context 'updating a cf value' do+ before do+ change_custom_field_value(work_package, custom_field.possible_values.first)+ end++ it 'updates the updated_at attribute' do+ expect { change_custom_field_value(work_package, custom_field.possible_values.last) }+ .to change { work_package.updated_at }+ end++ it 'updates the lock_version attribute' do+ expect { change_custom_field_value(work_package, custom_field.possible_values.last) }+ .to change { work_package.lock_version }.by(1)+ end+ end++ context 'updating a cf value and another attribute at the same time' do+ before do+ change_custom_field_value(work_package, custom_field.possible_values.first)+ end++ it 'updates the lock_version attribute by 1' do+ work_package.subject = 'new subject'++ expect { change_custom_field_value(work_package, custom_field.possible_values.last) }+ .to change { work_package.lock_version }.by(1)+ end+ end+ end+context 'required custom field exists' do- include_context 'project with required custom field'+ include_context 'project with custom field'it_behaves_like 'work package with required custom field'@@ -186,7 +254,7 @@ describe WorkPackage, type: :model dolet (:custom_field_2) { FactoryBot.create(:work_package_custom_field) }let(:type_feature) doFactoryBot.create(:type_feature,- custom_fields: [custom_field_2])+ custom_fields: [custom_field_2])endbefore do@@ -195,7 +263,7 @@ describe WorkPackage, type: :model doendcontext 'with initial type' do- include_context 'project with required custom field'+ include_context 'project with custom field'describe 'pre-condition' doit_behaves_like 'work package with required custom field'@@ -217,8 +285,8 @@ describe WorkPackage, type: :model docontext 'w/o initial type' dolet(:work_package_without_type) doFactoryBot.build_stubbed(:work_package,- project: project,- type: type)+ project: project,+ type: type)enddescribe 'pre-condition' do@@ -261,12 +329,12 @@ describe WorkPackage, type: :model dolet(:value) { 'text' * 1024 }let(:custom_field) doFactoryBot.create(:work_package_custom_field,- name: 'Test Text',- field_format: 'text',- is_required: true)+ name: 'Test Text',+ field_format: 'text',+ is_required: true)end- include_context 'project with required custom field'+ include_context 'project with custom field'it_behaves_like 'work package with required custom field'@@ -287,13 +355,13 @@ describe WorkPackage, type: :model dodescribe 'validation error interpolation' dolet :custom_field doFactoryBot.create :work_package_custom_field,- name: 'PIN',- field_format: 'text',- max_length: 4,- is_required: true+ name: 'PIN',+ field_format: 'text',+ max_length: 4,+ is_required: trueend- include_context 'project with required custom field'+ include_context 'project with custom field'it 'works for the max length validation' dowork_package.custom_field_values.first.value = '12345'diff --git a/spec/services/journals/user_reference_update_service_spec.rb b/spec/services/journals/user_reference_update_service_spec.rbnew file mode 100644index 00000000000..43ff2ce68df--- /dev/null+++ b/spec/services/journals/user_reference_update_service_spec.rb@@ -0,0 +1,106 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2020 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-2017 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 'spec_helper'++describe Journals::UserReferenceUpdateService, type: :model do+ let!(:work_package) { FactoryBot.create :work_package }+ let!(:doomed_user) { work_package.author }+ let!(:other_user) { FactoryBot.create(:user) }+ let!(:data1) do+ FactoryBot.build(:journal_work_package_journal,+ subject: work_package.subject,+ status_id: work_package.status_id,+ type_id: work_package.type_id,+ author_id: doomed_user.id,+ assigned_to_id: other_user.id,+ responsible_id: doomed_user.id,+ project_id: work_package.project_id)+ end+ let!(:data2) do+ FactoryBot.build(:journal_work_package_journal,+ subject: work_package.subject,+ status_id: work_package.status_id,+ type_id: work_package.type_id,+ author_id: doomed_user.id,+ assigned_to_id: doomed_user.id,+ responsible_id: other_user.id,+ project_id: work_package.project_id)+ end+ let!(:doomed_user_journal) do+ FactoryBot.create :work_package_journal,+ notes: '1',+ user: doomed_user,+ journable_id: work_package.id,+ data: data1+ end+ let!(:some_other_journal) do+ FactoryBot.create :work_package_journal,+ notes: '2',+ journable_id: work_package.id,+ data: data2+ end++ describe '.call' do+ subject do+ described_class+ .new(doomed_user)+ .call(DeletedUser.first)+ end++ before do+ subject+ end++ it "is success" do+ expect(subject)+ .to be_success+ end++ it "marks only the user's journal as deleted" do+ expect(doomed_user_journal.reload.user.is_a?(DeletedUser)).to be_truthy+ expect(some_other_journal.reload.user.is_a?(DeletedUser)).to be_falsey+ end++ it "marks the assignee stored in the WorkPackageJournal as deleted" do+ expect(data2.reload.assigned_to_id)+ .to eql(DeletedUser.first.id)++ expect(data1.reload.assigned_to_id)+ .to eql(other_user.id)+ end++ it "marks the responsible stored in the WorkPackageJournal as deleted" do+ expect(data1.reload.responsible_id)+ .to eql(DeletedUser.first.id)++ expect(data2.reload.responsible_id)+ .to eql(other_user.id)+ end+ end+enddiff --git a/spec/services/notifications/journal_notification_service_spec.rb b/spec/services/notifications/journal_notification_service_spec.rbindex 7391e90e882..5b0d1de7c44 100644--- a/spec/services/notifications/journal_notification_service_spec.rb+++ b/spec/services/notifications/journal_notification_service_spec.rb@@ -29,214 +29,51 @@require 'spec_helper'describe Notifications::JournalNotificationService do- let(:project) { FactoryBot.create(:project_with_types) }- let(:user) do- FactoryBot.build(:user,- mail_notification: 'all',- member_in_project: project)- end- let(:work_package) do- FactoryBot.create(:work_package,- project: project,- author: user,- type: project.types.first)- end- let(:journal) { work_package.journals.last }+ let(:journable) { FactoryBot.build_stubbed(:stubbed_work_package) }+ let(:journal) { FactoryBot.build_stubbed(:journal, journable: journable) }let(:send_mails) { true }- let(:notifications) { [] }-- def call_listener- described_class.call(journal, send_mails)- end- before do- # make sure no other calls are made due to WP creation/update- allow(OpenProject::Notifications).to receive(:send) # ... and do nothing+ shared_examples_for 'enqueues a notification' do+ before do+ # Freeze time+ allow(Time)+ .to receive(:current)+ .and_return(Time.current)- login_as(user)- allow(Setting).to receive(:notified_events).and_return(notifications)- end+ notification_set = double('notification set')- shared_examples_for 'enqueues a regular notification' do- it doexpect(EnqueueWorkPackageNotificationJob)- .to receive_message_chain(:set, :perform_later)+ .to receive(:set)+ .with(wait_until: Setting.journal_aggregation_time_minutes.to_i.minutes.from_now)+ .and_return(notification_set)- call_listener+ expect(notification_set)+ .to receive(:perform_later)+ .with(journal.id, send_mails)end- end- shared_examples_for 'sends notification' do- it 'sends a notification' do- expect(OpenProject::Notifications)- .to receive(:send)- .with(OpenProject::Events::AGGREGATED_WORK_PACKAGE_JOURNAL_READY,- journal: an_instance_of(Journal::AggregatedJournal),- send_mail: send_mails)-- call_listener+ it 'fulfills expectations' do+ described_class.call(journal, send_mails)endend- describe 'journal creation' do- context 'work_package_created' do- before do- FactoryBot.create(:work_package, project: project)- end-- it_behaves_like 'enqueues a regular notification'- end-- context 'work_package_updated' do- before do- work_package.add_journal(user)- work_package.subject = 'A change to the issue'- work_package.save!(validate: false)- end-- it_behaves_like 'enqueues a regular notification'+ shared_examples_for 'enqueues no notification' do+ before do+ expect(EnqueueWorkPackageNotificationJob)+ .not_to receive(:set)end- context 'work_package_note_added' do- before do- work_package.add_journal(user, 'This update has a note')- work_package.save!(validate: false)- end-- it_behaves_like 'enqueues a regular notification'+ it 'fulfills expectations' do+ described_class.call(journal, send_mails)endend- 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-- let(:author) { user }- 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] }-- def update_by(author, attributes)- WorkPackages::UpdateService- .new(user: author, model: work_package)- .call(attributes)- end-- shared_context 'updated until Journal 1' do- before do- expect(update_by(author, journal_notes: 'a comment')).to be_success- end- end-- shared_context 'updated until Journal 2' do- include_context 'updated until Journal 1'-- before do- work_package.reload- expect(update_by(author, subject: 'new subject')).to be_success- end- end-- shared_context 'updated until Journal 3' do- include_context 'updated until Journal 2'-- before do- work_package.reload- expect(update_by(author, journal_notes: 'a comment')).to be_success- end- end-- 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-- describe 'Journal 1' do- include_context 'updated until Journal 1'-- it_behaves_like 'enqueues a regular notification'- end-- describe 'Journal 2' do- include_context 'updated until Journal 2'-- it_behaves_like 'enqueues a regular notification'- end-- describe 'Journal 3' do- include_context 'updated until Journal 3'-- it_behaves_like 'enqueues a regular notification'- end- end-- context 'journal 3 created after timeout of 1, but inside of timeout for 2' do- describe 'Journal 3' do- include_context 'updated until Journal 3'-- before do- journal_2.update_attribute(:created_at, journal_1.created_at + (timeout / 2))- journal_3.update_attribute(:created_at, journal_1.created_at + timeout + 5.seconds)- end-- it_behaves_like 'sends notification' # for journal 1- it_behaves_like 'enqueues a regular notification' # for journal 3- end- end-- context 'journal 3 created after timeout of 1 and 2' do- # This is a normal case again, ensuring Journal 3 takes no responsibility when not necessary.-- describe 'Journal 3' do- include_context 'updated until Journal 3'-- before do- journal_2.update_attribute(:created_at, journal_1.created_at + (timeout / 2))- journal_3.update_attribute(:created_at, journal_2.created_at + timeout + 5.seconds)- end-- it_behaves_like 'enqueues a regular notification'- end- end-- context 'two subsequent changes after timeout of another journal' do- # This is a normal case again, because handling edge cases makes us miss on the normal cases-- before do- work_package.journals.first.update_attribute(:created_at, (timeout + 5.seconds).ago)- work_package.reload-- expect(update_by(author, done_ratio: 50)).to be_success- work_package.reload- expect(update_by(author, done_ratio: 60)).to be_success- work_package.reload- end-- it_behaves_like 'enqueues a regular notification'- end+ context 'for a work package journal' do+ it_behaves_like 'enqueues a notification'end-end-describe 'initialization' do- it 'subscribes the listener' do- expect(Notifications::JournalNotificationService).to receive(:call)- FactoryBot.create(:work_package)+ context 'for a news journal' do+ let(:journable) { FactoryBot.build_stubbed(:news) }+ it_behaves_like 'enqueues no notification'endenddiff --git a/spec/services/work_packages/update_service_spec.rb b/spec/services/work_packages/update_service_spec.rbindex 9901900745c..6e78e9d87d4 100644--- a/spec/services/work_packages/update_service_spec.rb+++ b/spec/services/work_packages/update_service_spec.rb@@ -51,7 +51,7 @@ describe WorkPackages::UpdateService, type: :model doendbefore do- # Stub update_ancestors because it messes with the JournalManager expect+ # Stub update_ancestors because it messes with the jouralizing expectationsallow(instance).to receive(:update_ancestors).and_return []enddiff --git a/spec/workers/mail_notification_jobs/enqueue_work_package_notification_job_spec.rb b/spec/workers/mail_notification_jobs/enqueue_work_package_notification_job_spec.rbindex 5329243bf22..f425539d759 100644--- a/spec/workers/mail_notification_jobs/enqueue_work_package_notification_job_spec.rb+++ b/spec/workers/mail_notification_jobs/enqueue_work_package_notification_job_spec.rb@@ -32,9 +32,8 @@ require 'spec_helper'describe EnqueueWorkPackageNotificationJob, type: :model dolet(:project) { FactoryBot.create(:project) }- let(:role) { FactoryBot.create(:role, permissions: [:view_work_packages]) }let(:recipient) do- FactoryBot.create(:user, member_in_project: project, member_through_role: role, login: "johndoe")+ FactoryBot.create(:user, member_in_project: project, member_with_permissions: [:view_work_packages], login: "johndoe")endlet(:author) { FactoryBot.create(:user, login: "marktwain") }let(:work_package) do@@ -100,6 +99,35 @@ describe EnqueueWorkPackageNotificationJob, type: :model doit_behaves_like 'sends no notification'end+ describe 'journal creation' do+ context 'work_package_created' do+ before do+ FactoryBot.create(:work_package, project: project)+ end++ it_behaves_like 'sends notification'+ end++ context 'work_package_updated' do+ before do+ work_package.add_journal(author)+ work_package.subject = 'A change to the issue'+ work_package.save!(validate: false)+ end++ it_behaves_like 'sends notification'+ end++ context 'work_package_note_added' do+ before do+ work_package.add_journal(author, 'This update has a note')+ work_package.save!(validate: false)+ end++ 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 notificationdiff --git a/spec_legacy/functional/wiki_controller_spec.rb b/spec_legacy/functional/wiki_controller_spec.rbindex 9969326b355..ad532f339a7 100644--- a/spec_legacy/functional/wiki_controller_spec.rb+++ b/spec_legacy/functional/wiki_controller_spec.rb@@ -119,34 +119,6 @@ describe WikiController, type: :controller doassert_equal 'testfile.txt', page.attachments.first.filenameend- it 'should update page' do- page = Wiki.find(1).pages.find_by(title: 'Another page')- page.content.recreate_initial_journal!-- session[:user_id] = 2- assert_no_difference 'WikiPage.count' do- assert_no_difference 'WikiContent.count' do- assert_difference 'Journal.count' do- put :update, params: { project_id: 1,- id: 'Another page',- content: {- comments: 'my comments',- text: 'edited',- lock_version: 1,- page: { title: 'Another page',- parent_id: '' } } }- end- end- end- assert_redirected_to '/projects/ecookbook/wiki/another-page'-- page.reload- assert_equal 'edited', page.content.text- assert_equal 'edited', page.content.text- assert_equal page.content.journals.map(&:version).max, page.content.version- assert_equal 'my comments', page.content.last_journal.notes- end-it 'should update page with failure' dosession[:user_id] = 2assert_no_difference 'WikiPage.count' dodiff --git a/spec_legacy/unit/journal_spec.rb b/spec_legacy/unit/journal_spec.rbdeleted file mode 100644index f646cf4a4d2..00000000000--- a/spec_legacy/unit/journal_spec.rb+++ /dev/null@@ -1,70 +0,0 @@-#-- encoding: UTF-8--#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2020 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-2017 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_relative '../legacy_spec_helper'--describe Journal,- type: :model,- with_settings: { notified_events: %w(work_package_added work_package_updated) } do- fixtures :all-- specify 'creating a journal should update the updated_on value of the parent record (touch)' do- @user = FactoryBot.create(:user)- @project = FactoryBot.create(:project)- @issue = FactoryBot.create(:work_package, project: @project)- start = @issue.updated_at- sleep(1) # TODO: massive hack to make sure the timestamps are different. switch to timecop later-- assert_difference('Journal.count') do- @issue.add_journal(@user, 'A note')- @issue.save- end-- refute_equal start, @issue.reload.updated_at- end-- specify 'accessing #journaled on a Journal should not error (parent class)' do- journal = Journal.new- expect {- assert_equal nil, journal.journable- }.not_to raise_error- end-- specify 'setting journal fields through the journaled object for creation' do- @issue = FactoryBot.create(:work_package)-- @issue.add_journal @issue.author, 'Test setting fields on Journal from Issue'- assert_difference('Journal.count') do- assert @issue.save- end-- assert_equal 'Test setting fields on Journal from Issue', @issue.last_journal.notes- assert_equal @issue.author, @issue.last_journal.user- end-enddiff --git a/spec_legacy/unit/mail_handler_spec.rb b/spec_legacy/unit/mail_handler_spec.rbindex 5dfe8e5c99c..99559a0a82e 100644--- a/spec_legacy/unit/mail_handler_spec.rb+++ b/spec_legacy/unit/mail_handler_spec.rb@@ -303,8 +303,8 @@ describe MailHandler, type: :model dospecify 'reply to issue update (Journal) by message_id' doJournal.delete_all- issue = WorkPackage.find(2)- j = FactoryBot.create :work_package_journal, id: 3, journable_id: issue.id+ FactoryBot.create :work_package_journal, id: 3, version: 1, journable_id: 2+ JournalVersion.create(journable_type: 'WorkPackage', journable_id: 2, version: 1)journal = submit_email('ticket_reply_by_message_id.eml')assert journal.data.is_a?(Journal::WorkPackageJournal), "Email was a #{journal.data.class}"assert_equal User.find_by_login('jsmith'), journal.user@@ -314,7 +314,6 @@ describe MailHandler, type: :model doendit 'should add work package note with attribute changes' do- WorkPackage.find(2).recreate_initial_journal!# This email contains: 'Status: Resolved'journal = submit_email('ticket_reply_with_status.eml')assert journal.data.is_a?(Journal::WorkPackageJournal)@@ -334,7 +333,6 @@ describe MailHandler, type: :model doendit 'should add work package note should send email notification' do- WorkPackage.find(2).recreate_initial_journal!journal = submit_email('ticket_reply.eml')assert journal.is_a?(Journal)assert_equal 3, ActionMailer::Base.deliveries.sizediff --git a/spec_legacy/unit/wiki_content_spec.rb b/spec_legacy/unit/wiki_content_spec.rbindex 8172e831846..7e94b753b00 100644--- a/spec_legacy/unit/wiki_content_spec.rb+++ b/spec_legacy/unit/wiki_content_spec.rb@@ -63,12 +63,10 @@ describe WikiContent, type: :model doendit 'should fetch history' do- wiki_content_journal = FactoryBot.build(:wiki_content_journal,- journable_id: @page.content.id)- wiki_content_journal.data.page_id = @page.id- wiki_content_journal.data.text = ''+ wiki_content_journal = FactoryBot.create(:wiki_content_journal,+ journable: @page.content)+ wiki_content_journal.data.update_attributes(page_id: @page.id, text: '')- @page.content.journals << wiki_content_journalassert [email protected]?@page.content.journals.each do |journal|assert_kind_of String, journal.data.text