From 0f6489648e3b5517ad9aaf7f08f832b2bbec80b0 Mon Sep 17 00:00:00 2001
From: philippe lhardy <pl@artisanlogiciel.net>
Date: Sat, 20 Jan 2024 12:39:44 +0100
Subject: manualy rebase 4.2.1 patch + pdf patch within master

on a 4.2.1 tag.

- applied 0001-Add-Group-Issue-Custom-Fields-functionality.patch
- applied 0001-fix-pdf-generation-of-full-width-layout.patch ( + manual actions )

ran localy ok

git merge on master
adapting fixes
ran localy ok

tentatively git rebase master but too many 4.2.1 deviations.
git reset on master and add this as a clear patch.
---
 app/controllers/projects_controller.rb        |  37 +++++
 app/helpers/issues_helper.rb                  |  99 ++++++++-----
 app/helpers/projects_helper.rb                |   4 +-
 app/models/attribute_group.rb                 |   9 ++
 app/models/attribute_group_field.rb           |   7 +
 app/models/custom_field.rb                    |   1 +
 app/models/project.rb                         |   2 +
 app/models/tracker.rb                         |   2 +
 app/views/issues/_form_custom_fields.html.erb |  55 ++++---
 app/views/issues/show.html.erb                |   4 +-
 .../_groupissuescustomfields.html.erb         | 140 ++++++++++++++++++
 config/locales/en.yml                         |   3 +
 config/locales/pt-BR.yml                      |   3 +
 config/routes.rb                              |   1 +
 .../20180913211420_create_attribute_groups.rb |  12 ++
 ...913212008_create_attribute_group_fields.rb |  11 ++
 lib/redmine/export/pdf/issues_pdf_helper.rb   |  95 ++++++++++--
 lib/redmine/preparation.rb                    |   2 +-
 public/stylesheets/application.css            |  45 ++++++
 test/fixtures/attribute_group_fields.yml      |  11 ++
 test/fixtures/attribute_groups.yml            |  13 ++
 21 files changed, 478 insertions(+), 78 deletions(-)
 create mode 100644 app/models/attribute_group.rb
 create mode 100644 app/models/attribute_group_field.rb
 create mode 100644 app/views/projects/settings/_groupissuescustomfields.html.erb
 create mode 100644 db/migrate/20180913211420_create_attribute_groups.rb
 create mode 100644 db/migrate/20180913212008_create_attribute_group_fields.rb
 create mode 100644 test/fixtures/attribute_group_fields.yml
 create mode 100644 test/fixtures/attribute_groups.yml

diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb
index 1faeee46c..c27897e09 100644
--- a/app/controllers/projects_controller.rb
+++ b/app/controllers/projects_controller.rb
@@ -203,6 +203,10 @@ class ProjectsController < ApplicationController
     @issue_category ||= IssueCategory.new
     @member ||= @project.members.new
     @trackers = Tracker.sorted.to_a
+    @cfs=AttributeGroup.joins(:custom_fields).joins(:tracker).
+      where(project_id: @project, tracker_id: @trackers, :custom_fields => {id: @project.all_issue_custom_fields.pluck(:id)}).
+      pluck("trackers.id", "id", "name", "position","attribute_group_fields.id", "attribute_group_fields.position",
+        "custom_fields.id", "custom_fields.name", "custom_fields.position").sort_by{|x| [x[3], x[5]]}
 
     @version_status = params[:version_status] || 'open'
     @version_name = params[:version_name]
@@ -233,6 +237,39 @@ class ProjectsController < ApplicationController
     end
   end
 
+  def groupissuescustomfields
+    # clean invalid values: invalid cfs, empty cf lists, empty groups
+    group_issues_custom_fields = (JSON.parse params[:group_issues_custom_fields]).
+      each{|tid,v| v.replace(v.select{|k,v| v["cfs"] ? v["cfs"].delete_if{|k,v| @project.all_issue_custom_fields.pluck(:id).include?(v)} : v})}.
+      each{|tid,v| v.delete_if{|k,v| v["cfs"].blank?}}.
+      delete_if{|k,v| v.blank?}
+
+    groups = AttributeGroup.where(project_id: @project.id).collect(&:id)
+    fields = AttributeGroupField.where(attribute_group_id: groups).collect(&:id)
+    group_issues_custom_fields.each do |tid,v|
+      v.each do |gp, g|
+        gid = groups.shift
+        if gid.nil?
+          gid=AttributeGroup.create(project_id: @project.id, tracker_id: tid, name: g["name"].nil? ? nil : g["name"], position: gp).id
+        else
+          AttributeGroup.update(gid, project_id: @project.id, tracker_id: tid, name: g["name"].nil? ? nil : g["name"], position: gp)
+        end
+        g['cfs'].each do |cfp, cf|
+          cfid = fields.shift
+          if cfid.nil?
+            AttributeGroupField.create(attribute_group_id: gid, custom_field_id: cf, position: cfp)
+          else
+            AttributeGroupField.update(cfid, attribute_group_id: gid, custom_field_id: cf, position: cfp)
+          end
+        end
+      end
+    end
+    AttributeGroupField.where(id: fields).delete_all
+    AttributeGroup.where(id: groups).destroy_all
+    flash[:notice] = l(:notice_successful_update)
+    redirect_to settings_project_path(@project, :tab => 'groupissuescustomfields')
+  end
+
   def archive
     unless @project.archive
       error = l(:error_can_not_archive_project)
