Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

[#63660] show attribute name in resolved subject (#18786)

Eric Schubertf02cf8cfd6b1
diff --git a/app/components/work_packages/types/pattern_input.html.erb b/app/components/work_packages/types/pattern_input.html.erb
index 58ce8d6fef0..eda2e088844 100644
--- a/app/components/work_packages/types/pattern_input.html.erb
+++ b/app/components/work_packages/types/pattern_input.html.erb
@@ -34,7 +34,6 @@ See COPYRIGHT and LICENSE files for more details.
classes: "pattern-input",
"data-controller": "pattern-input",
"data-pattern-input-pattern-initial-value": @value,
- "data-pattern-input-heading-locales-value": heading_locales,
"data-pattern-input-insert-as-text-template-value": I18n.t("types.edit.subject_configuration.pattern.insert_as_text"),
"data-pattern-input-suggestions-initial-value": suggestions_for_stimulus
)
diff --git a/app/components/work_packages/types/pattern_input.rb b/app/components/work_packages/types/pattern_input.rb
index 5634cabab84..aec45fc3e06 100644
--- a/app/components/work_packages/types/pattern_input.rb
+++ b/app/components/work_packages/types/pattern_input.rb
@@ -46,13 +46,6 @@ module WorkPackages
@suggestions_for_stimulus ||= @suggestions.to_json
end
- def heading_locales
- @suggestions.keys.reduce({}) do |acc, key|
- acc[key] = I18n.t("types.edit.subject_configuration.pattern.headings.#{key}")
- acc
- end.to_json
- end
-
def suggestions_list_component
@suggestions_list_component ||= Primer::Alpha::ActionList.new(
role: :list,
diff --git a/app/components/work_packages/types/subject_configuration_component.rb b/app/components/work_packages/types/subject_configuration_component.rb
index d96df46f714..b7278fc10db 100644
--- a/app/components/work_packages/types/subject_configuration_component.rb
+++ b/app/components/work_packages/types/subject_configuration_component.rb
@@ -63,11 +63,40 @@ module WorkPackages
::Types::Forms::SubjectConfigurationFormModel.new(
subject_configuration: values[:subject_configuration],
pattern: values[:pattern],
- suggestions: ::Types::Patterns::TokenPropertyMapper.new.tokens_for_type(model),
+ suggestions: sort_attributes(supported_attributes),
validation_errors: model.errors
)
end
+ def supported_attributes
+ attribute_tokens = ::Types::Patterns::TokenPropertyMapper.new.tokens_for_type(model)
+
+ result = {
+ work_package: {
+ title: I18n.t("types.edit.subject_configuration.token.context.work_package"),
+ tokens: []
+ },
+ parent: {
+ title: I18n.t("types.edit.subject_configuration.token.context.parent"),
+ tokens: []
+ },
+ project: {
+ title: I18n.t("types.edit.subject_configuration.token.context.project"),
+ tokens: []
+ }
+ }
+
+ attribute_tokens.each_with_object(result) do |token, obj|
+ token_hash = { key: token.key, label: token.label, label_with_context: token.label_with_context }
+ obj[token.context][:tokens] << token_hash
+ end
+ end
+
+ def sort_attributes(attributes)
+ attributes.each_value { |group| group[:tokens] = group[:tokens].sort_by { |a| a[:label] } }
+ attributes
+ end
+
def subject_configuration_form_values
if @subject_configuration_form_data.present?
@subject_configuration_form_data
diff --git a/app/contracts/types/base_contract.rb b/app/contracts/types/base_contract.rb
index 17f17cc27da..8515d42e6cd 100644
--- a/app/contracts/types/base_contract.rb
+++ b/app/contracts/types/base_contract.rb
@@ -109,7 +109,7 @@ module Types
valid_tokens = flat_valid_token_list
invalid_tokens = blueprint.scan(PatternResolver::TOKEN_REGEX)
.reduce([]) do |acc, match|
- token = Patterns::Token.build(match).key
+ token = Patterns::PatternToken.build(match).key
valid_tokens.include?(token) ? acc : acc << token
end
diff --git a/app/models/types/pattern_resolver.rb b/app/models/types/pattern_resolver.rb
index 703f2ca2f5e..eb84a0dd32a 100644
--- a/app/models/types/pattern_resolver.rb
+++ b/app/models/types/pattern_resolver.rb
@@ -36,30 +36,47 @@ module Types
def initialize(pattern)
@mapper = Patterns::TokenPropertyMapper.new
@pattern = pattern
- @tokens = pattern.scan(TOKEN_REGEX).map { |token| Patterns::Token.build(token) }
+ @pattern_tokens = pattern.scan(TOKEN_REGEX).map { |token| Patterns::PatternToken.build(token) }
end
def resolve(work_package)
- @tokens.inject(@pattern) do |pattern, token|
+ @tokens = @mapper.tokens_for_type(work_package.type)
+
+ @pattern_tokens.inject(@pattern) do |pattern, token|
pattern.gsub(token.pattern, get_value(work_package, token))
end
end
private
- def get_value(work_package, token)
- context = token.context == :work_package ? work_package : work_package.public_send(token.context)
+ def get_value(work_package, pattern_token)
+ context = pattern_token.context == :work_package ? work_package : work_package.public_send(pattern_token.context)
+ return ATTRIBUTE_PLACEHOLDER if context.nil?
+
+ attribute_token = @tokens.detect { |t| t.key == pattern_token.key }
+ return ATTRIBUTE_PLACEHOLDER if attribute_token.nil?
+
+ stringify(attribute_token.call(context), nil_replacement(attribute_token))
+ end
- stringify(@mapper[token.context_key].call(context))
+ def nil_replacement(attribute_resolver)
+ if attribute_resolver.context == :work_package
+ "[#{attribute_resolver.label}]"
+ else
+ "[#{attribute_resolver.label_with_context}]"
+ end
end
- def stringify(value)
+ def stringify(value, nil_fallback)
case value
when Date, Time, DateTime
value.strftime("%Y-%m-%d")
when Array
- value.join(", ")
+ compact = value.compact
+ compact.empty? ? nil_fallback : compact.join(", ")
when NilClass
+ nil_fallback
+ when :attribute_not_available
ATTRIBUTE_PLACEHOLDER
else
value.to_s
diff --git a/app/models/types/patterns/attribute_token.rb b/app/models/types/patterns/attribute_token.rb
new file mode 100644
index 00000000000..2e2066543d0
--- /dev/null
+++ b/app/models/types/patterns/attribute_token.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 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 Types
+ module Patterns
+ AttributeToken = Data.define(:key, :label, :resolve_fn) do
+ def label_with_context
+ attribute_context = I18n.t("types.edit.subject_configuration.token.context.#{context}")
+ I18n.t("types.edit.subject_configuration.token.label_with_context", attribute_context:, attribute_label: label)
+ end
+
+ def call(*)
+ resolve_fn.call(*)
+ end
+
+ def context
+ case key.to_s
+ when /^project_/
+ :project
+ when /^parent_/
+ :parent
+ else
+ :work_package
+ end
+ end
+ end
+ end
+end
diff --git a/app/models/types/patterns/token.rb b/app/models/types/patterns/pattern_token.rb
similarity index 77%
rename from app/models/types/patterns/token.rb
rename to app/models/types/patterns/pattern_token.rb
index e17f87e58fd..04abe5016e4 100644
--- a/app/models/types/patterns/token.rb
+++ b/app/models/types/patterns/pattern_token.rb
@@ -30,28 +30,22 @@
module Types
module Patterns
- Token = Data.define(:pattern, :key) do
+ PatternToken = Data.define(:pattern, :key) do
private_class_method :new
def self.build(pattern)
new(pattern, pattern.tr("{}", "").to_sym)
end
- def custom_field? = key.to_s.include?("custom_field")
-
- def context_key
- return key unless custom_field?
-
- key.to_s.gsub("#{context}_", "").to_sym
- end
-
def context
- return :work_package unless custom_field?
-
- context = key.to_s.gsub(/_?custom_field_\d+/, "")
- return :work_package if context.blank?
-
- context.to_sym
+ case key.to_s
+ when /^project_/
+ :project
+ when /^parent_/
+ :parent
+ else
+ :work_package
+ end
end
end
end
diff --git a/app/models/types/patterns/token_property_mapper.rb b/app/models/types/patterns/token_property_mapper.rb
index 1881e8bf7b4..25afa6f6286 100644
--- a/app/models/types/patterns/token_property_mapper.rb
+++ b/app/models/types/patterns/token_property_mapper.rb
@@ -31,88 +31,82 @@
module Types
module Patterns
class TokenPropertyMapper
- DEFAULT_FUNCTION = ->(key, context) do
- return nil if context.nil?
- return nil unless context.respond_to?(key.to_sym)
-
- context.public_send(key.to_sym)
- end.curry
-
- TOKEN_PROPERTY_MAP = IceNine.deep_freeze(
- {
- id: { fn: ->(wp) { wp.id }, label: -> { WorkPackage.human_attribute_name(:id) } },
- accountable: { fn: ->(wp) { wp.responsible&.name }, label: -> { WorkPackage.human_attribute_name(:responsible) } },
- assignee: { fn: ->(wp) { wp.assigned_to&.name }, label: -> { WorkPackage.human_attribute_name(:assigned_to) } },
- author: { fn: ->(wp) { wp.author&.name }, label: -> { WorkPackage.human_attribute_name(:author) } },
- category: { fn: ->(wp) { wp.category&.name }, label: -> { WorkPackage.human_attribute_name(:category) } },
- creation_date: { fn: ->(wp) { wp.created_at }, label: -> { WorkPackage.human_attribute_name(:created_at) } },
- estimated_time: { fn: ->(wp) { wp.estimated_hours }, label: -> { WorkPackage.human_attribute_name(:estimated_hours) } },
- remaining_time: { fn: ->(wp) { wp.remaining_hours }, label: -> { WorkPackage.human_attribute_name(:remaining_hours) } },
- finish_date: { fn: ->(wp) { wp.due_date }, label: -> { WorkPackage.human_attribute_name(:due_date) } },
- parent_id: { fn: ->(wp) { wp.parent&.id }, label: -> { WorkPackage.human_attribute_name(:id) } },
- parent_assignee: { fn: ->(wp) { wp.parent&.assigned_to&.name }, label: -> {
- WorkPackage.human_attribute_name(:assigned_to)
- } },
- parent_author: { fn: ->(wp) { wp.parent&.author&.name }, label: -> { WorkPackage.human_attribute_name(:author) } },
- parent_category: { fn: ->(wp) { wp.parent&.category&.name },
- label: -> { WorkPackage.human_attribute_name(:category) } },
- parent_creation_date: { fn: ->(wp) { wp.parent&.created_at },
- label: -> { WorkPackage.human_attribute_name(:created_at) } },
- parent_estimated_time: { fn: ->(wp) { wp.parent&.estimated_hours },
- label: -> { WorkPackage.human_attribute_name(:estimated_hours) } },
- parent_remaining_time: { fn: ->(wp) { wp.parent&.remaining_hours },
- label: -> { WorkPackage.human_attribute_name(:remaining_hours) } },
- parent_finish_date: { fn: ->(wp) { wp.parent&.due_date },
- label: -> { WorkPackage.human_attribute_name(:due_date) } },
- parent_priority: { fn: ->(wp) { wp.parent&.priority }, label: -> { WorkPackage.human_attribute_name(:priority) } },
- parent_subject: { fn: ->(wp) { wp.parent&.subject }, label: -> { WorkPackage.human_attribute_name(:subject) } },
- priority: { fn: ->(wp) { wp.priority }, label: -> { WorkPackage.human_attribute_name(:priority) } },
- project: { fn: ->(wp) { wp.project_id }, label: -> { WorkPackage.human_attribute_name(:project) } },
- project_active: { fn: ->(wp) { wp.project&.active? }, label: -> { Project.human_attribute_name(:active) } },
- project_name: { fn: ->(wp) { wp.project&.name }, label: -> { Project.human_attribute_name(:name) } },
- project_status: { fn: ->(wp) { wp.project&.status_code }, label: -> { Project.human_attribute_name(:status_code) } },
- project_parent: { fn: ->(wp) { wp.project&.parent_id }, label: -> { Project.human_attribute_name(:parent) } },
- project_public: { fn: ->(wp) { wp.project&.public? }, label: -> { Project.human_attribute_name(:public) } },
- start_date: { fn: ->(wp) { wp.start_date }, label: -> { WorkPackage.human_attribute_name(:start_date) } },
- status: { fn: ->(wp) { wp.status&.name }, label: -> { WorkPackage.human_attribute_name(:status) } },
- type: { fn: ->(wp) { wp.type&.name }, label: -> { WorkPackage.human_attribute_name(:type) } }
- }
- )
-
- def fetch(key)
- TOKEN_PROPERTY_MAP.dig(key, :fn) || DEFAULT_FUNCTION.call(key)
- end
-
- alias :[] :fetch
+ # rubocop:disable Layout/LineLength
+ BASE_ATTRIBUTE_TOKENS = [
+ AttributeToken.new(:id, WorkPackage.human_attribute_name(:id), ->(wp) { wp.id }),
+ AttributeToken.new(:accountable, WorkPackage.human_attribute_name(:responsible), ->(wp) { wp.responsible&.name }),
+ AttributeToken.new(:assignee, WorkPackage.human_attribute_name(:assigned_to), ->(wp) { wp.assigned_to&.name }),
+ AttributeToken.new(:author, WorkPackage.human_attribute_name(:author), ->(wp) { wp.author&.name }),
+ AttributeToken.new(:category, WorkPackage.human_attribute_name(:category), ->(wp) { wp.category&.name }),
+ AttributeToken.new(:creation_date, WorkPackage.human_attribute_name(:created_at), ->(wp) { wp.created_at }),
+ AttributeToken.new(:estimated_time, WorkPackage.human_attribute_name(:estimated_hours), ->(wp) { wp.estimated_hours }),
+ AttributeToken.new(:remaining_time, WorkPackage.human_attribute_name(:remaining_hours), ->(wp) { wp.remaining_hours }),
+ AttributeToken.new(:finish_date, WorkPackage.human_attribute_name(:due_date), ->(wp) { wp.due_date }),
+ AttributeToken.new(:parent_id, WorkPackage.human_attribute_name(:id), ->(parent) { parent.id }),
+ AttributeToken.new(:parent_assignee, WorkPackage.human_attribute_name(:assigned_to), ->(parent) { parent.assigned_to&.name }),
+ AttributeToken.new(:parent_author, WorkPackage.human_attribute_name(:author), ->(parent) { parent.author&.name }),
+ AttributeToken.new(:parent_category, WorkPackage.human_attribute_name(:category), ->(parent) { parent.category&.name }),
+ AttributeToken.new(:parent_creation_date, WorkPackage.human_attribute_name(:created_at), ->(parent) { parent.created_at }),
+ AttributeToken.new(:parent_estimated_time, WorkPackage.human_attribute_name(:estimated_hours), ->(parent) { parent.estimated_hours }),
+ AttributeToken.new(:parent_remaining_time, WorkPackage.human_attribute_name(:remaining_hours), ->(parent) { parent.remaining_hours }),
+ AttributeToken.new(:parent_finish_date, WorkPackage.human_attribute_name(:due_date), ->(parent) { parent.due_date }),
+ AttributeToken.new(:parent_priority, WorkPackage.human_attribute_name(:priority), ->(parent) { parent.priority }),
+ AttributeToken.new(:parent_subject, WorkPackage.human_attribute_name(:subject), ->(parent) { parent.subject }),
+ AttributeToken.new(:priority, WorkPackage.human_attribute_name(:priority), ->(wp) { wp.priority }),
+ AttributeToken.new(:project, WorkPackage.human_attribute_name(:project_id), ->(wp) { wp.project }),
+ AttributeToken.new(:project_active, Project.human_attribute_name(:active), ->(project) { project.active? }),
+ AttributeToken.new(:project_name, Project.human_attribute_name(:name), ->(project) { project.name }),
+ AttributeToken.new(:project_status, Project.human_attribute_name(:status_code), ->(project) { project.status_code }),
+ AttributeToken.new(:project_parent, Project.human_attribute_name(:parent), ->(project) { project.parent_id }),
+ AttributeToken.new(:project_public, Project.human_attribute_name(:public), ->(project) { project.public? }),
+ AttributeToken.new(:start_date, WorkPackage.human_attribute_name(:start_date), ->(wp) { wp.start_date }),
+ AttributeToken.new(:status, WorkPackage.human_attribute_name(:status), ->(wp) { wp.status&.name }),
+ AttributeToken.new(:type, WorkPackage.human_attribute_name(:type), ->(wp) { wp.type&.name })
+ ].freeze
+ # rubocop:enable Layout/LineLength
def tokens_for_type(type)
- base = default_tokens
- base[:work_package].merge!(tokenize(work_package_cfs_for(type)))
- base[:project].merge!(tokenize(project_attributes, "project_"))
- base[:parent].merge!(tokenize(all_work_package_cfs, "parent_"))
-
- base.transform_values { _1.sort_by(&:last).to_h }
+ [
+ *BASE_ATTRIBUTE_TOKENS,
+ *tokenize(work_package_cfs_for(type)),
+ *tokenize(project_cfs, "project_"),
+ *tokenize(all_work_package_cfs, "parent_")
+ ]
end
private
def default_tokens
- TOKEN_PROPERTY_MAP.keys.each_with_object({ work_package: {}, project: {}, parent: {} }) do |key, obj|
- label = TOKEN_PROPERTY_MAP.dig(key, :label).call
-
- case key.to_s
+ BASE_ATTRIBUTE_TOKENS.each_with_object({ work_package: {}, project: {}, parent: {} }) do |token, obj|
+ case token.key.to_s
when /^project_/
- obj[:project][key] = label
+ obj[:project][token.key] = token
when /^parent_/
- obj[:parent][key] = label
+ obj[:parent][token.key] = token
else
- obj[:work_package][key] = label
+ obj[:work_package][token.key] = token
end
end
end
+ def prefixed_label(context, attribute_label)
+ attribute_context = I18n.t("types.edit.subject_configuration.token.context.#{context}")
+ I18n.t("types.edit.subject_configuration.token.label_with_context", attribute_context:, attribute_label:)
+ end
+
def tokenize(custom_field_scope, prefix = nil)
- custom_field_scope.pluck(:name, :id).to_h { |name, id| [:"#{prefix}custom_field_#{id}", name] }
+ custom_field_scope.pluck(:name, :id).map do |name, id|
+ AttributeToken.new(
+ :"#{prefix}custom_field_#{id}",
+ name,
+ ->(context) do
+ key = :"custom_field_#{id}"
+ return :attribute_not_available unless context.respond_to?(key)
+
+ context.public_send(key)
+ end
+ )
+ end
end
def work_package_cfs_for(type)
@@ -123,7 +117,7 @@ module Types
WorkPackageCustomField.where.not(field_format: %w[text bool link empty]).order(:name)
end
- def project_attributes
+ def project_cfs
ProjectCustomField.where.not(field_format: %w[text bool link empty])
.where(admin_only: false, multi_value: false).order(:name)
end
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 2c7b53865a2..eeb1d35a0f9 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -687,13 +687,15 @@ en:
automatically_generated_subjects:
label: "Automatically generated subjects"
caption: "Define a pattern using referenced attributes and text to automatically generate work package subjects. Users will not be able to manually edit subjects."
- pattern:
- label: "Subject pattern"
- caption: "Add text or type / to search for an attribute. You can add spaces to separate them."
- headings:
+ token:
+ label_with_context: "%{attribute_context}: %{attribute_label}"
+ context:
work_package: "Work package"
parent: "Parent"
project: "Project"
+ pattern:
+ label: "Subject pattern"
+ caption: "Add text or type / to search for an attribute. You can add spaces to separate them."
insert_as_text: "No attributes found. Add as text: \"%{word}\""
export_configuration:
tab: "Generate PDF"
diff --git a/frontend/src/stimulus/controllers/pattern-input.controller.ts b/frontend/src/stimulus/controllers/pattern-input.controller.ts
index 66f40d2745d..5dda10abc93 100644
--- a/frontend/src/stimulus/controllers/pattern-input.controller.ts
+++ b/frontend/src/stimulus/controllers/pattern-input.controller.ts
@@ -33,11 +33,13 @@ import { Controller } from '@hotwired/stimulus';
// internal type used to filter suggestions
type FilteredSuggestions = Array<{
key:string;
+ label:string;
values:Array<{ prop:string; value:string; }>;
}>;
type TokenElement = HTMLElement&{ dataset:{ role:'token', prop:string } };
type ListElement = HTMLElement&{ dataset:{ role:'list_item', prop:string } };
+type AttributeToken = { key:string, label:string, label_with_context:string };
const COMPLETION_CHARACTER = '/';
const TOKEN_REGEX = /{{([0-9A-Za-z_]+)}}/g;
@@ -73,21 +75,19 @@ export default class PatternInputController extends Controller {
static values = {
patternInitial: String,
- headingLocales: Object,
suggestionsInitial: Object,
insertAsTextTemplate: String,
};
declare readonly patternInitialValue:string;
- declare readonly suggestionsInitialValue:Record<string, Record<string, string>>;
- declare readonly headingLocalesValue:Record<string, string>;
+ declare readonly suggestionsInitialValue:Record<string, { title:string, tokens:AttributeToken[] }>;
declare readonly insertAsTextTemplateValue:string;
- validTokenMap:Record<string, string> = {};
+ validTokenMap:Record<string, AttributeToken> = {};
currentRange:Range|undefined = undefined;
connect() {
- this.validTokenMap = this.flatLocalizedTokenMap();
+ this.validTokenMap = this.flatTokensKeyToLabelWithContext();
this.contentTarget.innerHTML = this.toHtml(this.patternInitialValue) || ' ';
this.tagInvalidTokens();
this.clearSuggestionsFilter();
@@ -212,17 +212,12 @@ export default class PatternInputController extends Controller {
this.clearSuggestionsFilter();
}
- private flatLocalizedTokenMap():Record<string, string> {
+ private flatTokensKeyToLabelWithContext():Record<string, AttributeToken> {
return Object.entries(this.suggestionsInitialValue)
- .reduce((acc, [groupKey, attributes]) => {
- if (groupKey !== 'work_package') {
- Object.entries(attributes).forEach(([key, value]) => {
- attributes[key] = `${this.tokenPrefix(groupKey)} ${value}`;
- });
- }
-
- return { ...acc, ...attributes };
- }, {});
+ .reduce((acc, [_, token_group]) => {
+ token_group.tokens.forEach((t) => { acc[t.key] = t; });
+ return acc;
+ }, {} as Record<string, AttributeToken>);
}
private updateFormInputValue():void {
@@ -361,9 +356,9 @@ export default class PatternInputController extends Controller {
if (textContent === null) { return null; }
if (this.isToken(parent)) {
- const key = parent.dataset.prop;
- const prefix = this.tokenPrefix(key.slice(0, key.indexOf('_')));
- const start = prefix && textContent.startsWith(`${prefix} `) ? prefix.length + 1 : 0;
+ const token = this.validTokenMap[parent.dataset.prop];
+ const prefix = token.label_with_context.replace(token.label, '');
+ const start = prefix && textContent.startsWith(prefix) ? prefix.length : 0;
return textContent.slice(start, selection.anchorOffset);
}
@@ -393,7 +388,7 @@ export default class PatternInputController extends Controller {
if (groupHeader) {
const headerElement = groupHeader.querySelector('h2');
if (headerElement) {
- headerElement.innerText = this.headingLocalesValue[group.key];
+ headerElement.innerText = group.label;
}
this.suggestionsTarget.appendChild(groupHeader);
@@ -447,9 +442,10 @@ export default class PatternInputController extends Controller {
const group = this.suggestionsInitialValue[key];
return {
key,
- values: Object.entries(group).filter(([prop, value]) => {
- return value.toLowerCase().includes(word.toLowerCase()) || prop.toLowerCase().includes(word.toLowerCase()) || word === '*';
- }).map(([prop, value]) => ({ prop, value })),
+ label: group.title,
+ values: group.tokens
+ .filter((token) => token.key.includes(word) || token.label.includes(word) || word === '*')
+ .map((token) => ({ prop: token.key, value: token.label })),
};
}).filter((group) => group.values.length > 0);
}
@@ -485,11 +481,11 @@ export default class PatternInputController extends Controller {
}
}
- private createToken(value:string):TokenElement {
+ private createToken(key:string):TokenElement {
const templateTarget = this.tokenTemplateTarget.content?.cloneNode(true) as DocumentFragment;
const contentElement = templateTarget.firstElementChild as TokenElement;
- contentElement.dataset.prop = value;
- contentElement.innerText = this.validTokenMap[value] || value;
+ contentElement.dataset.prop = key;
+ contentElement.innerText = this.tokenText(key);
return contentElement;
}
@@ -499,11 +495,11 @@ export default class PatternInputController extends Controller {
this.setStyle(node, 'accent');
const key = node.dataset.prop;
- if (node.textContent !== this.validTokenMap[key]) {
+ if (node.textContent !== this.tokenText(key)) {
if (this.containsCursor(node)) {
this.setStyle(node, 'secondary');
} else {
- node.innerText = this.validTokenMap[key] || key;
+ node.innerText = this.tokenText(key);
}
}
@@ -523,6 +519,20 @@ export default class PatternInputController extends Controller {
});
}
+ private tokenText(key:string):string {
+ const token = this.validTokenMap[key];
+
+ if (!token) {
+ return key;
+ }
+
+ if (token.key.startsWith('parent_') || token.key.startsWith('project_')) {
+ return token.label_with_context;
+ }
+
+ return token.label;
+ }
+
private toHtml(blueprint:string):string {
let html = blueprint.replace(/</g, '&lt;').replace(/>/g, '&gt;');
html = this.insertControlSpaces(html);
@@ -551,11 +561,6 @@ export default class PatternInputController extends Controller {
}, blueprint);
}
- private tokenPrefix(groupKey:string):string {
- const locale = this.headingLocalesValue[groupKey];
- return locale ? `${locale}:` : '';
- }
-
private toBlueprint():string {
let result = '';
this.contentTarget.childNodes.forEach((node:ChildNode) => {
diff --git a/spec/models/types/pattern_resolver_spec.rb b/spec/models/types/pattern_resolver_spec.rb
index 2a9d5dccfcb..bcd550a7034 100644
--- a/spec/models/types/pattern_resolver_spec.rb
+++ b/spec/models/types/pattern_resolver_spec.rb
@@ -42,11 +42,11 @@ RSpec.describe Types::PatternResolver do
end
context "when the pattern has WorkPackage properties" do
- let(:subject_pattern) { "{{id}} | {{done_ratio}} | {{creation_date}}" }
+ let(:subject_pattern) { "{{id}} | {{author}} | {{creation_date}}" }
it "resolves the pattern" do
expect(subject.resolve(work_package))
- .to eq("#{work_package.id} | N/A | #{work_package.created_at.to_date.iso8601}")
+ .to eq("#{work_package.id} | #{work_package.author} | #{work_package.created_at.to_date.iso8601}")
end
end
@@ -59,9 +59,18 @@ RSpec.describe Types::PatternResolver do
end
end
+ context "when the pattern has attributes that do not resolve to a value" do
+ let(:subject_pattern) { "{{invalid_attribute}} | empty: {{assignee}} | without parent: {{parent_subject}}" }
+
+ it "resolves the pattern" do
+ expect(subject.resolve(work_package)).to eq("N/A | empty: [Assignee] | without parent: N/A")
+ end
+ end
+
context "when the pattern has custom fields" do
let(:custom_field) { create(:string_wp_custom_field) }
let(:multi_value_field) { create(:multi_list_wp_custom_field) }
+ let(:custom_field_not_configured) { create(:string_wp_custom_field) }
let(:type) { create(:type, custom_fields: [custom_field, multi_value_field]) }
let(:project) { create(:project, types: [type], work_package_custom_fields: [custom_field, multi_value_field]) }
let(:project_custom_field) { create(:project_custom_field, projects: [project], field_format: "string") }
@@ -92,5 +101,13 @@ RSpec.describe Types::PatternResolver do
expect(subject.resolve(work_package)).to eq("PROSPEC A custom field value: Important Information")
end
+
+ context "if the pattern contains custom fields that are not configured" do
+ let(:subject_pattern) { "pattern: {{invalid_attribute}}" }
+
+ it "resolves the pattern" do
+ expect(subject.resolve(work_package)).to eq("pattern: N/A")
+ end
+ end
end
end
diff --git a/spec/models/types/patterns/token_property_mapper_spec.rb b/spec/models/types/patterns/token_property_mapper_spec.rb
index 0001ad606c5..f4ac4415664 100644
--- a/spec/models/types/patterns/token_property_mapper_spec.rb
+++ b/spec/models/types/patterns/token_property_mapper_spec.rb
@@ -68,35 +68,55 @@ RSpec.describe Types::Patterns::TokenPropertyMapper do
end
shared_let(:not_activated_custom_field) do
- create(:boolean_wp_custom_field).tap do |custom_field|
+ create(:string_wp_custom_field).tap do |custom_field|
work_package.type.custom_fields << custom_field
end
end
- described_class::TOKEN_PROPERTY_MAP.each_pair do |key, details|
- it "the token named #{key} resolves successfully" do
- expect { details[:fn].call(work_package) }.not_to raise_error
- expect(details[:fn].call(work_package)).not_to be_nil
+ described_class::BASE_ATTRIBUTE_TOKENS.each do |token|
+ it "the attribute token named #{token.key} resolves successfully" do
+ context = case token.key
+ when /^parent_/
+ work_package_parent
+ when /^project_/
+ project
+ else
+ work_package
+ end
+
+ expect { token.call(context) }.not_to raise_error
+ expect(token.call(context)).not_to be_nil
end
end
it "multi value fields are supported" do
- function = described_class.new.fetch :"custom_field_#{mult_list_custom_field.id}"
- expect(function.call(work_package)).to eq(%w[A B])
+ token = described_class.new.tokens_for_type(work_package.type).detect do |t|
+ t.key == :"custom_field_#{mult_list_custom_field.id}"
+ end
+ expect(token.call(work_package)).to eq(%w[A B])
end
it "must return nil if custom field is not activated in project" do
- function = described_class.new.fetch :"custom_field_#{not_activated_custom_field.id}"
- expect { function.call(work_package) }.not_to raise_error
- expect(function.call(work_package)).to be_nil
+ token = described_class.new.tokens_for_type(work_package.type).detect do |t|
+ t.key == :"custom_field_#{not_activated_custom_field.id}"
+ end
+
+ expect { token.call(work_package) }.not_to raise_error
+ expect(token.call(work_package)).to eq(:attribute_not_available)
end
it "returns all possible tokens" do
cf = string_custom_field
tokens = described_class.new.tokens_for_type(work_package.type)
- expect(tokens.keys).to match_array(%i[work_package project parent])
- expect(tokens[:project][:project_status]).to eq(Project.human_attribute_name(:status_code))
- expect(tokens[:work_package][:"custom_field_#{cf.id}"]).to eq(cf.name)
+ expect(tokens.first).to be_a(Types::Patterns::AttributeToken)
+ expect(detect(tokens, :project_status).label).to eq(Project.human_attribute_name(:status_code))
+ expect(detect(tokens, :"custom_field_#{cf.id}").label).to eq(cf.name)
+ end
+
+ private
+
+ def detect(tokens, key)
+ tokens.detect { |t| t.key == key }
end
end