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
fixes using the appropriate timestamp throughout the Journals::CreateService
ulferts24c395900387
diff --git a/app/services/journals/create_service.rb b/app/services/journals/create_service.rbindex a49492ff464..bc03e43c96b 100644--- a/app/services/journals/create_service.rb+++ b/app/services/journals/create_service.rb@@ -58,7 +58,6 @@ module Journalsif journalreload_journals- touch_journable(journal)endServiceResult.success result: journal@@ -110,14 +109,15 @@ module Journals# attachment and custom value information is removed. The journal itself is kept and will later on have its# updated_at and possibly its notes property updated.#- # The next 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 next CTEs (`max_journals`) responsibility is to fetch the latest journal and have that available for later queries+ # (i.e. when determining the latest state of the journable, when getting the current version number and when+ # comparing the timestamps of the last journalization time and the work package's updated_at time).#- # The next 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 three exceptions to this check are- # that if a note is provided, the predecessor has a different cause than the new journal would have or a predecessor- # is replaced, 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 next CTE (`changes`) determines whether a change as occurred so that a new journal needs to be created. The subsequent+ # CTEs, which are inserting new data, will only do so if the changes CTE returns an entry. The only three exceptions+ # to this check are that if a note is provided, the predecessor has a different cause than the new journal would have+ # or a predecessor is replaced, 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@@ -129,17 +129,21 @@ module Journals# without intending to.## Only if a change has been identified (or if a note/cause/predecessor is present) is a journal inserted by the- # next CTE (`insert_journal`). Its creation timestamp will be the 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. In case a predecessor is aggregated, an update of the already persisted, and- # stripped of its data, journal is carried out.+ # `inserted_journal` CTE. Its creation timestamp will be the updated_at value of the journable as this is the+ # logical creation time. If a note or a cause is present, however, the current time is taken as it signifies an action in+ # itself and there might not be a change to the journable at all. To account for this case, in which the updated_at of the+ # journable will be equal to the updated_at of the most recent journal (so the one before the current run),+ # the statement_timestamp() function is used to set a timestamp both on the journable (`touch_journable`) and+ # have that available in the later stages of the SQL as the authoritative time used whenever updated/created_at or+ # validity timestamps need to be touched (`fetch_time`).#- # 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.+ # In case a predecessor is aggregated the `inserted_journal`, does not insert in fact but rather it updates the already+ # persisted, and stripped of its data, journal.+ #+ # All cases (having a change, a note or a cause) 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.@@ -167,12 +171,16 @@ module Journals#{select_max_journal_sql(predecessor)}), changes AS (#{select_changed_sql}+ ), touch_journable AS (+ #{touch_journable_sql(predecessor, notes, cause)}+ ), fetch_time AS (+ #{fetch_time_sql}), insert_data AS (- #{insert_data_sql(predecessor, notes, cause)}- ), inserted_journal AS (- #{update_or_insert_journal_sql(predecessor, notes, cause)}+ #{insert_data_sql(notes, cause)}), update_predecessor AS (#{update_predecessor_sql(predecessor, notes, cause)}+ ), inserted_journal AS (+ #{update_or_insert_journal_sql(predecessor, notes, cause)}), insert_attachable AS (#{insert_attachable_sql}), insert_customizable AS (@@ -240,7 +248,7 @@ module JournalsjournalsSETnotes = :notes,- updated_at = #{timestamp_sql},+ updated_at = (SELECT updated_at FROM fetch_time),data_id = insert_data.id,cause = :causeFROM insert_data@@ -277,12 +285,12 @@ module JournalsCOALESCE(max_journals.version, 0) + 1,:user_id,:notes,- #{journal_timestamp_sql(notes, ':created_at')},- #{journal_timestamp_sql(notes, ':updated_at')},+ (SELECT updated_at FROM fetch_time),+ (SELECT updated_at FROM fetch_time),insert_data.id,:data_type,:cause,- tstzrange(#{journal_timestamp_sql(notes, ':created_at')}, NULL)+ tstzrange((SELECT updated_at FROM fetch_time), NULL)FROM max_journals, insert_dataRETURNING *SQL@@ -293,12 +301,10 @@ module Journalsjournable_id: journable.id,journable_type:,user_id: user.id,- created_at: journable_timestamp,- updated_at: journable_timestamp,data_type: journable.class.journal_class.name)end- def insert_data_sql(predecessor, notes, cause)+ def insert_data_sql(notes, cause)data_sql = <<~SQLINSERT INTO#{data_table_name} (@@ -310,7 +316,7 @@ module Journals#{journable_data_sql_addition}WHERE#{journable_table_name}.id = :journable_id- #{only_on_changed_or_forced_condition_sql(predecessor, notes, cause)}+ #{only_on_changed_or_forced_condition_sql(notes, cause)}RETURNING *SQL@@ -372,23 +378,71 @@ module Journalsjournable_class_name:)end+ # Updates the updated_at timestamp of the journable.+ # That is only carried out if the journable doesn't already have a newer timestamp than the most recent journal.+ # Most recent in this case can mean one of two things:+ # * if there is a predecessor we are aggregating with, it is that predecessor+ # * otherwise, the most recent journal that we are not aggregating with.+ # Whenever an attribute is updated on the journable before creating the journal, the udpated_at timestamp+ # will already have been increased so nothing needs to be done.+ # But if any of the associated data is updated or if only a cause or note is added, the journable would+ # otherwise not have receive an updated timestamp.+ # There is a special case if the updated_at of the journable is itself updated. In such a case, that value is used.+ def touch_journable_sql(predecessor, notes, cause)+ if journable.class.aaj_options[:timestamp].to_sym == :updated_at+ update_sql = <<~SQL+ UPDATE+ #{journable_table_name}+ SET+ updated_at = COALESCE(:update_timestamp, statement_timestamp())+ WHERE+ id = :id+ #{only_on_changed_or_forced_condition_sql(notes, cause)}+ AND NOT updated_at > COALESCE(:predecessor_timestamp, (SELECT updated_at FROM max_journals))+ RETURNING updated_at+ SQL++ sanitize(update_sql,+ update_timestamp: journable.updated_at_previously_changed? ? journable.updated_at : nil,+ predecessor_timestamp: predecessor&.updated_at,+ id: journable.id)+ else+ <<~SQL+ SELECT NULL::timestamp with time zone AS updated_at+ SQL+ end+ end++ # Fetches the timestamp to be used by all subsequent SQL statements e.g. for+ # * setting the created_at and updated_at timestamps of the newly created journal+ # * setting the updated_at timestamp on an updated (aggregated with) journal+ # * setting the validity_period (upper bound) of the preceding journal.+ def fetch_time_sql+ update_sql = <<~SQL+ SELECT COALESCE((SELECT updated_at FROM touch_journable), :journable_timestamp) AS updated_at+ SQL++ sanitize(update_sql,+ journable_timestamp:)+ end+# Sets the validity_period's upper boundary of the preceding journal to the created_at timestamp of the inserted journal.- # If there is a predecessor (meaning we are aggregating/updating an existing journal), nothing is done.+ # The upper bound set is not included.+ # If there is a predecessor (meaning we are aggregating/updating an existing journal), nothing is done since+ # in that case the preceding journal is the one we are currently aggregating with so it will still remain+ # the most recent one.def update_predecessor_sql(predecessor, notes, cause)return "SELECT 1" if predecessor.present?- update_sql = <<~SQL+ <<~SQLUPDATEjournalsSET- validity_period = tstzrange(journals.created_at, :created_at)+ validity_period = tstzrange(lower(validity_period), (SELECT updated_at FROM fetch_time), '[)')WHEREid = (SELECT id from max_journals)- #{only_on_changed_or_forced_condition_sql(predecessor, notes, cause)}+ #{only_on_changed_or_forced_condition_sql(notes, cause)}SQL-- sanitize(update_sql,- created_at: journable_timestamp)enddef select_max_journal_sql(predecessor)@@ -396,6 +450,7 @@ module JournalsSELECT:journable_id journable_id,:journable_type journable_type,+ updated_at,COALESCE(journals.version, fallback.version) AS version,COALESCE(journals.id, 0) id,COALESCE(journals.data_id, 0) data_id@@ -557,8 +612,8 @@ module Journalsdata_changes.join(' OR ')end- def only_on_changed_or_forced_condition_sql(predecessor, notes, cause)- if notes.blank? && cause.blank? && predecessor.nil?+ def only_on_changed_or_forced_condition_sql(notes, cause)+ if notes.blank? && cause.blank?"AND EXISTS (SELECT * FROM changes)"else""@@ -604,25 +659,11 @@ module Journals"REGEXP_REPLACE(COALESCE(#{column},''), '\\r\\n', '\n', 'g')"end- def journal_timestamp_sql(notes, attribute)- if notes.blank? && journable_timestamp- attribute- else- timestamp_sql- end- end-def cause_sql(cause)# Using the same encoder mechanism that ActiveRecord uses for json/jsonb columnsActiveSupport::JSON.encode(cause || {})end- def timestamp_sql- # Use the timestamp of the statement, not now() or statement_timestamp- # as they always return the same value of the start of transaction- "statement_timestamp() AT TIME ZONE 'utc'"- 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.@@ -630,17 +671,6 @@ module Journalsjournable.journals.reload if journable.journals.loaded?end- def touch_journable(journal)- return if journal.notes.blank? && journal.cause.blank?-- # 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.updated_at }- journable.update_columns(timestamps) if timestamps.any?- end-def aggregatable?(predecessor, notes, cause)predecessor.present? &&aggregation_active? &&diff --git a/db/migrate/20230608151123_add_validity_period_to_journals.rb b/db/migrate/20230608151123_add_validity_period_to_journals.rbindex cef0e7f3754..0b6ce2e5f93 100644--- a/db/migrate/20230608151123_add_validity_period_to_journals.rb+++ b/db/migrate/20230608151123_add_validity_period_to_journals.rb@@ -11,7 +11,9 @@ class AddValidityPeriodToJournals < ActiveRecord::Migration[7.0]endend- change_column_null :journals, :validity_period, false+ add_check_constraint :journals,+ 'NOT isempty(validity_period) AND validity_period IS NOT NULL',+ name: "journals_validity_period_not_empty"enddef fix_all_journal_timestampsdiff --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 aa1c126d6d0..4274c6634d3 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@@ -91,6 +91,10 @@ RSpec.describe WorkPackage docontext 'when nothing is changed' doit { expect { work_package.save! }.not_to change(Journal, :count) }++ it 'does not update the updated_at time of the work package' do+ expect { work_package.save! }.not_to change(work_package, :updated_at)+ endendcontext 'for different newlines', with_settings: { journal_aggregation_time_minutes: 0 } do@@ -129,24 +133,17 @@ RSpec.describe WorkPackage doendcontext 'when there is a legacy journal containing non-escaped newlines' do- let!(:work_package_journal1) do- create(:work_package_journal,- journable_id: work_package1.id,- version: 2,- data: build(:journal_work_package_journal,- description:))- end- let!(:work_package_journal2) do- create(:work_package_journal,- journable_id: work_package1.id,- version: 3,- data: build(:journal_work_package_journal,- description: changed_description))+ let!(:work_package1) do+ create(:work_package,+ journals: {+ 5.minutes.ago => { description: },+ 3.minutes.ago => { description: changed_description }+ })end- subject { work_package1.last_journal.details }-- it { is_expected.not_to have_key :description }+ it 'does not track the change to the newline characters' do+ expect(work_package1.reload.last_journal.details).not_to have_key :description+ endendend@@ -435,6 +432,7 @@ RSpec.describe WorkPackage dosubject dowork_package.add_journal(user: User.current, notes: 'some notes')work_package.save+ work_packageendit 'does not create a new journal entry' do@@ -442,8 +440,11 @@ RSpec.describe WorkPackage doendit 'has the timestamp of the work package update time for updated_at' do- subject- expect(work_package.last_journal.updated_at).to eql(work_package.updated_at)+ expect(subject.last_journal.updated_at).to eql(work_package.reload.updated_at)+ end++ it 'updates the updated_at time of the work package' do+ expect { subject.reload }.to change(work_package, :updated_at)endit 'stores the note with the existing journal entry' do@@ -456,6 +457,7 @@ RSpec.describe WorkPackage dowork_package.add_journal(user: User.current, notes: 'some notes')work_package.subject = 'blubs'work_package.save+ work_packageendit 'does not create a new journal entry' do@@ -463,8 +465,11 @@ RSpec.describe WorkPackage doendit 'has the timestamp of the work package update time for updated_at' do- subject- expect(work_package.last_journal.updated_at).to eql(work_package.updated_at)+ expect(subject.last_journal.updated_at).to eql(work_package.reload.updated_at)+ end++ it 'updates the updated_at time of the work package' do+ expect { subject.reload }.to change(work_package, :updated_at)endit 'stores the note with the existing journal entry' do@@ -477,16 +482,24 @@ RSpec.describe WorkPackage dowork_package.add_journal(user: User.current,cause: {- type: 'work_package_predecessor_changed_times',+ type: 'some cause',work_package_id: 42})work_package.save+ work_package+ end++ it 'has the cause logged in the last journal' do+ expect(subject.last_journal.cause).to eql({ 'type' => 'some cause', 'work_package_id' => 42 })endit 'has the timestamp of the work package update time for created_at' do- subject- expect(work_package.last_journal.updated_at).to eql(work_package.updated_at)+ expect(subject.last_journal.updated_at).to eql(work_package.reload.updated_at)+ end++ it 'updates the updated_at time of the work package' do+ expect { subject.reload }.to change(work_package, :updated_at)endit 'does create a new journal entry' do@@ -506,6 +519,7 @@ RSpec.describe WorkPackage do)work_package.subject = 'blubs'work_package.save+ work_packageendit 'has the timestamp of the work package update time for created_at' do@@ -516,6 +530,12 @@ RSpec.describe WorkPackage doexpect { subject }.to change(work_package, :last_journal)end+ it 'updates the updated_at time of the work package' do+ updated_at_before = work_package.updated_at++ expect(subject.reload.updated_at).not_to eql(updated_at_before)+ end+it 'stores the cause and note with the existing journal entry' dosubject@@ -736,11 +756,16 @@ RSpec.describe WorkPackage doendcontext 'when updated after aggregation timeout expired', with_settings: { journal_aggregation_time_minutes: 1 } do+ let(:last_update_time) { 2.minutes.ago }+subject(:journals) { work_package.journals }before do- work_package.last_journal.update_columns(created_at: 2.minutes.ago,- updated_at: 2.minutes.ago)+ work_package.last_journal.update_columns(created_at: last_update_time,+ updated_at: last_update_time,+ validity_period: last_update_time..Float::INFINITY)+ work_package.update_columns(created_at: last_update_time,+ updated_at: last_update_time)work_package.status = build(:status)work_package.save!