diff --git a/app/helpers/issues_helper.rb b/app/helpers/issues_helper.rb
index e2ee6d535..29f98d509 100644
--- a/app/helpers/issues_helper.rb
+++ b/app/helpers/issues_helper.rb
@@ -368,33 +368,48 @@ module IssuesHelper
     r.to_html
   end
 
-  def render_half_width_custom_fields_rows(issue)
-    values = issue.visible_custom_field_values.reject {|value| value.custom_field.full_width_layout?}
-    return if values.empty?
-
-    half = (values.size / 2.0).ceil
-    issue_fields_rows do |rows|
-      values.each_with_index do |value, i|
-        m = (i < half ? :left : :right)
-        rows.send m, custom_field_name_tag(value.custom_field), custom_field_value_tag(value), :class => value.custom_field.css_classes
-      end
-    end
-  end
-
-  def render_full_width_custom_fields_rows(issue)
-    values = issue.visible_custom_field_values.select {|value| value.custom_field.full_width_layout?}
-    return if values.empty?
-
+  def group_by_keys(project_id, tracker_id, custom_field_values)
+    keys_grouped = AttributeGroupField.joins(:attribute_group).
+      where(:attribute_groups => {project_id: project_id, tracker_id: tracker_id}).
+      order("attribute_groups.position", :position).pluck(:name, :custom_field_id).group_by(&:shift)
+    custom_fields_grouped = { nil => (keys_grouped[nil].nil? ? [] :
+      keys_grouped[nil].map{|n| custom_field_values.select{|x| x.custom_field[:id] == n[0]}}.flatten) |
+      custom_field_values.select{|y| ! keys_grouped.values.flatten.include?(y.custom_field[:id])}}
+    keys_grouped.reject{|k,v| k == nil}.each{|k,v| custom_fields_grouped[k] =
+      v.map{|n| custom_field_values.select{|x| x.custom_field[:id] == n[0]}}.flatten}
+    custom_fields_grouped
+  end
+
+  def render_custom_fields_rows(issue)
     s = ''.html_safe
-    values.each_with_index do |value, i|
-      attr_value_tag = custom_field_value_tag(value)
-      next if attr_value_tag.blank?
-
-      content =
-        content_tag('hr') +
-        content_tag('p', content_tag('strong', custom_field_name_tag(value.custom_field) )) +
-        content_tag('div', attr_value_tag, class: 'value')
-      s << content_tag('div', content, class: "#{value.custom_field.css_classes} attribute")
+    group_by_keys(issue.project_id, issue.tracker_id, issue.visible_custom_field_values).
+      each do |title, values|
+      if values.present?
+        s << content_tag('h4', title, :style => 'background: #0001; padding: 0.3em;') unless title.nil?
+        while values.present?
+          unless values[0].custom_field.full_width_layout?
+            lr_values = []
+            while values.present? && ! values[0].custom_field.full_width_layout?
+              lr_values += [ values.shift ]
+            end
+            half = (lr_values.size / 2.0).ceil
+            s << issue_fields_rows do |rows|
+              lr_values.each_with_index do |value, i|
+                m = (i < half ? :left : :right)
+                rows.send m, custom_field_name_tag(value.custom_field), custom_field_value_tag(value), :class => value.custom_field.css_classes
+              end
+            end
+          else
+            while values.present? && values[0].custom_field.full_width_layout?
+              value=values.shift
+              content = content_tag('div', custom_field_name_tag(value.custom_field) + ":", :class => 'label') +
+                        content_tag('div', custom_field_value_tag(value), :class => 'value')
+              content = content_tag('div', content, :class => "#{value.custom_field.css_classes} attribute")
+              s << content_tag('div', content, :class => 'splitcontent')
+            end
+          end
+        end
+      end
     end
     s
   end
@@ -457,14 +472,23 @@ module IssuesHelper
         end
       end
     end
-    issue.visible_custom_field_values(user).each do |value|
-      cf_value = show_value(value, false)
-      next if cf_value.blank?
-
-      if html
-        items << content_tag('strong', "#{value.custom_field.name}: ") + cf_value
-      else
-        items << "#{value.custom_field.name}: #{cf_value}"
+    group_by_keys(issue.project_id, issue.tracker_id, issue.visible_custom_field_values(user)).each do |title, values|
+      if values.present?
+        unless title.nil?
+          if html
+            items << content_tag('strong', "#{title}")
+          else
+            items << "#{title}"
+          end
+        end
+        values.each do |value|
+          cf_value = show_value(value, false)
+          if html
+            items << content_tag('strong', "#{value.custom_field.name}: ") + cf_value
+          else
+            items << "#{value.custom_field.name}: #{cf_value}"
+          end
+        end
       end
     end
     items
@@ -473,9 +497,12 @@ module IssuesHelper
   def render_email_issue_attributes(issue, user, html=false)
     items = email_issue_attributes(issue, user, html)
     if html
