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
[#54377] Embedded work package attributes in PDF export
as-op8752302407a1
diff --git a/Gemfile b/Gemfileindex ca1db68f251..9882d01a33d 100644--- a/Gemfile+++ b/Gemfile@@ -157,9 +157,11 @@ gem "structured_warnings", "~> 0.4.0"# don't require by default, instead load on-demand when actually configuredgem "airbrake", "~> 13.0.0", require: false+gem "markly", "~> 0.10"gem "md_to_pdf", git: "https://github.com/opf/md-to-pdf", ref: "8f14736a88ad0064d2a97be108fe7061ffbcee91"gem "prawn", "~> 2.4"gem "ttfunk", "~> 1.7.0" # remove after https://github.com/prawnpdf/prawn/issues/1346 resolved.+# prawn implicitly depends on matrix gem no longer in ruby core with 3.1gem "matrix", "~> 0.4.2"diff --git a/Gemfile.lock b/Gemfile.lockindex fac96af70f9..d8c3ea81140 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -1233,6 +1233,7 @@ DEPENDENCIESlograge (~> 0.14.0)lookbook (~> 2.3.0)mail (= 2.8.1)+ markly (~> 0.10)matrix (~> 0.4.2)md_to_pdf!meta-tags (~> 2.21.0)diff --git a/app/models/exports/formatters/custom_field.rb b/app/models/exports/formatters/custom_field.rbindex 5815fb2a18f..045b197bb9f 100644--- a/app/models/exports/formatters/custom_field.rb+++ b/app/models/exports/formatters/custom_field.rb@@ -24,7 +24,7 @@ module Exportscase custom_field.field_formatwhen "bool"value = object.typed_custom_value_for(custom_field)- value == nil ? false : value+ value ? I18n.t(:general_text_Yes) : I18n.t(:general_text_No)when "text"object.typed_custom_value_for(custom_field)elsediff --git a/app/models/projects/exports/formatters/active.rb b/app/models/projects/exports/formatters/active.rbnew file mode 100644index 00000000000..81980c07a75--- /dev/null+++ b/app/models/projects/exports/formatters/active.rb@@ -0,0 +1,42 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2024 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#+++module Projects::Exports+ module Formatters+ class Active < ::Exports::Formatters::Default+ def self.apply?(attribute, export_format)+ export_format == :pdf && %i[active].include?(attribute.to_sym)+ end++ ##+ # Takes a project and returns the localized status code+ def format(project, **)+ project.active ? I18n.t(:general_text_Yes) : I18n.t(:general_text_No)+ end+ end+ end+enddiff --git a/app/models/projects/exports/formatters/public.rb b/app/models/projects/exports/formatters/public.rbnew file mode 100644index 00000000000..40a6e85d1f0--- /dev/null+++ b/app/models/projects/exports/formatters/public.rb@@ -0,0 +1,42 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2024 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#+++module Projects::Exports+ module Formatters+ class Public < ::Exports::Formatters::Default+ def self.apply?(attribute, export_format)+ export_format == :pdf && %i[public].include?(attribute.to_sym)+ end++ ##+ # Takes a project and returns the localized status code+ def format(project, **)+ project.active ? I18n.t(:general_text_Yes) : I18n.t(:general_text_No)+ end+ end+ end+enddiff --git a/app/models/work_package/exports/macros/attributes.rb b/app/models/work_package/exports/macros/attributes.rbnew file mode 100644index 00000000000..6ce70aee38a--- /dev/null+++ b/app/models/work_package/exports/macros/attributes.rb@@ -0,0 +1,168 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2024 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#+++module WorkPackage::Exports+ module Macros+ # OpenProject attribute macros syntax+ # Examples:+ # workPackageLabel:1234:subject # Outputs work package label attribute "Subject" + help text+ # workPackageValue:1234:subject # Outputs the actual subject of #1234+ #+ # projectLabel:statusExplanation # Outputs current project label attribute "Status description" + help text+ # projectValue:statusExplanation # Outputs current project value for "Status description"+ class Attributes < OpenProject::TextFormatting::Matchers::RegexMatcher+ DISABLED_PROJECT_RICH_TEXT_FIELDS = %i[description status_explanation status_description].freeze+ DISABLED_WORK_PACKAGE_RICH_TEXT_FIELDS = %i[description].freeze++ def self.regexp+ %r{+ (\w+)(Label|Value) # The model type we try to reference+ (?::(?:([^"\s]+)|"([^"]+)"))? # Optional: An ID or subject reference+ (?::([^"\s.]+|"([^".]+)")) # The attribute name we're trying to reference+ }x+ end++ ##+ # Faster inclusion check before the regex is being applied+ def self.applicable?(content)+ content.include?("Label:") || content.include?("Value:")+ end++ def self.process_match(match, _matched_string, context)+ context => { user:, work_package: }+ type = match[2].downcase+ model_s = match[1]+ id = match[4] || match[3]+ attribute = match[6] || match[5]+ resolve_match(type, model_s, id, attribute, work_package, user)+ end++ def self.resolve_match(type, model_s, id, attribute, work_package, user)+ if model_s == "workPackage"+ resolve_work_package_match(id || work_package.id, type, attribute, user)+ elsif model_s == "project"+ resolve_project_match(id || work_package.project.id, type, attribute, user)+ else+ "[Error: Invalid attribute macro: #{model_s}]"+ end+ end++ def self.resolve_label_work_package(attribute)+ resolve_label(WorkPackage, attribute)+ end++ def self.resolve_label_project(attribute)+ resolve_label(Project, attribute)+ end++ def self.resolve_label(model, attribute)+ model.human_attribute_name(+ ::API::Utilities::PropertyNameConverter.to_ar_name(attribute.to_sym, context: model.new)+ )+ end++ def self.resolve_work_package_match(id, type, attribute, user)+ return resolve_label_work_package(attribute) if type == "label"+ return "[Error: Invalid attribute macro: #{type}]" unless type == "value"++ work_package = WorkPackage.find_by(id:)+ if work_package.nil? || !user.allowed_in_project?(:view_work_packages, work_package.project)+ return "[Error: #{WorkPackage.name} #{id} not found}]"+ end++ resolve_value_work_package(work_package, attribute)+ end++ def self.resolve_project_match(id, type, attribute, user)+ return resolve_label_project(attribute) if type == "label"+ return "[Error: Invalid attribute macro: #{type}]" unless type == "value"++ project = Project.find_by(id:)+ if project.nil? || !user.allowed_in_project?(:view_project, project)+ return "[Error: #{Project.name} #{id} not found}]"+ end++ resolve_value_project(project, attribute)+ end++ def self.escape_tags(value)+ # only disable html tags, but do not replace html entities+ value.to_s.gsub("<", "<").gsub(">", ">")+ end++ def self.resolve_value_project(project, attribute)+ cf = CustomField.find_by(name: attribute, type: "ProjectCustomField")+ if cf.nil?+ ar_name = ::API::Utilities::PropertyNameConverter.to_ar_name(attribute.to_sym, context: project)+ else+ ar_name = "cf_#{cf.id}"+ # currently we do not support embedding rich text fields: long text custom fields+ return "[Rich text embedding currently not supported in export]" if cf.formattable?++ # TODO: Is the user allowed to see this custom field/"project attribute"?+ end++ # currently we do not support embedding rich text field: e.g. projectValue:1234:description+ if DISABLED_PROJECT_RICH_TEXT_FIELDS.include?(ar_name.to_sym)+ return "[Rich text embedding currently not supported in export]"++ end++ format_attribute_value(ar_name, Project, project)+ end++ def self.resolve_value_work_package(work_package, attribute)+ cf = CustomField.find_by(name: attribute, type: "WorkPackageCustomField")+ if cf.nil?+ ar_name = ::API::Utilities::PropertyNameConverter.to_ar_name(attribute.to_sym, context: work_package)+ else+ ar_name = "cf_#{cf.id}"+ # currently we do not support embedding rich text fields: long text custom fields+ return "[Rich text embedding currently not supported in export]" if cf.formattable?++ # TODO: Are there access restrictions on work_package custom fields?+ end++ # currently we do not support embedding rich text field: workPackageValue:1234:description+ if DISABLED_WORK_PACKAGE_RICH_TEXT_FIELDS.include?(ar_name.to_sym)+ return "[Rich text embedding currently not supported in export]"++ end++ format_attribute_value(ar_name, WorkPackage, work_package)+ end++ def self.format_attribute_value(ar_name, model, obj)+ formatter = Exports::Register.formatter_for(model, ar_name, :pdf)+ value = formatter.format(obj)+ # important NOT to return empty string as this could change meaning of markdown+ # e.g. **to_be_replaced** could be rendered as **** (horizontal line and a *)+ value.blank? ? " " : escape_tags(value)+ end+ end+ end+enddiff --git a/app/models/work_package/pdf_export/markdown_field.rb b/app/models/work_package/pdf_export/markdown_field.rbindex 963396d3006..b3a6447b8a9 100644--- a/app/models/work_package/pdf_export/markdown_field.rb+++ b/app/models/work_package/pdf_export/markdown_field.rb@@ -28,6 +28,7 @@module WorkPackage::PDFExport::MarkdownFieldinclude WorkPackage::PDFExport::Markdown+ PREFORMATTED_BLOCKS = %w(pre code).freezedef write_markdown_field!(work_package, markdown, label)return if markdown.blank?@@ -37,7 +38,52 @@ module WorkPackage::PDFExport::MarkdownFieldpdf.formatted_text([styles.wp_markdown_label.merge({ text: label })])endwith_margin(styles.wp_markdown_margins) do- write_markdown! work_package, markdown+ write_markdown! work_package, apply_markdown_field_macros(markdown)+ end+ end++ private++ def apply_markdown_field_macros(markdown)+ apply_macros(markdown, WorkPackage::Exports::Macros::Attributes)+ end++ def apply_macros(markdown, formatter)+ return markdown unless formatter.applicable?(markdown)++ document = Markly.parse(markdown)+ document.walk do |node|+ if node.type == :html+ node.string_content = apply_macro_html(node.string_content, work_package, formatter)+ elsif node.type == :text+ node.string_content = apply_macro_text(node.string_content, work_package, formatter)+ end+ end+ document.to_markdown+ end++ def apply_macro_text(text, work_package, formatter)+ return text unless formatter.applicable?(text)++ text.gsub!(formatter.regexp) do |matched_string|+ matchdata = Regexp.last_match+ formatter.process_match(matchdata, matched_string, { user: User.current, work_package: })+ end+ end++ def apply_macro_html(html, work_package, formatter)+ return html unless formatter.applicable?(html)++ doc = Nokogiri::HTML.fragment(html)+ apply_macro_html_node(doc, work_package, formatter)+ doc.to_html+ end++ def apply_macro_html_node(node, work_package, formatter)+ if node.text?+ node.content = apply_macro_text(node.content, work_package, formatter)+ elsif PREFORMATTED_BLOCKS.exclude?(node.name)+ node.children.each { |child| apply_macro_html_node(child, work_package, formatter) }endendenddiff --git a/app/models/work_package/pdf_export/work_package_detail.rb b/app/models/work_package/pdf_export/work_package_detail.rbindex 2d4aae33e8e..2f575c12bdc 100644--- a/app/models/work_package/pdf_export/work_package_detail.rb+++ b/app/models/work_package/pdf_export/work_package_detail.rb@@ -143,7 +143,7 @@ module WorkPackage::PDFExport::WorkPackageDetailreturn [] unless cf.is_for_all? || work_package.project.work_package_custom_field_ids.include?(cf.id)- return [{ label: cf.name || form_key, name: form_key }]+ return [{ label: cf.name || form_key, name: form_key.to_s.sub("custom_field_", "cf_") }]endif form_key == :datediff --git a/config/initializers/export_formats.rb b/config/initializers/export_formats.rbindex f95759cdf16..26f2092b412 100644--- a/config/initializers/export_formats.rb+++ b/config/initializers/export_formats.rb@@ -20,6 +20,8 @@ Rails.application.configure do |application|formatter Project, Exports::Formatters::CustomFieldformatter Project, Projects::Exports::Formatters::Statusformatter Project, Projects::Exports::Formatters::Description+ formatter Project, Projects::Exports::Formatters::Public+ formatter Project, Projects::Exports::Formatters::Activeendendenddiff --git a/spec/models/work_packages/pdf_export/work_package_to_pdf_spec.rb b/spec/models/work_packages/pdf_export/work_package_to_pdf_spec.rbindex f6fd8f60c8d..4491fbbd77e 100644--- a/spec/models/work_packages/pdf_export/work_package_to_pdf_spec.rb+++ b/spec/models/work_packages/pdf_export/work_package_to_pdf_spec.rb@@ -36,10 +36,17 @@ RSpec.describe WorkPackage::PDFExport::WorkPackageToPdf dot.attribute_groups.first.attributes.push(cf_disabled_in_project.attribute_name, cf_long_text.attribute_name)endend+ let(:parent_project) do+ create(:project, name: "Parent project")+ endlet(:project) docreate(:project,name: "Foo Bla. Report No. 4/2021 with/for Case 42",types: [type],+ public: true,+ status_code: "on_track",+ active: true,+ parent: parent_project,work_package_custom_fields: [cf_long_text, cf_disabled_in_project, cf_global_bool],work_package_custom_field_ids: [cf_long_text.id, cf_global_bool.id]) # cf_disabled_in_project.id is disabledend@@ -47,11 +54,15 @@ RSpec.describe WorkPackage::PDFExport::WorkPackageToPdf docreate(:user,member_with_permissions: { project => %w[view_work_packages export_work_packages] })end+ let(:category) { create(:category, project:, name: "Demo") }+ let(:version) { create(:version, project:) }let(:export_time) { DateTime.new(2023, 6, 30, 23, 59) }let(:export_time_formatted) { format_time(export_time, true) }let(:image_path) { Rails.root.join("spec/fixtures/files/image.png") }+ let(:priority) { create(:priority_normal) }let(:image_attachment) { Attachment.new author: user, file: File.open(image_path) }let(:attachments) { [image_attachment] }+ let(:cf_long_text_description) { "foo" }let(:cf_long_text) { create(:issue_custom_field, :text, name: "LongText") }let!(:cf_disabled_in_project) do# NOT enabled by project.work_package_custom_field_ids => NOT in PDF@@ -65,8 +76,11 @@ RSpec.describe WorkPackage::PDFExport::WorkPackageToPdf dodefault_value: true)end- let(:work_package) do- description = <<~DESCRIPTION+ let(:status) { create(:status, name: "random", is_default: true) }+ let!(:parent_work_package) { create(:work_package, type:, subject: "Parent wp") }++ let(:description) do+ <<~DESCRIPTION**Lorem** _ipsum_ ~~dolor~~ `sit` [amet](https://example.com/), consetetur sadipscing elitr.<mention data-text="@OpenProject Admin">@OpenProject Admin</mention>@@ -80,14 +94,32 @@ RSpec.describe WorkPackage::PDFExport::WorkPackageToPdf do</p><p><unknown-tag>Foo</unknown-tag></p>DESCRIPTION+ end+ let(:work_package) docreate(:work_package,+ id: 1,project:,type:,subject: "Work package 1",+ start_date: "2024-05-30",+ due_date: "2024-05-30",+ created_at: export_time,+ updated_at: export_time,+ author: user,+ assigned_to: user,+ responsible: user,story_points: 1,+ estimated_hours: 10,+ done_ratio: 25,+ remaining_hours: 9,+ parent: parent_work_package,+ priority:,+ version:,+ status:,+ category:,description:,custom_values: {- cf_long_text.id => "foo",+ cf_long_text.id => cf_long_text_description,cf_disabled_in_project.id => "6.25",cf_global_bool.id => true}).tap do |wp|@@ -109,6 +141,15 @@ RSpec.describe WorkPackage::PDFExport::WorkPackageToPdf doexport.export!endend+ let(:expected_details) do+ exporter.send(:attributes_data_by_wp, work_package)+ .flat_map do |item|+ value = get_column_value(item[:name])+ result = [item[:label].upcase]+ result << value if value.present?+ result+ end+ enddef get_column_value(column_name)formatter = Exports::Register.formatter_for(WorkPackage, column_name, :pdf)@@ -126,18 +167,10 @@ RSpec.describe WorkPackage::PDFExport::WorkPackageToPdf dodescribe "with a request for a PDF" doit "contains correct data" do- details = exporter.send(:attributes_data_by_wp, work_package)- .flat_map do |item|- value = get_column_value(item[:name])- result = [item[:label].upcase]- result << value if value.present?- result- end- # Joining the results for comparison since word wrapping leads to a different array for the same content- result = pdf[:strings].join(" ")+ result = pdf[:strings]expected_result = ["#{type.name} ##{work_package.id} - #{work_package.subject}",- *details,+ *expected_details,label_title(:description),"Lorem", " ", "ipsum", " ", "dolor", " ", "sit", " ","amet", ", consetetur sadipscing elitr.", " ", "@OpenProject Admin",@@ -145,10 +178,97 @@ RSpec.describe WorkPackage::PDFExport::WorkPackageToPdf do"Foo","LongText", "foo","1", export_time_formatted, project.name- ].join(" ")- expect(result).to eq(expected_result)- expect(result).not_to include("DisabledCustomField")+ ].flatten+ # Joining the results for comparison since word wrapping leads to a different array for the same content+ expect(result.join(" ")).to eq(expected_result.join(" "))+ expect(result.join(" ")).not_to include("DisabledCustomField")expect(pdf[:images].length).to eq(2)end++ describe "with embedded attributes" do+ let(:supported_work_package_embeds) do+ [+ ["assignee", user.name],+ ["author", user.name],+ ["category", category.name],+ ["createdAt", export_time_formatted],+ ["updatedAt", export_time_formatted],+ ["estimatedTime", "10.0 h"],+ ["remainingTime", "9.0 h"],+ ["version", version.name],+ ["responsible", user.name],+ ["dueDate", "05/30/2024"],+ ["spentTime", "0.0 h"],+ ["startDate", "05/30/2024"],+ ["parent", "#{type.name} ##{parent_work_package.id}: #{parent_work_package.name}"],+ ["priority", priority.name],+ ["project", project.name],+ ["status", status.name],+ ["subject", "Work package 1"],+ ["type", type.name],+ ["description", "[Rich text embedding currently not supported in export]"]+ ]+ end+ let(:supported_project_embeds) do+ [+ ["active", "Yes"],+ ["description", "[Rich text embedding currently not supported in export]"],+ ["identifier", project.identifier],+ ["name", project.name],+ ["status", I18n.t("activerecord.attributes.project.status_codes.#{project.status_code}")],+ ["statusExplanation", "[Rich text embedding currently not supported in export]"],+ ["parent", parent_project.name],+ ["public", "Yes"]+ ]+ end+ let(:supported_work_package_embeds_table) do+ supported_work_package_embeds.map do |embed|+ "<tr><td>workPackageLabel:#{embed[0]}</td><td>workPackageValue:#{embed[0]}</td></tr>"+ end+ end+ let(:description) do+ <<~DESCRIPTION+ ## Work package attributes and labels+ <table><tbody>#{supported_work_package_embeds_table}</tbody></table>+ DESCRIPTION+ end+ let(:supported_project_embeds_table) do+ supported_project_embeds.map do |embed|+ "<tr><td>projectLabel:#{embed[0]}</td><td>projectValue:#{embed[0]}</td></tr>"+ end+ end+ let(:cf_long_text_description) do+ <<~DESCRIPTION+ ## Project attributes and labels+ <table><tbody>#{supported_project_embeds_table}</tbody></table>+ DESCRIPTION+ end++ it "contains resolved attributes and labels" do+ result = pdf[:strings]+ expected_result = [+ "#{type.name} ##{work_package.id} - #{work_package.subject}",+ *expected_details,+ label_title(:description),+ "Work package attributes and labels",+ supported_work_package_embeds.map do |embed|+ [WorkPackage.human_attribute_name(+ API::Utilities::PropertyNameConverter.to_ar_name(embed[0].to_sym, context: work_package)+ ), embed[1]]+ end,+ "1", export_time_formatted, project.name,+ "LongText",+ "Project attributes and labels",+ supported_project_embeds.map do |embed|+ [Project.human_attribute_name(+ API::Utilities::PropertyNameConverter.to_ar_name(embed[0].to_sym, context: project)+ ), embed[1]]+ end,+ "2", export_time_formatted, project.name+ ].flatten+ # Joining the results for comparison since word wrapping leads to a different array for the same content+ expect(result.join(" ")).to eq(expected_result.join(" "))+ end+ endendend