-      content_tag('ul', items.map{|s| content_tag('li', s)}.join("\n").html_safe, :class => "details")
+      content_tag('ul', items.select{|s| s.is_a? String}.map{|s| content_tag('li', s)}.join("\n").html_safe, :class => "details") + "\n" +
+        items.select{|s| !s.is_a? String}.map{|item| content_tag('div', item.shift) + "\n" +
+        content_tag('ul', item.map{|s| content_tag('li', s)}.join("\n").html_safe, :class => "details")}.join("\n").html_safe
     else
-      items.map{|s| "* #{s}"}.join("\n")
+      items.select{|s| s.is_a? String}.map{|s| "* #{s}"}.join("\n") + "\n" +
+        items.select{|s| !s.is_a? String}.map{|item| "#{item.shift}\n" + item.map{|s| "* #{s}"}.join("\n")}.join("\n")
     end
   end
 
diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb
index d4f7339a0..b8dffe853 100644
--- a/app/helpers/projects_helper.rb
+++ b/app/helpers/projects_helper.rb
@@ -39,7 +39,9 @@ module ProjectsHelper
         {:name => 'boards', :action => :manage_boards,
          :partial => 'projects/settings/boards', :label => :label_board_plural},
         {:name => 'activities', :action => :manage_project_activities,
-         :partial => 'projects/settings/activities', :label => :label_time_tracking}
+         :partial => 'projects/settings/activities', :label => :label_time_tracking},
+        {:name => 'groupissuescustomfields', :action => :edit_project,
+         :partial => 'projects/settings/groupissuescustomfields', :label => :grouped_cf}
       ]
     tabs.
       select {|tab| User.current.allowed_to?(tab[:action], @project)}.
diff --git a/app/models/attribute_group.rb b/app/models/attribute_group.rb
new file mode 100644
index 000000000..52d7ac3bf
--- /dev/null
+++ b/app/models/attribute_group.rb
@@ -0,0 +1,9 @@
+class AttributeGroup < ActiveRecord::Base
+  belongs_to :project
+  belongs_to :tracker
+  has_many :attribute_group_fields, :dependent => :delete_all
+  has_many :custom_fields, :through => :attribute_group_fields
+  acts_as_positioned
+
+  scope :sorted, lambda { order(:position) }
+end
diff --git a/app/models/attribute_group_field.rb b/app/models/attribute_group_field.rb
new file mode 100644
index 000000000..c040138ab
--- /dev/null
+++ b/app/models/attribute_group_field.rb
@@ -0,0 +1,7 @@
+class AttributeGroupField < ActiveRecord::Base
+  belongs_to :attribute_group
+  belongs_to :custom_field
+  acts_as_positioned
+
+  scope :sorted, lambda { order(:position) }
+end
diff --git a/app/models/custom_field.rb b/app/models/custom_field.rb
index be9cf550f..87ad0f586 100644
--- a/app/models/custom_field.rb
+++ b/app/models/custom_field.rb
@@ -26,6 +26,7 @@ class CustomField < ActiveRecord::Base
            :class_name => 'CustomFieldEnumeration',
            :dependent => :delete_all
   has_many :custom_values, :dependent => :delete_all
+  has_many :attribute_group_fields, :dependent => :delete_all
   has_and_belongs_to_many :roles,
                           :join_table => "#{table_name_prefix}custom_fields_roles#{table_name_suffix}",
                           :foreign_key => "custom_field_id"
diff --git a/app/models/project.rb b/app/models/project.rb
index 58346d373..a5fd5a407 100644
--- a/app/models/project.rb
+++ b/app/models/project.rb
@@ -55,6 +55,8 @@ class Project < ActiveRecord::Base
   has_many :changesets, :through => :repository
   has_one :wiki, :dependent => :destroy
   # Custom field for the project issues
+  has_many :attribute_groups, :dependent => :destroy
+  has_many :attribute_group_fields, :through => :attribute_groups
   has_and_belongs_to_many :issue_custom_fields,
                           lambda {order(:position)},
                           :class_name => 'IssueCustomField',
diff --git a/app/models/tracker.rb b/app/models/tracker.rb
index ef2f48b04..3e8bdefa3 100644
--- a/app/models/tracker.rb
+++ b/app/models/tracker.rb
@@ -36,6 +36,8 @@ class Tracker < ActiveRecord::Base
   has_and_belongs_to_many :custom_fields, :class_name => 'IssueCustomField',
                           :join_table => "#{table_name_prefix}custom_fields_trackers#{table_name_suffix}",
                           :association_foreign_key => 'custom_field_id'
+  has_many :attribute_groups, :dependent => :destroy
+  has_many :attribute_group_fields, :through => :attribute_groups
   acts_as_positioned
 
   validates_presence_of :default_status
diff --git a/app/views/issues/_form_custom_fields.html.erb b/app/views/issues/_form_custom_fields.html.erb
index fddcd742f..3d887b90d 100644
--- a/app/views/issues/_form_custom_fields.html.erb
+++ b/app/views/issues/_form_custom_fields.html.erb
@@ -1,24 +1,33 @@
-<% custom_field_values = @issue.editable_custom_field_values %>
-<% custom_field_values_full_width = custom_field_values.select { |value| value.custom_field.full_width_layout? } %>
-<% custom_field_values -= custom_field_values_full_width %>
-
-<% if custom_field_values.present? %>
-<div class="splitcontent">
-<div class="splitcontentleft">
-<% i = 0 %>
-<% split_on = (custom_field_values.size / 2.0).ceil - 1 %>
-<% custom_field_values.each do |value| %>
-  <p><%= custom_field_tag_with_label :issue, value, :required => @issue.required_attribute?(value.custom_field_id) %></p>
-<% if i == split_on -%>
-</div><div class="splitcontentright">
-<% end -%>
-<% i += 1 -%>
-<% end -%>
-</div>
-</div>
-<% end %>
-
-<% custom_field_values_full_width.each do |value| %>
-  <p><%= custom_field_tag_with_label :issue, value, :required => @issue.required_attribute?(value.custom_field_id) %></p>
-  <%= wikitoolbar_for "issue_custom_field_values_#{value.custom_field_id}", preview_issue_path(:project_id => @issue.project, :issue_id => @issue.id) if value.custom_field.full_text_formatting? %>
+<% group_by_keys(@issue.project_id, @issue.tracker_id, @issue.editable_custom_field_values).each do |title,values| %>
+  <% if values.present? %>
+    <%= content_tag('h4', title, :style => 'background: #0001; padding: 0.3em;') unless title.nil? %>
+    <% while values.present? %>
+      <% if values[0].custom_field.full_width_layout? %>
+        <% while values.present? && values[0].custom_field.full_width_layout? %>
+          <% value = values.shift %>
+          <p><%= custom_field_tag_with_label :issue, value, :required => @issue.required_attribute?(value.custom_field_id) %></p>
+          <%= wikitoolbar_for "issue_custom_field_values_#{value.custom_field_id}", preview_issue_path(:project_id => @issue.project, :issue_id => @issue.id) if value.custom_field.full_text_formatting? %>
+        <% end %>
+      <% else %>
+        <div class="splitcontent">
+          <% lr_values = [] %>
+          <% while values.present? && ! values[0].custom_field.full_width_layout? %>
+            <% lr_values += [ values.shift ] %>
+          <% end %>
+          <div class="splitcontentleft">
+            <% i = 0 %>
+            <% split_on = (lr_values.size / 2.0).ceil - 1 %>
+            <% lr_values.each do |value| %>
+              <p><%= custom_field_tag_with_label :issue, value, :required => @issue.required_attribute?(value.custom_field_id) %></p>
+              <%= wikitoolbar_for "issue_custom_field_values_#{value.custom_field_id}", preview_issue_path(:project_id => @issue.project, :issue_id => @issue.id) if value.custom_field.full_text_formatting? %>
+              <% if i == split_on %>
+                </div><div class="splitcontentright">
+              <% end %>
+              <% i += 1 %>
+            <% end %>
+          </div>
+        </div>
+      <% end %>
+    <% end %>
+  <% end %>
 <% end %>
diff --git a/app/views/issues/show.html.erb b/app/views/issues/show.html.erb
index 6f0a0a984..f950deb89 100644
--- a/app/views/issues/show.html.erb
+++ b/app/views/issues/show.html.erb
@@ -77,7 +77,7 @@
     rows.right l(:label_spent_time), issue_spent_hours_details(@issue), :class => 'spent-time'
   end
 end %>
-<%= render_half_width_custom_fields_rows(@issue) %>
+<%= render_custom_fields_rows(@issue) %>
 <%= call_hook(:view_issues_show_details_bottom, :issue => @issue) %>
 </div>
 
@@ -100,8 +100,6 @@ end %>
   <%= link_to_attachments @issue, :thumbnails => true %>
 <% end %>
 
-<%= render_full_width_custom_fields_rows(@issue) %>
-
 <%= call_hook(:view_issues_show_description_bottom, :issue => @issue) %>
 
 <% if !@issue.leaf? || User.current.allowed_to?(:manage_subtasks, @project) %>
diff --git a/app/views/projects/settings/_groupissuescustomfields.html.erb b/app/views/projects/settings/_groupissuescustomfields.html.erb
new file mode 100644
index 000000000..58f8318c3
--- /dev/null
+++ b/app/views/projects/settings/_groupissuescustomfields.html.erb
@@ -0,0 +1,140 @@
+<p><%= select_tag "tracker_id", options_from_collection_for_select(@project.trackers.collect, "id", "name"), {:required => true, :onchange => "refresh_trackers(this);"} %><p>
+
+<div id='custom_fields_form'>
+  <% @project.trackers.each do |t| %>
+  <div id='tracker_<%= t.id %>' class='tracker'>
+    <span style="color: #888;"><%= l(:changed_cf_position) %></span>
+    <ul class='sortable_items sortable_tracker-<%= t.id %> nil not_a_group'>
+      <% @cfs.select{|x| x[0]==t.id && x[2]==nil}.each do |x| %>
+      <li id="<%= x[6] %>" pos="<%= x[8] %>"><%= x[7] %></li>
+      <% end %>
+    </ul>
+    <span style="color: #888;"><%= l(:global_cf_position) %></span>
+    <ul class="sortable_items sortable_tracker-<%= t.id %> unsorted not_a_group">
+      <% Issue.new(project_id: @project.id, tracker_id: t.id).custom_field_values.
+           select{|x| ! @cfs.select{|c| c[0]==t.id}.map{|c| c[6]}.include?(x.custom_field_id)}.
+           collect{|x| [x.custom_field.id, x.custom_field.name, x.custom_field.position]}.each do |x| %>
+      <li id="<%= x[0] %>" pos="<%= x[2] %>"><%= x[1] %></li>
+      <% end %>
+    </ul>
+    <span style="color: #888;"><%= l(:grouped_cf) %></span>
+    <div class='sortable_groups groups_tracker-<%= t.id %>'>
+      <% @cfs.select{|x| x[0]==t.id && x[2]!=nil}.map{|x| x[2]}.uniq.each do |g| %>
+      <div class="sortable_group">
+        <input type="text" value="<%= g %>" style="background: #ddf; padding: 5px; width: 360px"/>
+        <img src="/images/delete.png" onclick="remove_label(this, 'tracker-<%= t.id %>');"/>
+        <ul class='sortable_items sortable_tracker-<%= t.id %>'>
+          <% @cfs.select{|x| x[0]==t.id && x[2]==g}.each do |x| %>
+          <li id="<%= x[6] %>" pos="<%= x[8] %>"><%= x[7] %></li>
+          <% end %>
+        </ul>
+      </div>
+      <% end %>
+      <div>
+        <input type="text" value="" style="background: #ddf; padding: 5px; width: 370px"/>
+        <img src="/images/add.png" style="" onclick="add_label(this, 'tracker-<%= t.id %>');"/>
+      </div>
+    </div>
+  </div>
+  <% end %>
+<%= form_for @project, :url => { :action => 'groupissuescustomfields', :id => @project },
+            :html => {:id => 'groupissuescustomfields-form',
+                      :method => :post} do |f| %>
+
+<%= hidden_field :group_issues_custom_fields, '', :id => 'group_issues_custom_fields', :name => 'group_issues_custom_fields' %>
+<p><%= submit_tag l(:button_save), :onclick => "fill_json_data();" %></p>
+<% end %>
+</div>
+
+<script>
+function init_sortables(labelclass) {
+  $( '.groups_' + labelclass ).sortable({
+    items: 'div.sortable_group',
+    connectWith: '.groups_' + labelclass,
+    start: function(event, ui) {
+      ui.placeholder.height(ui.item.height());
+    },
+    axis: 'y'
+  });
+  $( '.sortable_' + labelclass ).sortable({
+    connectWith: '.sortable_' + labelclass,
+    update: function(event, ui) {
+      if (ui.item.parent().hasClass('unsorted')) {
+        ui.item.parent().prepend(ui.item);
+        ui.item.parent().children('li').each(function () {
+          if (parseInt($(this).attr('pos')) < parseInt(ui.item.attr('pos'))) {
+            ui.item.insertAfter(this);
+          }
+        });
+      }
+    },
+    axis: 'y'
+  }).disableSelection();
+}
+function refresh_trackers(tracker) {
+  $('.tracker').hide();
+  $('#tracker_' + tracker.value).show();
+}
+function add_label(label, labelclass) {
+  var old_label = $(label), new_label = $(label).parent().clone();
+  new_label.children().first().val('').trigger('change');
+  old_label.attr('src','/images/delete.png').attr('onclick','remove_label(this, "' + labelclass + '");');
+  old_label.prev().width('360px');
+  old_label.parent().addClass('ui-sortable-handle sortable_group');
+  old_label.parent().sortable({
+    connectWith: '.groups_' + labelclass
+  }).disableSelection();
+  old_label.parent().append('<ul id="' + labelclass + '_" class="sortable_items sortable_' + labelclass + '"/>');
+  old_label.next().sortable({
+    connectWith: '.sortable_' + labelclass
+  }).disableSelection();
+  old_label.parent().parent().append(new_label);
+}
+function remove_label(label, labelclass) {
+  $(label).next().children().each(function () {
+    var item = this;
+    $('.unsorted.sortable_' + labelclass).prepend(this);
+    $('.unsorted.sortable_' + labelclass).children('li').each(function () {
+      if (parseInt($(this).attr('pos')) < parseInt($(item).attr('pos'))) {
+        $(item).insertAfter(this);
+      }
+    });
+  });
+  $(label).parent().hide();
+}
+function fill_json_data() {
+  var r = {}, gp = 0, cp = 0;
+  $('#custom_fields_form').children('div').each(function () {
+    var tracker_id = this.id.split('_').pop();
+    gp = 0, cp = 0;
+
+    // Group 'nil'
+    r[tracker_id] = {};
+    r[tracker_id][++gp] = {'cfs': {}};
+    $(this).children('.nil').children().each(function () {
+      cp++;
+      r[tracker_id][gp]['cfs'][cp] = this.id;
+    });
+    if (! r[tracker_id][gp]['cfs'][1]) { delete r[tracker_id][gp]; }
+    $(this).children('.sortable_groups').children().each(function () {
+      if ($(this).children('ul').length) {
+        r[tracker_id][++gp] = {
+          'name': $(this).children('input').val(),
+          'cfs': {}
+        };
+        cp = 0;
+        $(this).children('ul').children().each(function () {
+          r[tracker_id][gp]['cfs'][++cp] = this.id;
+        });
+        if (! r[tracker_id][gp]['cfs'][1]) { r[tracker_id][gp] = ''; }
+      }
+    });
+    if ( ! r[tracker_id] ) { r[tracker_id] = ''; }
+  });
+  console.log(r);
+  $('#group_issues_custom_fields').val(JSON.stringify(r)); }
+$('#tracker_id').change();
+<% @project.trackers.each do |t| %>
+init_sortables('tracker-<%= t.id %>');
+<% end %>
+</script>
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 2bbd776a3..7131553c0 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1366,6 +1366,9 @@ en:
   description_issue_category_reassign: Choose issue category
   description_wiki_subpages_reassign: Choose new parent page
   text_repository_identifier_info: 'Only lower case letters (a-z), numbers, dashes and underscores are allowed.<br />Once saved, the identifier cannot be changed.'
+  grouped_cf: Grouped Custom Fields
+  global_cf_position: Global Custom Fields Position
+  changed_cf_position: Changed Custom Fields Position
   text_login_required_html: When not requiring authentication, public projects and their contents are openly available on the network. You can <a href="%{anonymous_role_path}">edit the applicable permissions</a>.
   label_login_required_yes: "Yes"
   label_login_required_no: "No, allow anonymous access to public projects"
diff --git a/config/locales/pt-BR.yml b/config/locales/pt-BR.yml
index 6eebf1d47..661d2972c 100644
--- a/config/locales/pt-BR.yml
+++ b/config/locales/pt-BR.yml
@@ -1227,6 +1227,9 @@ pt-BR:
   permission_view_news: Ver notícias
   label_no_preview_alternative_html: Visualização não disponível. Faça o %{link} do arquivo.
   label_no_preview_download: download
+  grouped_cf: Agrupar campos personalizados
+  global_cf_position: Posição global de campos personalizados
+  changed_cf_position: Alterar posição de campos personalizados
   setting_close_duplicate_issues: Fechar tarefas duplicadas automaticamente
   error_exceeds_maximum_hours_per_day: Não é possível registrar mais de %{max_hours} horas no mesmo dia (%{logged_hours} horas já foram registradas)
   setting_time_entry_list_defaults: Registro de horas padrão
diff --git a/config/routes.rb b/config/routes.rb
index 540f3d0af..7c2e43682 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -137,6 +137,7 @@ Rails.application.routes.draw do
 
     member do
       get 'settings(/:tab)', :action => 'settings', :as => 'settings'
+      post 'groupissuescustomfields'
       match 'archive', :via => [:post, :put]
       match 'unarchive', :via => [:post, :put]
       match 'close', :via => [:post, :put]
diff --git a/db/migrate/20180913211420_create_attribute_groups.rb b/db/migrate/20180913211420_create_attribute_groups.rb
new file mode 100644
index 000000000..f582cd18d
--- /dev/null
+++ b/db/migrate/20180913211420_create_attribute_groups.rb
@@ -0,0 +1,12 @@
+class CreateAttributeGroups < ActiveRecord::Migration[4.2]
+  def change
+    create_table :attribute_groups do |t|
+      t.references :project, index: true, foreign_key: true
+      t.references :tracker, index: true, foreign_key: true
+      t.string :name
+      t.integer :position, :default => nil, :null => true
+
+      t.timestamps null: false
+    end
+  end
+end
diff --git a/db/migrate/20180913212008_create_attribute_group_fields.rb b/db/migrate/20180913212008_create_attribute_group_fields.rb
new file mode 100644
index 000000000..a36371c67
--- /dev/null
+++ b/db/migrate/20180913212008_create_attribute_group_fields.rb
@@ -0,0 +1,11 @@
+class CreateAttributeGroupFields < ActiveRecord::Migration[4.2]
+  def change
+    create_table :attribute_group_fields do |t|
+      t.references :attribute_group, index: true, foreign_key: true
+      t.references :custom_field, index: true, foreign_key: true
+      t.integer :position
+
+      t.timestamps null: false
+    end
+  end
+end
diff --git a/lib/redmine/export/pdf/issues_pdf_helper.rb b/lib/redmine/export/pdf/issues_pdf_helper.rb
index 834cd6db8..2a6008b8c 100644
--- a/lib/redmine/export/pdf/issues_pdf_helper.rb
+++ b/lib/redmine/export/pdf/issues_pdf_helper.rb
@@ -66,12 +66,6 @@ module Redmine
           left  << nil while left.size  < rows
           right << nil while right.size < rows
 
-          custom_field_values = issue.visible_custom_field_values.reject {|value| value.custom_field.full_width_layout?}
-          half = (custom_field_values.size / 2.0).ceil
-          custom_field_values.each_with_index do |custom_value, i|
-            (i < half ? left : right) << [custom_value.custom_field.name, show_value(custom_value, false)]
-          end
-
           if pdf.get_rtl
             border_first_top = 'RT'
             border_last_top  = 'LT'
@@ -83,6 +77,7 @@ module Redmine
             border_first = 'L'
             border_last  = 'R'
           end
+          border_middle_top  = 'T'
 
           rows = [left.size, right.size].max
           rows.times do |i|
@@ -105,12 +100,12 @@ module Redmine
                              (i == 0 ? border_first_top : border_first), '', 0, 0)
             pdf.SetFontStyle('', 9)
             pdf.RDMMultiCell(60, height, item ? item.last.to_s : "",
-                             (i == 0 ? border_last_top : border_last), '', 0, 0)
+                             (i == 0 ? border_middle_top : ""), '', 0, 0)
 
             item = right[i]
             pdf.SetFontStyle('B', 9)
             pdf.RDMMultiCell(35, height, item ? "#{item.first}:" : "",
-                             (i == 0 ? border_first_top : border_first), '', 0, 0)
+                             (i == 0 ? border_middle_top : ""), '', 0, 0)
             pdf.SetFontStyle('', 9)
             pdf.RDMMultiCell(60, height, item ? item.last.to_s : "",
                              (i == 0 ? border_last_top : border_last), '', 0, 2)
@@ -118,14 +113,86 @@ module Redmine
             pdf.set_x(base_x)
           end
 
+          group_by_keys(issue.project_id, issue.tracker_id, issue.visible_custom_field_values).each do |title, values|
+            if values.present?
+              unless title.nil?
+                pdf.RDMCell(35 + 155, 5, title, "LRT", 1)
+              end
+
+              while values.present?
+                if values[0].custom_field.full_width_layout?
+                  while values.present? && values[0].custom_field.full_width_layout?
+                    heights = []
+                    value = values.shift
+                    pdf.SetFontStyle('B', 9)
+                    heights << pdf.get_string_height(35, "#{value.custom_field.name}:")
+                    pdf.SetFontStyle('',9)
+                    heights << pdf.get_string_height(155, show_value(value, false))
+                    height = heights.max
+
+                    pdf.SetFontStyle('B',9)
+                    pdf.RDMMultiCell(35, height, "#{value.custom_field.name}:", border_first, '', 0, 0)                               
+                    pdf.SetFontStyle('', 9)
+                    pdf.RDMMultiCell(155, height, show_value(value, false), border_last, '', 0, 2)
+
+                    pdf.set_x(base_x)
+                  end
+                else
+                  lr_values = []
+                  while values.present? && ! values[0].custom_field.full_width_layout?
+                    lr_values += [ values.shift ]
+                  end
+
+                  half = (lr_values.size / 2.0).ceil
+                  left = []
+                  right = []
+                  lr_values.each_with_index do |custom_value, i|
+                    (i < half ? left : right) << [custom_value.custom_field.name, show_value(custom_value, false)]
+                  end
+
+                  rows = left.size > right.size ? left.size : right.size
+                  rows.times do |i|
+                    heights = []
+                    pdf.SetFontStyle('B', 9)
+                    item = left[i]
+                    heights << pdf.get_string_height(35, item ? "#{item.first}:" : "")
+                    item = right[i]
+                    heights << pdf.get_string_height(35, item ? "#{item.first}:" : "")
+                    pdf.SetFontStyle('', 9)
+                    item = left[i]
+                    heights << pdf.get_string_height(60, item ? item.last.to_s  : "")
+                    item = right[i]
+                    heights << pdf.get_string_height(60, item ? item.last.to_s  : "")
+                    height = heights.max
+
+                    item = left[i]
+                    pdf.SetFontStyle('B', 9)
+                    pdf.RDMMultiCell(35, height, item ? "#{item.first}:" : "", border_first, '', 0, 0)
+                    pdf.SetFontStyle('', 9)
+                    pdf.RDMMultiCell(60, height, item ? item.last.to_s : "", "", '', 0, 0)
+
+                    item = right[i]
+                    pdf.SetFontStyle('B', 9)
+                    pdf.RDMMultiCell(35, height, item ? "#{item.first}:" : "",  "", '', 0, 0)
+                    pdf.SetFontStyle('', 9)
+                    pdf.RDMMultiCell(60, height, item ? item.last.to_s : "", border_last, '', 0, 2)
+
+                    pdf.set_x(base_x)
+                  end
+                end
+              end
+            end
+          end
+
           pdf.SetFontStyle('B', 9)
           pdf.RDMCell(35 + 155, 5, l(:field_description), "LRT", 1)
           pdf.SetFontStyle('', 9)
 
           # Set resize image scale
           pdf.set_image_scale(1.6)
+
           text = pdf_format_text(issue, :description)
-          pdf.RDMwriteFormattedCell(35+155, 5, '', '', text, issue.attachments, "LRB")
+          pdf.RDMwriteFormattedCell(35 + 155, 5, '', '', text, issue.attachments, "LRB")
 
           custom_field_values = issue.visible_custom_field_values.select {|value| value.custom_field.full_width_layout?}
           custom_field_values.each do |value|
@@ -134,19 +201,19 @@ module Redmine
             next if text.blank?
 
             pdf.SetFontStyle('B', 9)
-            pdf.RDMCell(35+155, 5, value.custom_field.name, "LRT", 1)
+            pdf.RDMCell(35 + 155, 5, value.custom_field.name, "LRT", 1)
             pdf.SetFontStyle('', 9)
             if is_html
-              pdf.RDMwriteFormattedCell(35+155, 5, '', '', text, issue.attachments, "LRB")
+              pdf.RDMwriteFormattedCell(35 + 155, 5, '', '', text, issue.attachments, "LRB")
             else
-              pdf.RDMwriteHTMLCell(35+155, 5, '', '', text, issue.attachments, "LRB")
+              pdf.RDMwriteHTMLCell(35 + 155, 5, '', '', text, issue.attachments, "LRB")
             end
           end
 
           unless issue.leaf?
             truncate_length = (!is_cjk? ? 90 : 65)
             pdf.SetFontStyle('B', 9)
-            pdf.RDMCell(35+155, 5, l(:label_subtask_plural) + ":", "LTR")
+            pdf.RDMCell(35 + 155, 5, l(:label_subtask_plural) + ":", "LTR")
             pdf.ln
             issue_list(issue.descendants.visible.sort_by(&:lft)) do |child, level|
               buf = "#{child.tracker} # #{child.id}: #{child.subject}".
@@ -177,7 +244,7 @@ module Redmine
               end
               buf = buf.truncate(truncate_length)
               pdf.SetFontStyle('', 8)
-              pdf.RDMCell(35+155-60, 5, buf, border_first)
+              pdf.RDMCell(35 + 155 - 60, 5, buf, border_first)
               pdf.SetFontStyle('B', 8)
               pdf.RDMCell(20, 5, relation.other_issue(issue).status.to_s, "")
               pdf.RDMCell(20, 5, format_date(relation.other_issue(issue).start_date), "")
diff --git a/lib/redmine/preparation.rb b/lib/redmine/preparation.rb
index 64333672a..06da9cab0 100644
--- a/lib/redmine/preparation.rb
+++ b/lib/redmine/preparation.rb
@@ -36,7 +36,7 @@ module Redmine
         map.permission :view_project, {:projects => [:show, :bookmark], :activities => [:index]}, :public => true, :read => true
         map.permission :search_project, {:search => :index}, :public => true, :read => true
         map.permission :add_project, {:projects => [:new, :create]}, :require => :loggedin
-        map.permission :edit_project, {:projects => [:settings, :edit, :update]}, :require => :member
+        map.permission :edit_project, {:projects => [:settings, :edit, :update, :groupissuescustomfields]}, :require => :member
         map.permission :close_project, {:projects => [:close, :reopen]}, :require => :member, :read => true
         map.permission :delete_project, {:projects => :destroy}, :require => :member, :read => true
         map.permission :select_project_publicity, {}, :require => :member
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index 2015768d0..6c13f3994 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1971,3 +1971,48 @@ th[role=columnheader]:not(.no-sort):hover:after {
 	display: inline;
 	opacity: 1;
 }
+
+/* Custom Field Groups */
+.sortable_groups {
+  background: #eee;
+  border: 1px solid #888;
+  width: 445px;
+  min-height: 30px;
+  margin: 5px;
+  padding: 5px;
+}
+.sortable_groups div {
+  background: #ddf;
+  border: 1px solid #888;
+  min-height: 30px;
+  margin: 5px;
+  padding: 5px;
+}
+.sortable_items {
+  background: #eee;
+  border: 1px solid #888;
+  width: 400px;
+  min-height: 30px;
+  margin: 5px;
+  padding: 5px;
+}
+.sortable_items li {
+  background: #ffffff;
+  border: 1px solid #888;
+  margin: 5px;
+  padding: 5px;
+  list-style-type: none;
+  font-size: 1.2em;
+}
+.not_a_group {
+  padding: 5px 27px;
+}
+.ui-sortable-handle:before {
+  content:url('/images/reorder.png');
+  margin-right: 5px;
+}
+.ui-sortable-placeholder {
+  background: #8888ff;
+  border: 1px solid #888;
+  visibility: visible;
+}
diff --git a/test/fixtures/attribute_group_fields.yml b/test/fixtures/attribute_group_fields.yml
new file mode 100644
index 000000000..7b2302fad
--- /dev/null
+++ b/test/fixtures/attribute_group_fields.yml
@@ -0,0 +1,11 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
+
+one:
+  attribute_group_id:
+  custom_field_id:
+  position: 1
+
+two:
+  attribute_group_id:
+  custom_field_id:
+  position: 1
diff --git a/test/fixtures/attribute_groups.yml b/test/fixtures/attribute_groups.yml
new file mode 100644
index 000000000..9e634057b
--- /dev/null
+++ b/test/fixtures/attribute_groups.yml
@@ -0,0 +1,13 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
+
+one:
+  project_id:
+  tracker_id:
+  name: MyString
+  position: 1
+
+two:
+  project_id:
+  tracker_id:
+  name: MyString
+  position: 1
-- 
2.39.2

