This commit is contained in:
choibk 2026-01-05 12:28:46 +09:00
commit 7e172b0572
258 changed files with 60235 additions and 0 deletions

68
.gitignore vendored Normal file
View File

@ -0,0 +1,68 @@
# =========================
# OS / Editor
# =========================
.DS_Store
Thumbs.db
.vscode/
.idea/
*.swp
*.swo
# =========================
# Ruby / Rails
# =========================
.bundle/
vendor/bundle/
coverage/
tmp/
log/
*.log
# =========================
# Redmine / Rails cache
# =========================
public/assets/
public/packs/
node_modules/
.yarn/
.yarn-cache/
# =========================
# Database (local test only)
# =========================
*.sqlite3
*.sqlite3-journal
# =========================
# Test / CI artifacts
# =========================
spec/examples.txt
rerun.txt
# =========================
# Plugin build / generated files
# =========================
*.gem
pkg/
*.rbc
# =========================
# Security / Local override
# =========================
.env
.env.*
config/database.yml
config/secrets.yml
config/initializers/secret_token.rb
# =========================
# Easy plugins specific
# =========================
easy_*/tmp/
easy_*/log/
easy_*/public/assets/
# =========================
# Linter / Test scripts output
# =========================
.run-*.log

0
easy_baseline/Gemfile Normal file
View File

1
easy_baseline/README.md Normal file
View File

@ -0,0 +1 @@
# Easy Baseline

View File

@ -0,0 +1,22 @@
lib_dir = File.join(File.dirname(__FILE__), 'lib', 'easy_baseline')
# Redmine patches
patch_path = File.join(lib_dir, '*_patch.rb')
Dir.glob(patch_path).each do |file|
require file
end
require lib_dir
require File.join(lib_dir, 'hooks')
Redmine::AccessControl.map do |map|
map.project_module :easy_baselines do |pmap|
pmap.permission :view_baselines, {
easy_baselines: [:index, :show],
easy_baseline_gantt: [:show]
}
pmap.permission :edit_baselines, {
easy_baselines: [:create, :destroy, :new]
}
end
end

View File

@ -0,0 +1,44 @@
class EasyBaselineGanttController < ApplicationController
accept_api_auth :show
before_action :find_baseline
before_action :authorize
def show
# Wait for gantt modifications
issue_ids = @project.issues.pluck(:id)
version_ids = @project.versions.pluck(:id)
b_table = EasyBaselineSource.table_name
i_table = Issue.table_name
v_table = Version.table_name
@issues = @baseline.issues.
joins(:easy_baseline_source).
where(easy_baseline_sources: { source_id: issue_ids }).
pluck("#{i_table}.start_date, #{i_table}.due_date, #{i_table}.done_ratio, #{b_table}.source_id")
@versions = @baseline.easy_baseline_sources.
versions.
joins_baseline_versions.
where(easy_baseline_sources: { source_id: version_ids }).
pluck("#{v_table}.effective_date, #{b_table}.source_id")
respond_to do |format|
format.api
end
end
private
def find_baseline
@baseline = Project.includes(:easy_baseline_for).
where(id: params[:id]).
where.not(easy_baseline_for_id: nil).
first!
@project = @baseline.easy_baseline_for
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@ -0,0 +1,79 @@
class EasyBaselinesController < ApplicationController
accept_api_auth :index, :create, :destroy
before_action :find_project_by_project_id
before_action :authorize
before_action :authorize_baseline_source
include Redmine::I18n
include SortHelper
def index
@baselines = Project.where(easy_baseline_for: @project)
end
def new
prepare_baseline
end
def create
prepare_baseline
Mailer.with_deliveries(false) do
if @baseline.save(validate: false) && @baseline.copy(@project, only: ['versions', 'issues'], with_time_entries: false)
# Easyredmine copies time on {copy_issues}
@baseline.time_entries.destroy_all
respond_to do |format|
format.html {
flash[:notice] = l(:notice_easy_baseline_created, project_name: @project.name)
redirect_back_or_default project_easy_baselines_path(@project)
}
format.api { render_api_ok }
end
else
respond_to do |format|
format.html { render :new }
format.api { render_validation_errors(@baseline) }
end
end
end
end
def destroy
@baseline = Project.find(params[:id])
@baseline.destroy
respond_to do |format|
format.html {
flash[:notice] = l(:notice_successful_delete)
redirect_back_or_default project_easy_baselines_path(@project)
}
format.api { head :no_content }
end
end
private
def prepare_baseline(options={})
options[:name] = params[:easy_baseline][:name] if params[:easy_baseline]
@baseline = Project.copy_from(@project)
@baseline.status = Project::STATUS_ARCHIVED
# Without this hack it disables a modules on original project see http://www.redmine.org/issues/20512 for details
@baseline.enabled_modules = []
@baseline.enabled_module_names = @project.enabled_module_names
@baseline.name = options[:name] || (format_time(Time.now) + ' ' + @project.name)
@baseline.identifier = options[:name].present? ? options[:name].parameterize : @project.identifier + '_' + Time.now.strftime('%Y%m%d%H%M%S')
@baseline.easy_baseline_for_id = @project.id
@baseline.parent = EasyBaseline.baseline_root_project
# Project.copy_from change customized so CV are not copyied but moved
# Already done in easyredmine
@baseline.custom_values = @project.custom_values.map{|v| cloned_v = v.dup; cloned_v.customized = @baseline; cloned_v}
end
def authorize_baseline_source
render_404 unless @project.easy_baseline_for.nil?
end
end

View File

View File

@ -0,0 +1,22 @@
class EasyBaselineSource < ActiveRecord::Base
belongs_to :baseline, class_name: 'Project'
scope :issues, -> { where(:relation_type => 'Issue') }
scope :versions, -> { where(:relation_type => 'Version') }
scope :with_source, -> { where.not(:source_id => nil) }
scope :without_source, -> { where(:source_id => nil) }
scope :joins_source_versions, -> { joins("INNER JOIN #{Version.table_name} ON #{self.table_name}.source_id = #{Version.table_name}.id") }
scope :joins_baseline_versions, -> { joins("INNER JOIN #{Version.table_name} ON #{self.table_name}.destination_id = #{Version.table_name}.id") }
def source
@source ||= self.relation_type.constantize.find(source_id)
end
def destination
@destination ||= self.relation_type.constantize.find(destination_id)
end
end

View File

View File

@ -0,0 +1,23 @@
api.easy_baseline_gantt do
api.array :issues do
@issues.each do |start_date, due_date, done_ratio, source_id|
api.issue do
api.connected_to_issue_id source_id
api.start_date start_date
api.due_date due_date
api.done_ratio done_ratio
end
end
end
api.array :versions do
@versions.each do |effective_date, source_id|
api.version do
api.connected_to_version_id source_id
api.start_date effective_date
end
end
end
end

View File

@ -0,0 +1,8 @@
api.array :easy_baselines do
@baselines.each do |baseline|
api.easy_baseline do
api.id baseline.id
api.name baseline.name
end
end
end

View File

@ -0,0 +1,32 @@
<div class="contextual">
<% if User.current.allowed_to?(:edit_baselines, @project) %>
<%# todo: show modal to pick baseline's name %>
<%#= link_to_function(l(:label_create_easy_baseline), "ysy.pro.baseline.openCreateModal()", :class => 'icon icon-add') %>
<%= link_to(l(:label_create_easy_baseline), project_easy_baselines_path(@project), :method => :post, :class => 'icon icon-add') %>
<% end %>
</div>
<h2><%= l(:label_easy_baselines) %></h2>
<table class="list">
<tr>
<th><%= l(:field_name) %></th>
<th><%= l(:field_project) %></th>
<th></th>
</tr>
<% @baselines.each do |baseline| %>
<tr class="<%= cycle 'odd', 'even' %>">
<td><%= baseline.name %></td>
<td><%= link_to baseline.easy_baseline_for.name, project_path(baseline.easy_baseline_for_id) %></td>
<td class="buttons">
<% if User.current.allowed_to?(:edit_baselines, @project) %>
<%= link_to l("button_delete"), project_easy_baseline_path(@project, baseline),
:method => 'delete', :class => "icon icon-del", :data => { :confirm => l(:text_are_you_sure) } %>
<% end %>
</td>
</tr>
<% end %>
</table>

View File

@ -0,0 +1,2 @@
<%= error_messages_for(@baseline) %>
<%= button_to(l(:label_try_again), project_easy_baselines_path(@project, back_url: params[:back_url])) %>

View File

View File

@ -0,0 +1,2 @@
---
ar:

View File

@ -0,0 +1,11 @@
---
cs:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Baseline pro
label_create_easy_baseline: Vytvořit baseline
label_easy_baselines: Easy Baselines
label_try_again: Zkusit znovu
notice_easy_baseline_created: Baseline projektu %{project_name} úspěšně vytvořena

View File

@ -0,0 +1,2 @@
---
da:

View File

@ -0,0 +1,13 @@
---
de:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/de
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Basisplan
easy_baseline_project_prefix: Basisplan für
field_easy_baseline_for: Baseline
label_create_easy_baseline: Basisplan erstellen
label_easy_baselines: Easy Basispläne
label_try_again: Wiederholen
notice_easy_baseline_created: Basisplan für den Projekt %{project_name} wurde
erfolgreich erstellt

View File

@ -0,0 +1,2 @@
---
en-AU:

View File

@ -0,0 +1,2 @@
---
en-GB:

View File

@ -0,0 +1,2 @@
---
en-US:

View File

@ -0,0 +1,13 @@
---
en:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Baseline for
field_easy_baseline_for: Baseline
label_create_easy_baseline: Create baseline
label_easy_baselines: Easy Baselines
label_try_again: Try again
notice_easy_baseline_created: Baseline for project %{project_name} succesfully created
project_module_easy_baselines: Easy Baselines

View File

@ -0,0 +1,13 @@
---
es:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/es
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Referencia para
field_easy_baseline_for: Referencia
label_create_easy_baseline: Crear referencia
label_easy_baselines: Easy Baselines
label_try_again: Inténtalo de nuevo
notice_easy_baseline_created: La referencia para el proyecto %{project_name} se
ha creado correctamente

View File

@ -0,0 +1,2 @@
---
fi:

View File

@ -0,0 +1,13 @@
---
fr:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: ''
field_easy_baseline_for: Point de comparaison (baseline)
label_create_easy_baseline: Établir un point de comparaison
label_easy_baselines: Easy Baselines
label_try_again: Essayer à nouveau
notice_easy_baseline_created: Ligne de base pour projet %{project_name} créé avec
succès

View File

@ -0,0 +1,2 @@
---
he:

View File

@ -0,0 +1,2 @@
---
hr:

View File

@ -0,0 +1,12 @@
---
hu:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Baseline erre
field_easy_baseline_for: Alapérték
label_create_easy_baseline: Alapvonal létrehozása
label_easy_baselines: Easy Baselines
label_try_again: Próbálja újra
notice_easy_baseline_created: Alapvonal létrehozva a %{project_name} projekthez

View File

@ -0,0 +1,13 @@
---
it:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Baseline per
field_easy_baseline_for: Baseline
label_create_easy_baseline: Crea baseline
label_easy_baselines: Easy Baselines
label_try_again: Prova di nuovo
notice_easy_baseline_created: Baseline per il progetto %{project_name} creata con
successo

View File

@ -0,0 +1,13 @@
---
ja:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Baseline for
field_easy_baseline_for: ベースライン
label_create_easy_baseline: ベースラインの作成
label_easy_baselines: ベースライン管理
label_try_again: 再度実行してください
notice_easy_baseline_created: "%{project_name} のベースラインは正常に作成されました"
project_module_easy_baselines: 簡単なベースライン

View File

@ -0,0 +1,12 @@
---
ko:
easy_baseline_plugin_author: 이지 소프트웨어
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: 이지 베이스라인
easy_baseline_project_prefix: 를 위한 베이스라인
field_easy_baseline_for: 기준
label_create_easy_baseline: 베이스라인 작성
label_easy_baselines: 이지 베이스라인
label_try_again: 다시 시도하세요
notice_easy_baseline_created: 프로젝트 %{project_name}를 위한 베이스라인이 성공적으로 생성되었습니다

View File

@ -0,0 +1,2 @@
---
mk:

View File

@ -0,0 +1,12 @@
---
nl:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/nl
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Baseline voor
field_easy_baseline_for: Baseline
label_create_easy_baseline: Maak baseline
label_easy_baselines: Easy Baselines
label_try_again: Probeer opnieuw
notice_easy_baseline_created: Baseline voor project %{project_name} aangemaakt

View File

@ -0,0 +1,2 @@
---
'no':

View File

@ -0,0 +1,12 @@
---
pl:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/pl
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Bazy Easy
easy_baseline_project_prefix: Baza dla
field_easy_baseline_for: Linia bazowa
label_create_easy_baseline: Utwórz bazę
label_easy_baselines: Bazy Easy
label_try_again: Spróbuj ponownie
notice_easy_baseline_created: Baza dla projektu %{project_name} została utworzona

View File

@ -0,0 +1,13 @@
---
pt-BR:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Easy Baseline
easy_baseline_project_prefix: Linha de base para
field_easy_baseline_for: Linha de base.
label_create_easy_baseline: Criar linha de base
label_easy_baselines: Easy Baselines
label_try_again: Tentar novamente
notice_easy_baseline_created: Linha de base para o projeto %{project_name} criada
com sucesso

View File

@ -0,0 +1,2 @@
---
pt:

View File

@ -0,0 +1,2 @@
---
ro:

View File

@ -0,0 +1,12 @@
---
ru:
easy_baseline_plugin_author: Easy Software
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: ''
easy_baseline_plugin_name: Базовый план
easy_baseline_project_prefix: Базовый план для
field_easy_baseline_for: Базовый план
label_create_easy_baseline: Создать базовый план
label_easy_baselines: Базовые планы
label_try_again: Попробуйте еще раз
notice_easy_baseline_created: Базовый план для проекта %{project_name} создан.

View File

@ -0,0 +1,2 @@
---
sk:

View File

@ -0,0 +1,6 @@
---
sl:
easy_baseline_project_prefix: Referenčni načrt za
label_create_easy_baseline: Ustvari referenčni načrt
label_try_again: Poskusi znova
notice_easy_baseline_created: Uspešno ustvarjen referenčni načrt za projekt %{project_name}

View File

@ -0,0 +1,2 @@
---
sq:

View File

@ -0,0 +1,2 @@
---
sr-YU:

View File

@ -0,0 +1,2 @@
---
sr:

View File

@ -0,0 +1,2 @@
---
sv:

View File

@ -0,0 +1,2 @@
---
th:

View File

@ -0,0 +1,2 @@
---
tr:

View File

@ -0,0 +1,2 @@
---
zh-TW:

View File

@ -0,0 +1,12 @@
---
zh:
easy_baseline_plugin_author: EASY软件
easy_baseline_plugin_author_url: http://www.easyproject.cz/en
easy_baseline_plugin_description: Baseline-原始时间线
easy_baseline_plugin_name: Easy 原始时间线
easy_baseline_project_prefix: '下列项目的原时间线(Baseline):'
field_easy_baseline_for: 原时间线
label_create_easy_baseline: 创建原时间线(Baseline)
label_easy_baselines: Easy原时间线(Baseline)
label_try_again: 重试
notice_easy_baseline_created: 项目 %{project_name}的原时间线(Baseline)创建成功

View File

@ -0,0 +1,6 @@
resources :projects do
resources :easy_baselines, :except => [:show, :edit, :update]
end
resources :easy_baseline_gantt, :only => :show

View File

@ -0,0 +1,5 @@
class AddEasyBaselineForToProject < ActiveRecord::Migration[6.1]
def change
add_reference :projects, :easy_baseline_for, index: true
end
end

View File

@ -0,0 +1,10 @@
class CreateEasyBaselineSources < ActiveRecord::Migration[6.1]
def change
create_table :easy_baseline_sources do |t|
t.references :baseline, index: true
t.references :source
t.references :destination
t.string :relation_type
end
end
end

11
easy_baseline/init.rb Normal file
View File

@ -0,0 +1,11 @@
Redmine::Plugin.register :easy_baseline do
name 'Easy Baseline'
author 'Easy Software Ltd'
url 'https://www.easysoftware.com'
author_url 'https://www.easysoftware.com'
description 'Allow to create a snapshot of a project in time.'
version '3.0'
end
require_relative 'after_init'

View File

@ -0,0 +1,23 @@
module EasyBaseline
IDENTIFIER = 'easy_baselines-root'
def self.baseline_root_project
project = Project.find_by_identifier(IDENTIFIER)
return project if project
project = Project.new(identifier: IDENTIFIER)
project.name = 'Easy Baselines Root'
project.status = Project::STATUS_ARCHIVED
project.is_public = false
project.save!(validate: false)
project
# Project.where(identifier: IDENTIFIER).first_or_create! do |project|
# project.name = 'Easy Baselines Root'
# project.status = Project::STATUS_ARCHIVED
# project.is_public = false
# end
end
end

View File

@ -0,0 +1,9 @@
module EasyBaseline
class Hooks < Redmine::Hook::ViewListener
def model_project_copy_before_save(context={ })
context[:destination_project].status = Project::STATUS_ARCHIVED if context[:destination_project].easy_baseline_for_id
end
end
end

View File

@ -0,0 +1,24 @@
module EasyBaseline
module IssuePatch
def self.prepended(base)
base.class_eval do
has_one :easy_baseline_source, -> { where(relation_type: 'Issue') }, class_name: 'EasyBaselineSource', foreign_key: :destination_id, dependent: :nullify
has_many :easy_baseline_destinations, -> { where(relation_type: 'Issue') }, class_name: 'EasyBaselineSource', foreign_key: :source_id, dependent: :destroy
after_save :create_baseline_from_copy, if: :copy?
def create_baseline_from_copy
return if self.project.easy_baseline_for_id.nil?
EasyBaselineSource.create(baseline_id: self.project_id, relation_type: 'Issue', source_id: @copied_from.id, destination_id: self.id)
end
end
end
end
end
Issue.prepend EasyBaseline::IssuePatch

View File

@ -0,0 +1,83 @@
module EasyBaseline
module ProjectPatch
def self.prepended(base)
base.prepend InstanceMethods
base.singleton_class.prepend(ClassMethods)
base.class_eval do
belongs_to :easy_baseline_for, class_name: 'Project'
has_many :easy_baseline_sources, foreign_key: 'baseline_id'
before_save :prevent_unarchive_easy_baseline
end
end
module InstanceMethods
def baseline_root?
identifier == EasyBaseline::IDENTIFIER
end
def copy_versions(project)
super
if self.easy_baseline_for_id == project.id
self.versions.each do |v|
v.copied_from = project.versions.detect{|cv| cv.name == v.name }
v.save
end
end
end
def allows_to(action)
return true if easy_baseline_for_id && archived?
super
end
def validate_custom_field_values_with_easy_baseline
if baseline_root? && archived?
true
else
super
end
end
private
def validate_parent_with_easy_baseline
if @unallowed_parent_id
errors.add(:parent_id, :invalid)
elsif parent_id_changed?
if parent.present? && (!parent.active? || !move_possible?(parent)) && !parent.baseline_root?
errors.add(:parent_id, :invalid)
end
end
end
def prevent_unarchive_easy_baseline
if (easy_baseline_for_id || baseline_root?) && status_changed? && !archived?
errors.add(:status, :invalid)
return false
end
end
end
module ClassMethods
def allowed_to_condition(user, permission, options={}, &block)
condition = super
if options[:easy_baseline].present?
condition.gsub!("#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND", "")
end
condition
end
end
end
end
Project.prepend EasyBaseline::ProjectPatch

View File

@ -0,0 +1,28 @@
module EasyBaseline
module VersionPatch
def self.prepended(base)
base.class_eval do
after_save :create_baseline_from_copy, if: :copy?
attr_accessor :copied_from
def copy?
@copied_from.present?
end
private
def create_baseline_from_copy
return if self.project.easy_baseline_for_id.nil?
EasyBaselineSource.create(baseline_id: self.project_id, relation_type: 'Version', source_id: @copied_from.id, destination_id: self.id)
end
end
end
end
end
Version.prepend EasyBaseline::VersionPatch

View File

@ -0,0 +1,35 @@
require File.expand_path('../../../../easyproject/easy_plugins/easy_extensions/test/spec/spec_helper', __FILE__)
describe EasyBaselinesController, :logged => :admin do
let(:project) { FactoryGirl.create(:project, :add_modules => %w(easy_baselines easy_gantt)) }
around(:each) do |example|
with_settings(rest_api_enabled: 1) do
example.run
end
end
describe '#new' do
it 'accept name param' do
get :new, project_id: project, easy_baseline: { name: 'Specialni jmeno' }
expect(assigns(:baseline).name).to eq('Specialni jmeno')
end
it 'baselines project' do
project
expect{
get :new, project_id: project, easy_baseline: { name: 'Specialni jmeno' }
}.to change(Project, :count).by(1)
end
it 'baselines project with identifiers enabled' do
project
with_easy_settings(:project_display_identifiers => true) do
expect{
get :new, project_id: project, easy_baseline: { name: 'Specialni jmeno' }
}.to change(Project, :count).by(1)
end
end
end
end

1
easy_gantt/Gemfile Normal file
View File

@ -0,0 +1 @@

60
easy_gantt/LICENSE Normal file
View File

@ -0,0 +1,60 @@
LICENCE
All Easy Redmine Extensions are distributed under GNU/GPL 2 license (see below).
If not otherwise stated, all images, cascading style sheets, and included JavaScript are NOT GPL, and are released under the Easy Redmine Commercial Use License (see below).
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
EASY REDMINE COMMERCIAL USE LICENSE
The Easy Redmine Commercial Use License is a GPL compatible license that pertains only to the images, cascading style sheets and JavaScript elements of Easy Redmine Themes and Styles produced by Easy Software Ltd. As stated by the GPL version 2.0 license, these elements of product that are not compiled together but are sent independently of GPL code, and combined in a client's browser, do not have to be GPL themselves. These images, cascading style sheets and JavaScript elements are copyright Easy Software Ltd. and can be used and manipulated for your own or if you have signed Easy Redmine Partner Agreement for your clients purposes. You cannot redistribute these files as your own, or include them in any package or extension of your own without prior consent of Easy Software Ltd.
Unauthorised distribution or making it accessible to a third party without prior Easy Software Ltd. consent, authorizes Easy Software Ltd. to invoice contractual penalty in the amount of 10 000 EUR for any breach of the this License.

3
easy_gantt/README.md Normal file
View File

@ -0,0 +1,3 @@
# Easy Gantt
For documentation and requirements, go to https://www.easyredmine.com/redmine-gantt-plugin

97
easy_gantt/after_init.rb Normal file
View File

@ -0,0 +1,97 @@
lib_dir = File.join(File.dirname(__FILE__), 'lib', 'easy_gantt')
# Redmine patches
patch_path = File.join(lib_dir, '*_patch.rb')
Dir.glob(patch_path).each do |file|
require file
end
require lib_dir
require File.join(lib_dir, 'hooks')
Redmine::MenuManager.map :top_menu do |menu|
menu.push(:easy_gantt, { controller: 'easy_gantt', action: 'index', set_filter: 0 },
caption: :label_easy_gantt,
after: :documents,
icon: 'stats',
html: { class: 'icon icon-stats' },
if: proc { User.current.allowed_to_globally?(:view_global_easy_gantt) })
end
Redmine::MenuManager.map :project_menu do |menu|
menu.push(:easy_gantt, { controller: 'easy_gantt', action: 'index' },
param: :project_id,
caption: :button_project_menu_easy_gantt,
if: proc { |p| User.current.allowed_to?(:view_easy_gantt, p) })
end
Redmine::MenuManager.map :easy_gantt_tools do |menu|
menu.push(:back, 'javascript:void(0)',
param: :project_id,
caption: :button_back,
icon: 'chevrons-left',
html: { icon: 'icon-chevrons-left' })
menu.push(:task_control, 'javascript:void(0)',
param: :project_id,
caption: :button_edit,
icon: 'edit',
html: { icon: 'icon-edit' })
menu.push(:add_task, 'javascript:void(0)',
param: :project_id,
caption: :label_new,
icon: 'add',
html: { trial: true, icon: 'icon-add' },
if: proc { |p| p.present? })
menu.push(:critical, 'javascript:void(0)',
param: :project_id,
caption: :'easy_gantt.button.critical_path',
icon: 'summary',
html: { trial: true, icon: 'icon-summary' },
if: proc { |p| p.present? })
menu.push(:baseline, 'javascript:void(0)',
param: :project_id,
caption: :'easy_gantt.button.create_baseline',
icon: 'projects',
html: { trial: true, icon: 'icon-projects icon-project' },
if: proc { |p| p.present? })
end
Redmine::AccessControl.map do |map|
map.project_module :easy_gantt do |pmap|
# View project level
pmap.permission(:view_easy_gantt, {
easy_gantt: [:index, :issues, :projects],
easy_gantt_pro: [:lowest_progress_tasks, :cashflow_data]
}, read: true)
# Edit project level
pmap.permission(:edit_easy_gantt, {
easy_gantt: [:change_issue_relation_delay, :reschedule_project]
}, require: :member)
# View global level
pmap.permission(:view_global_easy_gantt, {
easy_gantt: [:index, :issues, :projects, :project_issues],
easy_gantt_pro: [:lowest_progress_tasks, :cashflow_data]
}, global: true, read: true)
# Edit global level
pmap.permission(:edit_global_easy_gantt, {
}, global: true, require: :loggedin)
# View personal level
# pmap.permission(:view_personal_easy_gantt, {
# }, global: true, read: true)
# Edit personal level
pmap.permission(:edit_personal_easy_gantt, {
}, global: true, require: :loggedin)
end
end

View File

@ -0,0 +1,261 @@
class EasyGanttController < ApplicationController
accept_api_auth :index, :issues, :projects, :project_issues, :change_issue_relation_delay, :reschedule_project
menu_item :easy_gantt
RELATION_TYPES_TO_LOAD = ['relates', 'blocks', 'blocked', 'precedes', 'follows', 'start_to_start', 'finish_to_finish', 'start_to_finish']
before_action :find_optional_project, except: [:reschedule_project, :project_issues]
before_action :find_opened_project, except: [:reschedule_project]
before_action :authorize, if: proc { @project.present? }
before_action :authorize_global, if: proc { @project.nil? }
before_action :check_rest_api_enabled, only: [:index]
before_action :find_relation, only: [:change_issue_relation_delay]
helper :queries
include QueriesHelper
helper :sort
include SortHelper
helper :custom_fields
helper :icons
def index
retrieve_query
end
# Data retrieve method
def issues
retrieve_query
load_projects
load_issues
load_versions
load_relations
build_dates @issues, :start_date, :due_date
end
# Data retrieve method
def projects
retrieve_query
load_projects
build_dates @projects, :gantt_start_date, :gantt_due_date
@projects_issues_counts = Issue.visible.gantt_opened.where(project_id: @projects).group(:project_id).count(:id)
end
def project_issues
# TODO: Global route to skip rights
@issues = Issue.visible.gantt_opened.where(project_id: params[:project_id]).order(:start_date)
@issue_ids = @issues.map(&:id)
load_relations
version_ids = @issues.map(&:fixed_version_id).uniq.compact
@versions = Version.open.where('id IN (?) OR project_id = ?', version_ids, params[:project_id]).sorted
end
def change_issue_relation_delay
if !User.current.allowed_to?(:manage_issue_relations, @project)
return render_403
end
@relation.update_column(:delay, params[:delay].to_i)
respond_to do |format|
format.api { render_api_ok }
end
end
# You cannot use issue.reschedule_on because it will
# also set start_date which is not desirable !!!
def reschedule_project
begin
# Do not used callback `find_project` because it will test access rights
# to project context. Method wont work if project does not have gantt enabled.
project = Project.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
return
end
project.gantt_reschedule(params[:days].to_i)
respond_to do |format|
format.api { render_api_ok }
end
end
def current_menu_item
@current_menu_item ||= if params[:gantt_type] == 'rm'
:resource
else
:easy_gantt
end
end
private
def check_rest_api_enabled
if Setting.rest_api_enabled != '1'
render_error message: l('easy_gantt.errors.no_rest_api')
return false
end
end
def find_relation
@relation = IssueRelation.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
def query_class
@project ? EasyGantt::EasyGanttIssueQuery : EasyGantt::EasyGanttProjectQuery
end
def retrieve_query
if params[:query_id].present?
cond = 'project_id IS NULL'
if @project
cond << " OR project_id = #{@project.id}"
end
@query = query_class.where(cond).find_by(id: params[:query_id])
raise ActiveRecord::RecordNotFound if @query.nil?
raise Unauthorized unless @query.visible?
@query.project = @project
sort_clear
else
@query = query_class.new(name: '_')
@query.project = @project
@query.from_params(params)
end
if @opened_project
@query.opened_project = @opened_project
end
end
# Load version from loaded task and from opened projects
# TO_CONSIDER: Send versions if there is no tasks?
def load_versions
version_ids = @issues.map(&:fixed_version_id).uniq.compact
@versions = Version.open.where("id IN (?) OR project_id = ?", version_ids, @opened_project.id).sorted
end
# Load subproject of opened project which contains filtered tasks
#
# Project 1
# |-- Project 1.1
# | `-- Project 1.1.1
# | |-- Task 1
# | `-- Task 2
# `-- Project 1.2
#
# If Project 1 is opened, Project 1.1 must be send even if there is no task
#
# TO_CONSIDER: Send full tree and load only opened_project's issues
#
def load_projects
p_table = Project.table_name
@projects = []
# Project gantt is opened, normally only subprojects will be sent
# but there is not any root project yet
if @project && @opened_project == @project
@projects << @project
end
projects = @query.without_opened_project { |q|
scope = q.create_entity_scope
# Not necessary, will take only subprojects
if @opened_project
scope = scope.where("#{p_table}.lft >= ? AND #{p_table}.rgt <= ?", @opened_project.lft, @opened_project.rgt)
end
scope.reorder(nil).distinct.pluck("#{p_table}.lft, #{p_table}.rgt, #{p_table}.parent_id")
}
if projects.blank?
return
end
# All ancestors conditions
tree_conditions = []
projects.each do |lft, rgt|
tree_conditions << "(lft <= #{lft} AND rgt >= #{rgt})"
end
tree_conditions = tree_conditions.join(' OR ')
@parent_ids = projects.map(&:last)
# From ancestors take only current opened level
@projects.concat Project.where(tree_conditions).where(parent_id: @opened_project.try(:id)).to_a
Project.load_gantt_dates(@projects)
if Setting.plugin_easy_gantt['show_project_progress'] == '1'
Project.load_gantt_completed_percent(@projects)
end
end
# Only between loaded tasks
def load_relations
if @issue_ids.empty?
@relations = []
else
@relations = IssueRelation.where('issue_from_id IN (?) OR issue_to_id IN (?)', @issue_ids, @issue_ids).
where(relation_type: RELATION_TYPES_TO_LOAD)
end
end
def load_issues
preloads = [:project, :author, :assigned_to, :relations_to]
if Setting.plugin_easy_gantt['show_task_soonest_start'] == '1'
preloads << :parent
preloads << { relations_to: :issue_from }
else
preloads << :relations_to
end
@issues = @query.entities(
includes: [:project, :status, :assigned_to, :fixed_version, :tracker, :priority, :custom_values],
preload: preloads,
order: "#{Issue.table_name}.start_date, #{Issue.table_name}.id"
)
@issue_ids = @issues.map(&:id)
end
def build_dates(data, starts, ends)
starts = data.map(&starts).compact
ends = data.map(&ends).compact
@start_date = (starts.min || ends.min || Date.today) - 1.day
@end_date = (ends.max || starts.max || Date.today) + 1.day
end
def find_optional_project
# Easy query workaround
if params[:set_filter] == '1' && params[:project_id].present? && params[:project_id].start_with?('=', '!*', '*')
return
end
super
end
def find_opened_project
if params[:opened_project_id].present?
@opened_project = Project.find(params[:opened_project_id])
else
@opened_project = @project
end
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@ -0,0 +1,219 @@
module EasyGanttHelper
def easy_gantt_include_js(*javascripts, from_plugin: 'easy_gantt')
plugin = from_plugin
result = ''
javascripts.flatten!
javascripts.compact!
javascripts.each do |javascript|
result << javascript_include_tag("#{from_plugin}/#{javascript}", plugin: plugin)
end
result.html_safe
end
def easy_gantt_include_css(*stylesheets, media: 'screen', from_plugin: 'easy_gantt')
plugin = from_plugin
result = ''
stylesheets.flatten!
stylesheets.compact!
stylesheets.each do |stylesheet|
result << stylesheet_link_tag("#{from_plugin}/#{stylesheet}", plugin: plugin, media: media)
end
result.html_safe
end
def easy_gantt_js_button(text, options={})
if text.is_a?(Symbol)
lang_key = text
text = l(lang_key, scope: [:easy_gantt, :button])
options[:title] ||= l(lang_key, scope: [:easy_gantt, :title], default: text)
end
options[:class] = "gantt-menu-button #{options[:class]}"
options[:class] << ' button' unless options.delete(:no_button)
if (icon = options.delete(:icon))
options[:class] << " icon #{icon}"
text = sprite_icon(icon.sub("icon-", ""), text)
end
link_to(text, options[:url] || 'javascript:void(0)', options)
end
def easy_gantt_help_button(*args)
options = args.extract_options!
feature = args.shift
text = args.shift
options[:class] = "gantt-menu-help-button #{options[:class]}"
options[:icon] ||= 'icon-help'
options[:id] = 'button_' + feature.to_s + '_help'
help_text = raw l(:text, scope: [:easy_gantt, :popup, feature])
easy_gantt_js_button(text || '&#8203;'.html_safe, options) + %Q(
<div id="#{feature}_help_modal" style="display:none">
<h3 class="title">#{raw l(:heading, scope: [:easy_gantt, :popup, feature]) }</h3>
<p>#{help_text}</p>
</div>
).html_safe
end
def api_render_versions(api, versions)
return if versions.blank?
api.array :versions do
versions.each do |version|
api.version do
api.id version.id
api.name version.name
api.start_date version.effective_date
api.project_id version.project_id
api.project_name version.project&.name
api.permissions do
api.editable version.gantt_editable?
end
end
end
end
end
def api_render_columns(api, query)
api.array :columns do
query.columns.each do |c|
api.column do
api.name c.name
api.title c.caption
end
end
end
end
def api_render_issues(api, issues, with_columns: false)
api.array :issues do
issues.each do |issue|
api.issue do
api.id issue.id
api.name issue.subject
api.start_date issue.start_date
api.due_date issue.due_date
api.estimated_hours issue.estimated_hours
api.done_ratio issue.done_ratio
api.closed issue.closed?
api.fixed_version_id issue.fixed_version_id
api.overdue issue.overdue?
api.parent_issue_id issue.parent_id
api.project_id issue.project_id
api.tracker_id issue.tracker_id
api.priority_id issue.priority_id
api.status_id issue.status_id
api.assigned_to_id issue.assigned_to_id
if Setting.plugin_easy_gantt['show_task_soonest_start'] == '1' && @project.nil?
api.soonest_start issue.soonest_start
end
if Setting.plugin_easy_gantt['show_task_latest_due'] == '1' && @project.nil?
api.latest_due issue.latest_due
end
api.is_planned !!issue.project.try(:is_planned)
api.permissions do
api.editable issue.gantt_editable?
end
if with_columns
api.array :columns do
@query.columns.each do |c|
api.column do
api.name c.name
api.value gantt_format_column(issue, c, c.value(issue))
end
end
end
end
end
end
end
end
def api_render_relations(api, relations)
api.array :relations do
relations.each do |rel|
api.relation do
api.id rel.id
api.source_id rel.issue_from_id
api.target_id rel.issue_to_id
api.type rel.relation_type
api.delay rel.delay.to_i
end
end
end
end
def api_render_projects(api, projects, with_columns: false)
api.array :projects do
projects.each do |project|
api.project do
api.id project.id
api.name project.name
api.start_date project.gantt_start_date || Date.today
api.due_date project.gantt_due_date || Date.today
api.parent_id project.parent_id
api.is_baseline project.try(:easy_baseline_for_id?)
# Schema
api.status_id project.status
api.priority_id project.try(:easy_priority_id)
api.permissions do
api.editable project.gantt_editable?
end
if Setting.plugin_easy_gantt['show_project_progress'] == '1'
api.done_ratio project.gantt_completed_percent
end
if @projects_issues_counts && @projects_issues_counts.has_key?(project.id)
api.issues_count @projects_issues_counts[project.id]
end
if @parent_ids && @parent_ids.include?(project.id)
api.has_subprojects true
end
if with_columns
api.array :columns do
@query.columns.each do |c|
api.column do
api.name c.name
api.value gantt_format_column(project, c, c.value(project))
end
end
end
end
end
end
end
end
# This method exist because
# 1. EntityAttributeHelper is for complex html formating
# 2. Redmine doest not have it
# Gantt should show light and non-html values
def gantt_format_column(entity, column, value)
if entity.is_a?(Project) && column.name == :status && respond_to?(:format_project_attribute)
format_project_attribute(Project, column, value)
elsif value.is_a?(Float)
locale = User.current.language.presence || ::I18n.locale
number_with_precision(value, locale: locale).to_s
elsif value.is_a?(Array)
value.join(', ')
else
value.to_s
end
end
end

View File

@ -0,0 +1,82 @@
module EasyGantt
class EasyGanttIssueQuery < IssueQuery
attr_accessor :entity_scope
attr_accessor :opened_project
def default_columns_names
[:subject, :priority, :assigned_to]
end
def entity
Issue
end
def from_params(params)
build_from_params(params)
end
def to_params
params = { set_filter: 1, type: self.class.name, f: [], op: {}, v: {} }
filters.each do |filter_name, opts|
params[:f] << filter_name
params[:op][filter_name] = opts[:operator]
params[:v][filter_name] = opts[:values]
end
params[:c] = column_names
params
end
def to_partial_path
'easy_gantt/easy_queries/show'
end
def initialize_available_filters
super
@available_filters.delete('subproject_id')
end
def entity_scope
@entity_scope ||= begin
scope = Issue.visible
if Project.column_names.include? 'easy_baseline_for_id'
scope = scope.where(Project.table_name => {easy_baseline_for_id: nil})
end
scope
end
end
def create_entity_scope(options={})
entity_scope.includes(options[:includes]).
references(options[:includes]).
preload(options[:preload]).
where(statement).
where(options[:conditions])
end
def entities(options={})
create_entity_scope(options).order(options[:order])
end
def project_statement
p_table = Project.table_name
conditions = "#{p_table}.status = #{Project::STATUS_ACTIVE}"
if opened_project
conditions = "#{conditions} AND #{Project.table_name}.id = #{opened_project.id}"
end
conditions
end
def without_opened_project
_opened_project = opened_project
self.opened_project = nil
yield self
ensure
self.opened_project = _opened_project
end
end
end

View File

@ -0,0 +1,92 @@
module EasyGantt
class EasyGanttProjectQuery < Query
attr_accessor :opened_project
self.queried_class = Project
self.available_columns = [
QueryColumn.new(:name, sortable: "#{Project.table_name}.name"),
QueryColumn.new(:created_on, sortable: "#{Project.table_name}.created_on"),
QueryColumn.new(:updated_on, sortable: "#{Project.table_name}.updated_on"),
]
def initialize(*args)
super
self.filters ||= {}
end
def default_columns_names
[:name]
end
def initialize_available_filters
add_available_filter 'name', type: :text
add_available_filter 'created_on', type: :date_past
add_available_filter 'updated_on', type: :date_past
end
def from_params(params)
build_from_params(params)
end
def to_params
params = { set_filter: 1, type: self.class.name, f: [], op: {}, v: {} }
filters.each do |filter_name, opts|
params[:f] << filter_name
params[:op][filter_name] = opts[:operator]
params[:v][filter_name] = opts[:values]
end
params[:c] = column_names
params
end
def to_partial_path
'easy_gantt/easy_queries/show'
end
def entities(options={})
scope = Project.active.visible
if Project.column_names.include?('easy_baseline_for_id')
scope = scope.where(Project.table_name => { easy_baseline_for_id: nil })
end
scope = scope.includes(options[:includes]).
references(options[:includes]).
preload(options[:preload]).
where(statement).
where(options[:conditions]).
order(options[:order])
if opened_project
scope = scope(projects: { id: opened_project.id })
end
scope.to_a
end
def entity_scope
Project.visible
end
def create_entity_scope(options={})
entity_scope.includes(options[:includes]).
references(options[:includes]).
preload(options[:preload]).
where(statement).
where(options[:conditions])
end
def without_opened_project
_opened_project = opened_project
self.opened_project = nil
yield self
ensure
self.opened_project = _opened_project
end
end
end

View File

@ -0,0 +1,3 @@
<p class="error">
<%= l(:error_epm_easy_gantt_already_active) %>
</p>

View File

@ -0,0 +1,49 @@
<%
heads_for_wiki_formatter
%>
<%= content_for :header_tags do %>
<%= easy_gantt_include_css('easy_gantt', media: 'all') %>
<%= easy_gantt_include_css('modal_editor') %>
<%= easy_gantt_include_js(
'utils',
'dhtmlxgantt',
'dhtmlxgantt_marker',
'main',
'data',
'loader',
'saver',
'logger',
'widget',
'panel_widget',
'gantt_widget',
'view',
'history',
'dhtml_modif',
'dhtml_addons',
'dhtml_rewrite',
('dhtml_relations' if Setting.parent_issue_dates === "derived"),
'background',
'pro_manager',
'storage',
'tooltip',
'toolpanel',
'print',
'left_grid',
'sumrow',
'bars',
'problem_finder',
'collapsor',
'flash_message',
'libs/mustache',
'libs/raf',
'libs/svg',
) %>
<%= easy_gantt_include_js(
('sample' unless EasyGantt.easy_gantt_pro?),
('libs/moment')
) %>
<script type="application/javascript">
$(ysy.initGantt);
</script>
<% end %>

View File

@ -0,0 +1,151 @@
<%= content_for :header_tags do %>
<script type="text/javascript">
window.ysy = window.ysy || {};
ysy.settings = ysy.settings || {};
$.extend(true, ysy.settings, <%= {
platform: 'redmine',
easyRedmine: false,
isGantt: (params[:controller] == 'easy_gantt'),
language: I18n.locale.to_s,
project: ({ id: @project.id, name: @project.name } if @project),
dateFormat: (Setting.date_format.presence || I18n.t('date.formats.default')),
nonWorkingWeekDays: EasyGantt.non_working_week_days,
milestonePush: false,
workDayDelays: Setting.plugin_easy_gantt['relation_delay_in_workdays'],
fixedRelations: false,
defaultZoom: Setting.plugin_easy_gantt['default_zoom'],
paths: {
rootPath: home_path
},
labels: {
buttons: {
button_delete: l(:button_delete),
button_submit: l(:button_submit),
button_yes: l(:general_text_Yes),
button_no: l(:general_text_No),
button_cancel: l(:button_cancel),
button_reload: l('easy_gantt.button.reload'),
button_save: l(:button_save)
},
sample_text: l('easy_gantt.sample.text').html_safe,
sample_global_free_text: l('easy_gantt.sample_global_free.text').html_safe,
date: {
month_full: Array(l('date.month_names')).compact,
month_short: Array(l('date.abbr_month_names')).compact,
day_full: Array(l('date.day_names')).compact,
day_short: Array(l('date.abbr_day_names')).compact
},
types: {
project: l(:field_project),
issue: l(:field_issue),
milestone: l(:field_version),
relation: l(:field_relation)
},
errors: Array(l('activerecord.errors.messages')).compact,
errors2: {
unsaved_parent: l('easy_gantt.errors.unsaved_parent')
},
problems: {
overMilestone: l('easy_gantt.errors.overmile'),
too_short: l('easy_gantt.errors.too_short'),
overdue: l('easy_gantt.errors.overdue'),
progressDateOverdue: l('easy_gantt.errors.progress_date_overdue'),
shortDelay: l('easy_gantt.errors.short_delay')
},
gateway: {
sendFailed: l('easy_gantt.gateway.send_failed'),
entitySaveFailed: l('easy_gantt.gateway.entity_save_failed'),
allSended: l(:notice_successful_update)
},
titles: {
easyGantt: l(:heading_easy_gantts_issues)
},
warnings: {
change_link_length: l("easy_gantt.errors.change_link_length"),
}
},
styles: {
backgrounds:{
selected: '#fff3a1',
line: 'rgba(200,200,200,0.5)',
line_month: '#aaaaff'
}
}
}.to_json.html_safe %>)
ysy.view = ysy.view || {};
ysy.view.templates = $.extend(ysy.view.templates, <%= {
TaskTooltip: %{
<h3 class="gantt-tooltip-header">{{name}}</h3>
{{#start_date}}
<div class="gantt-tooltip-start_date"><span class="gantt-tooltip-label">#{l(:field_start_date)}:</span> {{start_date}}</div>
{{/start_date}}
{{#end_date}}
<div class="gantt-tooltip-end_date"><span class="gantt-tooltip-label">#{l(:field_due_date)}:</span> {{end_date}}</div>
{{/end_date}}
{{#milestone}}
<div class="gantt-tooltip-milestone"><span class="gantt-tooltip-label">#{l(:field_version)}:</span> {{milestone.name}}</div>
{{/milestone}}
{{#columns}}
<div class="gantt-tooltip-column-{{name}}"><span class="gantt-tooltip-label">{{label}}:</span> {{value}}</div>
{{/columns}}
{{#problems}}
<div class="gantt-tooltip-problem">{{.}}</div>
{{/problems}}
},
Button: %{
<span class="button {{active}}" title="{{title}}">
<a id="{{elid}}_button_in" class="gantt_button{{icon}}" href="javascript:void(0)">{{name}}</a>
</span>
},
LinkButton: %{
<a class="{{css}}" title="{{title}}" href="javascript:void(0)">{{name}}</a>
},
SuperPanel: %{},
# reloadModal: %{
# <h3 class="title">#{l('easy_gantt.reload_modal.title')}</h3>
# <h4>#{l('easy_gantt.reload_modal.label_errors')}:</h4>
# <ul class="gantt-reload-modal-errors">
# {{#errors}}
# <li class="gantt-reload-model-error">{{.}}</li>
# {{/errors}}
# </ul>
# <p>#{l('easy_gantt.reload_modal.text_reload_appeal')}</p>
# },
preBlocker: %{
<div style="left:{{pos_x}}px" class="gantt_task_relation_stop gantt_task_relation_stop_left" title="#{l('easy_gantt.text_blocker_move_pre')}">
</div>
},
endBlocker: %{
<div style="left:{{pos_x}}px" class="gantt_task_relation_stop gantt_task_relation_stop_right" title="#{l('easy_gantt.text_blocker_move_end')}">
</div>
},
ProblemFinder: %{
#{l('easy_gantt.button.problem_finder')}:
<span class="gantt-menu-problems-count{{#count}} gantt-with-problems{{/count}}">{{count}}</span>
},
ProblemFinderList: %{
<ol>
{{#entities}}
<li>
<a href="javascript:ysy.pro.problemFinder.scrollToEntity('{{entityId}}')">
{{#isProject}}#{l(:field_project)}{{/isProject}}{{^isProject}}#{l(:field_issue)}{{/isProject}}: <strong>{{name}}</strong>
<br>
<span class="gantt-menu-problems-reason">{{text}}</span>
</a>
</li>
{{/entities}}
{{#relations}}
<li>
<a href="javascript:ysy.pro.problemFinder.scrollToEntity('{{entityId}}')">
#{l(:field_relation)}: <strong>{{sourceName}}</strong> - <strong>{{targetName}}</strong>
<br>
<span class="gantt-menu-problems-reason">{{text}}</span>
</a>
</li>
{{/relations}}
</ol>
}
}.to_json.html_safe %>)
</script>
<% end %>

View File

@ -0,0 +1,71 @@
<%
unless defined?(show_menu_items)
show_menu_items = true
end
zooms = ['day', 'week', 'month', 'quarter', 'year']
%>
<span id="close_all_something">
<a id="button_close_all_projects" title="<%= l(:close_all, scope: [:easy_gantt, :button])+' '+l(:label_project_plural) %>" class="gantt-button-symbol icon-folder" href="javascript:void(0)"><%= sprite_icon('folder', '') %></a>
<a id="button_close_all_milestones" title="<%= l(:close_all, scope: [:easy_gantt, :button])+' '+l(:label_version_plural) %>" class="gantt-button-symbol gantt-icon-milestone" href="javascript:void(0)"><%= sprite_icon('milestone', '') %></a>
<a id="button_close_all_parent_issues" title="<%= l(:close_all, scope: [:easy_gantt, :button])+' '+l(:label_parent_issue_plural) %>" class="gantt-button-symbol gantt-icon-parent-issue" href="javascript:void(0)"><%= sprite_icon('parent', '') %></a>
</span>
<div id="supertop_panel" class="gantt-supertop-panel easy-gantt__supertop-panel clear"></div>
<div id="easy_gantt_menu" class="easy-gantt__menu clear">
<div class="push-left">
<% if Rails.env.development? %>
<%= easy_gantt_js_button l(:button_test), id: 'button_test' %>
<% end %>
<%= easy_gantt_js_button("", id: 'button_jump_today', title: l(:jump_today, scope: [:easy_gantt, :title]), icon: 'icon-list') %>
<% zooms.each do |name| %>
<%= easy_gantt_js_button(:"#{name}_zoom", id: "button_#{name}_zoom", icon: "icon-zoom-in") %>
<% end %>
</div>
<div class="push-right">
<% if show_menu_items %>
<%= easy_gantt_js_button(:problem_finder, {
url: 'javascript:void(0)',
id: 'button_problem_finder',
class: 'problem-finder',
no_button: true
}) %>
<div class="easy-gantt__menu-group easy-gantt__menu-group--tooltiped easy-gantt__menu-tools">
<a href="javascript:void(0)" class="button gantt-menu-button icon icon-settings easy-gantt__menu-tools-button"><%= sprite_icon('settings', l(:tool_panel, :scope => [:easy_gantt, :button])) %></a>
<ul id="easy_gantt_tool_panel" class="easy-gantt__menu-item">
<% menu_items_for(:easy_gantt_tools, @project) do |node| %>
<li>
<%
opts = node.html_options.dup
opts[:url] = (node.url.is_a?(Proc) ? node.url.call(@project) : node.url)
opts[:id] = "button_#{node.name}"
opts[:no_button] = 'true'
caption = opts[:caption].is_a?(Proc) ? opts[:caption].call(params[:gantt_type]) : node.caption
%>
<% if opts.delete(:trial) %>
<%= easy_gantt_help_button(node.name, caption, opts) %>
<% else %>
<%= easy_gantt_js_button(caption, opts) %>
<% end %>
</li>
<% end %>
</ul>
</div>
<%= easy_gantt_js_button(l(:button_save), {
url: 'javascript:void(0)',
id: 'button_save',
icon: 'icon-save',
no_button: true,
class: 'button-positive button-1'
}) %>
<% end %>
</div>
<%= call_hook(:view_easy_gantts_issues_toolbars, project: @project) %>
</div>
<!-- This is container for gantt -->
<div id="gantt_cont" style="width: 100%;" class="clear"></div>
<!-- End container for gantt -->

View File

@ -0,0 +1,72 @@
<%
unless defined?(form_options)
form_options = {}
end
query ||= @query
form_path ||= easy_gantt_path(@project)
form_options[:additional_elements_to_serialize] ||= 'null'
%>
<div class="content-title"><%= title(easy_query_name) %></div>
<%= form_tag(form_path, method: :get, id: 'query_form') do %>
<div id="query_form_with_buttons" class="hide-when-print">
<%= hidden_field_tag 'set_filter', '1' %>
<div id="query_form_content">
<fieldset id="filters" class="collapsible <%= @query.new_record? ? "" : "collapsed" %>">
<legend onclick="toggleFieldset(this);" class="icon icon-<%= @query.new_record? ? "expanded" : "collapsed" %>">
<%= sprite_icon(@query.new_record? ? "angle-down" : "angle-right") %>
<%= l(:label_filter_plural) %>
</legend>
<div style="<%= @query.new_record? ? "" : "display: none;" %>">
<%= render 'queries/filters', query: query %>
</div>
</fieldset>
<fieldset class="collapsible collapsed">
<legend onclick="toggleFieldset(this);" class="icon icon-collapsed">
<%= sprite_icon("angle-right") %>
<%= l(:label_options) %>
</legend>
<div style="display: none;">
<table>
<tr>
<td><%= l(:field_column_names) %></td>
<td><%= render_query_columns_selection(query) %></td>
</tr>
</table>
</div>
</fieldset>
</div>
<p class="buttons">
<%= link_to_function sprite_icon('checked', l(:button_apply)), 'applyEasyGanttQuery()', class: 'icon icon-checked' %>
<%= link_to sprite_icon('reload', l(:button_clear)), { set_filter: 1, project_id: @project }, class: 'icon icon-reload' %>
</p>
</div>
<% end %>
<script>
var additionalElementsToSerialize;
$(document).ready(function(){
additionalElementsToSerialize = <%=raw form_options[:additional_elements_to_serialize] %>;
});
function applyEasyGanttQuery(){
if (additionalElementsToSerialize) {
var data = additionalElementsToSerialize.serializeArray()[0];
if (data) {
var newInput = $("<input />").attr("type", "hidden")
.attr("name", data.name)
.attr("value", data.value);
newInput.appendTo("#query_form");
}
}
$("#query_form").submit();
}
</script>

View File

@ -0,0 +1,176 @@
<%
plugin = Redmine::Plugin.find('easy_gantt')
query ||= @query
main_gantt_params = query.to_params.merge(key: User.current.api_key, format: 'json')
main_gantt_path = if @project
issues_easy_gantt_path(@project, main_gantt_params)
else
projects_easy_gantt_path(main_gantt_params)
end
unless defined?(show_query)
show_query = true
end
if EasyGantt.easy_gantt_pro?
sample_path = ''
else
sample_path = "#{home_path}plugin_assets/easy_gantt/data/sample_{{version}}.json"
end
%>
<div id="easy_gantt" class="redmine gantt clear">
<% if show_query %>
<% if User.current.admin? && @project.nil? %>
<div class="contextual settings">
<%= link_to sprite_icon('settings', ''), plugin_settings_path(plugin, back_url: request.fullpath), class: 'icon icon-settings', title: l(:label_easy_gantt_settings)%>
</div>
<% end %>
<%= render query, easy_query_name: l(:heading_easy_gantts_issues),
wrapper_class: '',
form_options: { additional_elements_to_serialize: '$("input#easy_gantt_type")' },
options: { show_free_search: false,
show_custom_formatting: false,
additional_tagged_url_options: { gantt_type: params[:gantt_type] } } %>
<% end %>
<%= hidden_field_tag 'gantt_type', '', id: 'easy_gantt_type' %>
<%= render 'easy_gantt/menu_graph' %>
<div id="easy_gantt_footer" class="gantt-footer">
<div id="easy_gantt_footer_legend" class="gantt-footer-legend"></div>
<div id="gantt_footer_buttons" class="gantt-footer-menu">
<%= easy_gantt_js_button(l(:button_print), icon: 'icon-document', id: 'button_print') %>
<% unless EasyGantt.easy_gantt_pro? %>
<%= easy_gantt_js_button(:load_sample_data, id: 'button_sample') %>
<% end %>
</div>
<p><%= link_to l(:text_easy_gantt_footer), l(:link_easy_gantt_plugin), target: '_blank' %></p>
</div>
</div>
<%= render 'easy_gantt/includes' %>
<%= render 'easy_gantt/js_prepare' %>
<%= content_for :header_tags do %>
<script type="text/javascript">
window.ysy = window.ysy || {};
ysy.settings = ysy.settings || {};
ysy.view = ysy.view || {};
$.extend(true, ysy.settings, <%= {
hoursPerDay: 8,
parentIssueDates: (Setting.parent_issue_dates == 'derived'),
paths: {
mainGantt: main_gantt_path.html_safe,
issuePOST: issues_path(format: 'json', key: User.current.api_key),
issuePUT: issue_path(':issueID', format: 'json', key: User.current.api_key),
issueDELETE: issue_path(':issueID', format: 'json', key: User.current.api_key),
relationPOST: issue_relations_path(':issueID', format: 'json', key: User.current.api_key),
relationPUT: relation_easy_gantt_path(':projectID', ':relaID', format: 'json', key: User.current.api_key),
relationDELETE: relation_path(':relaID', format: 'json', key: User.current.api_key),
versionPOST: project_versions_path(':projectID', format: 'json', key: User.current.api_key),
versionPUT: version_path(':versionID', format: 'json', key: User.current.api_key),
sample_data: sample_path
},
labels: {
links: {
start_to_start: l(:label_start_to_start),
start_to_finish: l(:label_start_to_finish),
finish_to_finish: l(:label_finish_to_finish),
precedes: l(:label_precedes),
relates: l(:label_relates_to),
copied_to: l(:label_copied_to),
blocks: l(:label_blocks),
duplicates: l(:label_duplicates)
},
errors2:{
loop_link: l('easy_gantt.errors.loop_link'),
link_target_new: l('easy_gantt.errors.link_target_new'),
link_target_readonly: l('easy_gantt.errors.link_target_readonly'),
unsupported_link_type: l('easy_gantt.errors.unsupported_link_type'),
duplicate_link: l('easy_gantt.errors.duplicate_link')
}
}
}.to_json.html_safe %>);
ysy.view.templates = $.extend(ysy.view.templates, <%= {
LinkConfigPopup: %{
<h3 class='title'>#{l(:heading_delay_popup)}</h3>
<label for='link_delay_input'>#{l(:field_delay)}:</label>
<span style="width:100px;display:inline-block;"></span>
<input id='link_delay_input' type='number' min='{{minimal}}' value='{{delay}}' size='3'>
<!--<a id='link_fix_actual' class='button icon icon-link' href='javascript:void(0)'>#{sprite_icon('link', l(:button_use_actual_delay))}</a>-->
<!--<a id='link_remove_delay' class='button icon icon-link' href='javascript:void(0)' >#{sprite_icon('link', l('easy_gantt.button.remove_delay'))}</a>-->
<div id='link_popup_button_cont' >
<hr>
<a id='link_delete' class='icon icon-unlink button' href='javascript:void(0)'>#{sprite_icon('unlink', l(:button_delete))}</a>
<a id='link_close' class='icon icon-save button-positive' href='javascript:void(0)' style='float:right'>#{sprite_icon('save', l(:button_submit))}</a>
</div>
},
SuperPanel: %{
{{#sample}}
<div id="sample_cont" class="flash notice gantt-sample-flash">
<h2 id="sample_label">#{l('easy_gantt.sample.header')}</h2>
<p>{{{text}}}</p>
<p class="" style="text-align:center">
<a id="sample_video_button" class="icon icon-youtube" href="javascript:void(0)">#{sprite_icon('youtube', l('easy_gantt.sample.video_label'))}</a>
{{^global_free}}
<a id="sample_close_button" class="gantt-sample-close-button button button-important" href="javascript:void(0)" title="#{l('easy_gantt.sample.close_label')}">#{l('easy_gantt.sample.close_label')}</a>
{{/global_free}}
{{#global_free}}
<a id="sample_upgrade_button" class="button button-positive" href="#{l(:link_easy_gantt_plugin)}" target="_blank" title="#{l('easy_gantt.label_pro_upgrade')}">#{l('easy_gantt.label_pro_upgrade')}</a>
{{/global_free}}
</p>
<div class="clear"></div>
</div>
{{/sample}}
},
easy_unimplemented: %{
<h3 class="title">{{modal.title}}</h3><span>{{{modal.text}}}</span>
},
video_modal: %{
<h3 class="title">#{l('easy_gantt.sample.video.title')}</h3>
<iframe class="gantt-modal-video" width="800" height="450" src="//www.youtube.com/embed/#{l('easy_gantt.sample.video.video_id')}?autoplay=1">
</iframe>
<p>#{l('easy_gantt.sample.video.text')}</p>
},
video_modal_global: %{
<h3 class="title">#{l('easy_gantt.sample_global_free.video.title')}</h3>
<iframe class="gantt-modal-video" width="800" height="450" src="//www.youtube.com/embed/#{l('easy_gantt.sample_global_free.video.video_id')}?autoplay=1">
</iframe>
<p>#{l('easy_gantt.sample_global_free.video.text')}</p>
},
legend: %{
{{text}}
},
linkDragModal: %{
{{#errorReason}}
<b>{{errorReason}}</b>
{{/errorReason}}
{{^errorReason}}
#{l(:label_relation_new)}{{#type}} <b>{{type}}</b>{{/type}}<br>
<b>{{from}}</b> #{l('easy_gantt.link_dir.link_end')}<br>
{{#to}}<b>{{to}}</b> #{l('easy_gantt.link_dir.link_start')}{{/to}}
{{/errorReason}}
},
printIncludes: %{
#{easy_gantt_include_css('easy_gantt', media: 'all')}
}
}.to_json.html_safe %>);
</script>
<% end %>
<%= call_hook(:view_easy_gantt_index_bottom, project: @project, query: query) %>
<% content_for :sidebar do %>
<%= call_hook(:view_easy_gantt_index_sidebar, project: @project, query: query, gantt_type: params[:gantt_type]) %>
<% # DEPRECATED %>
<%= call_hook(:view_easy_gantts_issues_sidebar, project: @project, query: query) %>
<% end %>

View File

@ -0,0 +1,12 @@
api.easy_gantt_data do
api.start_date @start_date
api.end_date @end_date
api_render_columns(api, @query)
api_render_projects(api, @projects)
api_render_issues(api, @issues, with_columns: true)
api_render_relations(api, @relations)
api_render_versions(api, @versions)
end

View File

@ -0,0 +1,5 @@
api.easy_gantt_data do
api_render_issues(api, @issues)
api_render_relations(api, @relations)
api_render_versions(api, @versions)
end

View File

@ -0,0 +1,7 @@
api.easy_gantt_data do
api.start_date @start_date
api.end_date @end_date
api_render_columns(api, @query)
api_render_projects(api, @projects, with_columns: true)
end

View File

@ -0,0 +1,5 @@
<% # Just for hiding %>
<script>
$("#custom_formatting").remove();
</script>

View File

@ -0,0 +1,44 @@
<%
default_zoom_options = [
[l('easy_gantt.button.day_zoom'), 'day'],
[l('easy_gantt.button.week_zoom'), 'week'],
[l('easy_gantt.button.month_zoom'), 'month'],
[l('easy_gantt.button.quarter_zoom'), 'quarter'],
[l('easy_gantt.button.year_zoom'), 'year']
]
%>
<%= title l(:title_easy_gantt_settings) %>
<div class="box tabular">
<p>
<%= label_tag 'settings_relation_delay_in_workdays', l(:field_easy_gantt_relation_delay_in_workdays) %>
<%= check_box_tag 'settings[relation_delay_in_workdays]', '1', @settings['relation_delay_in_workdays'] == '1' %>
<em class="info small">
<%= l(:text_easy_gantt_relation_delay_in_workdays) %>
</em>
</p>
<p>
<%= label_tag 'settings_show_project_progress', l(:field_easy_gantt_show_project_progress) %>
<%= check_box_tag 'settings[show_project_progress]', '1', @settings['show_project_progress'] == '1' %>
<em class="info small">
<%= l(:text_easy_gantt_show_project_progress) %>
</em>
</p>
<p>
<%= label_tag 'settings_show_task_soonest_start', l(:field_easy_gantt_show_task_soonest_start) %>
<%= check_box_tag 'settings[show_task_soonest_start]', '1', @settings['show_task_soonest_start'] == '1' %>
<em class="info small">
<%= l(:text_easy_gantt_show_task_soonest_start) %>
</em>
</p>
<p>
<%= label_tag 'settings_default_zoom', l(:field_easy_gantt_default_zoom) %>
<%= select_tag 'settings[default_zoom]', options_for_select(default_zoom_options, @settings['default_zoom']) %>
</p>
<%= call_hook :view_easy_gantt_settings %>
</div>

View File

@ -0,0 +1,84 @@
{
"start_date": "yyyy-mm-dd",
"due_date":"yyyy-mm-dd",
"columns": [
{
"name": "name",
"title": "Jméno",
"mapped":true,
"type":"text"
},
{
"name":"start_date",
"title":"Počátek",
"mapped":true
},
{
"name":"end_date",
"title":"Konec",
"mapped":true
},
{
"name": "assignee",
"title": "Přirazeno",
"mapped":true,
"type":"select",
"completes":"/easy_auto_completer/assignable_users"
},
{
"name": "address",
"title": "Adresa",
"type":"text"
},
{
"name": "priority",
"title": "Priorita",
"type":"select",
"completes":"/easy_auto_completer/issue_priorities"
},
{
"name":"estimated",
"title":"Odhad",
"type":"text"
}
],
"issues": [
{
"id": 0,
"name": "název úkolu",
"start_date": "yyyy-mm-dd",
"end_date": "yyyy-mm-dd",
"estimated": 25,
"progress": 0.10,
"css": "issue-open project-35 tracker-5 status-1",
"assignee": {"id": 65, "name": "lukas"},
"version":65,
"columns": {
"address":"Levá 5, Horní Dolní",
"priority":"Vysoká",
"estimated":256
}
}
],
"projects":[],
"versions":[
{
"id": 65,
"name": "název milníku",
"start_date": "yyyy-mm-dd",
"css": "issue-open project-35 tracker-5 status-1",
"milestone":true
}
],
"relations": [
{
"id": 5,
"source": 6,
"target": 7,
"type": "precedes",
"delay": 0
}
]
}

View File

@ -0,0 +1,565 @@
{
"easy_gantt_data": {
"start_date": "2016-03-28",
"end_date": "2016-06-08",
"columns": [
{
"name": "subject",
"title": "Subject"
},
{
"name": "assigned_to",
"title": "Assignee"
}
],
"projects": [],
"issues": [
{
"id": 371,
"name": "Features Specification",
"start_date": "2016-03-29",
"due_date": "2016-03-29",
"estimated_hours": 1.0,
"done_ratio": 0,
"fixed_version_id": 58,
"overdue": true,
"project_id": 41,
"tracker_id": 5,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Features Specification"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 372,
"name": "Creative brief",
"start_date": "2016-04-04",
"due_date": "2016-04-08",
"estimated_hours": 1.0,
"done_ratio": 0,
"fixed_version_id": 58,
"overdue": true,
"project_id": 41,
"tracker_id": 5,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Creative brief"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 373,
"name": "Marketing brief",
"start_date": "2016-04-04",
"due_date": "2016-04-04",
"estimated_hours": 1.0,
"done_ratio": 0,
"fixed_version_id": 58,
"overdue": true,
"project_id": 41,
"tracker_id": 5,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Marketing brief"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 374,
"name": "Wireframes",
"start_date": "2016-04-11",
"due_date": "2016-04-11",
"estimated_hours": 8.0,
"done_ratio": 0,
"fixed_version_id": 57,
"overdue": true,
"project_id": 41,
"tracker_id": 3,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Wireframes"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 375,
"name": "Graphics",
"start_date": "2016-04-15",
"due_date": "2016-04-18",
"estimated_hours": 16.0,
"done_ratio": 0,
"fixed_version_id": 57,
"overdue": true,
"project_id": 41,
"tracker_id": 3,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Graphics"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 376,
"name": "XHTML + CSS coding",
"start_date": "2016-04-25",
"due_date": "2016-05-02",
"estimated_hours": 15.0,
"done_ratio": 0,
"fixed_version_id": 57,
"overdue": true,
"project_id": 41,
"tracker_id": 3,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "XHTML + CSS coding"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 378,
"name": "VirtueMart implementation",
"start_date": "2016-05-03",
"due_date": "2016-05-03",
"estimated_hours": 5.0,
"done_ratio": 0,
"fixed_version_id": 56,
"overdue": true,
"project_id": 41,
"tracker_id": 4,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "VirtueMart implementation"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 383,
"name": "On-line payments",
"start_date": "2016-05-09",
"due_date": "2016-05-10",
"estimated_hours": 10.0,
"done_ratio": 0,
"fixed_version_id": 56,
"overdue": true,
"project_id": 41,
"tracker_id": 13,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "On-line payments"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 379,
"name": "Web structure",
"start_date": "2016-05-11",
"due_date": "2016-05-11",
"estimated_hours": 5.0,
"done_ratio": 0,
"fixed_version_id": 55,
"overdue": true,
"project_id": 41,
"tracker_id": 4,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Web structure"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 377,
"name": "CMS - implementation + setting",
"start_date": "2016-05-12",
"due_date": "2016-05-12",
"estimated_hours": 5.0,
"done_ratio": 0,
"fixed_version_id": 56,
"overdue": true,
"project_id": 41,
"tracker_id": 4,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "CMS - implementation + setting"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 380,
"name": "Products",
"start_date": "2016-05-16",
"due_date": "2016-05-17",
"estimated_hours": 10.0,
"done_ratio": 0,
"fixed_version_id": 55,
"overdue": true,
"project_id": 41,
"tracker_id": 4,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Products"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 381,
"name": "Specific features",
"start_date": "2016-05-18",
"due_date": "2016-05-18",
"estimated_hours": 10.0,
"done_ratio": 0,
"fixed_version_id": 54,
"overdue": true,
"project_id": 41,
"tracker_id": 13,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Specific features"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 382,
"name": "Easy Redmine Integration",
"start_date": "2016-05-23",
"due_date": "2016-05-23",
"estimated_hours": 5.0,
"done_ratio": 0,
"fixed_version_id": 54,
"overdue": true,
"project_id": 41,
"tracker_id": 13,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Easy Redmine Integration"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 384,
"name": "Google Analytics",
"start_date": "2016-05-25",
"due_date": "2016-05-30",
"estimated_hours": 3.0,
"done_ratio": 0,
"fixed_version_id": 53,
"overdue": true,
"project_id": 41,
"tracker_id": 4,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Google Analytics"
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 385,
"name": "Testing ",
"start_date": "2016-05-30",
"due_date": "2016-05-31",
"estimated_hours": 10.0,
"done_ratio": 0,
"fixed_version_id": 53,
"overdue": true,
"project_id": 41,
"tracker_id": 4,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Testing "
},
{
"name": "assigned_to",
"value": ""
}
]
},
{
"id": 386,
"name": "Debug",
"start_date": "2016-06-02",
"due_date": "2016-06-07",
"estimated_hours": 10.0,
"done_ratio": 0,
"fixed_version_id": 53,
"overdue": true,
"project_id": 41,
"tracker_id": 13,
"priority_id": 9,
"status_id": 1,
"assigned_to_id": 21,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Debug"
},
{
"name": "assigned_to",
"value": "Ondrej Ezr"
}
]
},
{
"id": 387,
"name": "Training",
"start_date": "2016-06-06",
"due_date": "2016-06-07",
"estimated_hours": 4.0,
"done_ratio": 0,
"fixed_version_id": 53,
"overdue": true,
"project_id": 41,
"tracker_id": 4,
"priority_id": 9,
"status_id": 1,
"permissions": {
"editable": true
},
"columns": [
{
"name": "subject",
"value": "Training"
},
{
"name": "assigned_to",
"value": ""
}
]
}
],
"relations": [
{
"id": 27,
"source_id": 374,
"target_id": 375,
"type": "precedes",
"delay": 3
},
{
"id": 28,
"source_id": 375,
"target_id": 376,
"type": "precedes",
"delay": 4
},
{
"id": 29,
"source_id": 376,
"target_id": 377,
"type": "precedes",
"delay": 7
},
{
"id": 30,
"source_id": 385,
"target_id": 386,
"type": "precedes",
"delay": 1
}
],
"versions": [
{
"id": 58,
"name": "Analysis",
"start_date": "2016-04-04",
"project_id": 41,
"permissions": {
"editable": true
}
},
{
"id": 57,
"name": "Design",
"start_date": "2016-05-02",
"project_id": 41,
"permissions": {
"editable": true
}
},
{
"id": 56,
"name": "CMS + E-commerce platform",
"start_date": "2016-05-13",
"project_id": 41,
"permissions": {
"editable": true
}
},
{
"id": 55,
"name": "Content + Products",
"start_date": "2016-05-17",
"project_id": 41,
"permissions": {
"editable": true
}
},
{
"id": 54,
"name": "Easy Redmine integration",
"start_date": "2016-05-23",
"project_id": 41,
"permissions": {
"editable": true
}
},
{
"id": 53,
"name": "Public Launch",
"start_date": "2016-06-10",
"project_id": 41,
"permissions": {
"editable": true
}
}
]
}
}

File diff suppressed because it is too large Load Diff

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 763 B

View File

@ -0,0 +1,304 @@
/* background.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.view = ysy.view || {};
ysy.view.getGanttBackground = function () {
var colors = ysy.settings.styles.backgrounds;
function getBackgroundColor() {
var defaultColor = "rgba(200, 200, 200, 0.25)";
if (!window.getComputedStyle) return defaultColor;
var styles = window.getComputedStyle(document.getElementsByTagName('body')[0]);
var colorString = styles.getPropertyValue('background-color') || "";
if (!colorString.match(/rgba?\([0-9, ]+\)/)) return defaultColor;
var colorSplit = colorString.replace(/^rgba?\(|\s+|\)$/g,'').split(',');
var colorArray = [parseInt(colorSplit[0]), parseInt(colorSplit[1]), parseInt(colorSplit[2])];
var strongColorArray = [];
var stronger = 3;
for (var i = 0; i < 3; i++) {
var component = colorArray[i];
if (component > 255 * (stronger - 1) / stronger) {
strongColorArray.push(255 - (255 - component) * stronger);
} else {
strongColorArray.push(Math.floor(component / stronger));
}
}
return "rgba(" + strongColorArray.join(", ") + ", 0.15)";
}
var backgroundColor = getBackgroundColor();
return {
fullCanvasRender: false,
container: gantt.$task_bg,
renderer: true,
filter: gantt._create_filter(['_filter_task', '_is_chart_visible', '_is_std_background']),
lastItems: null,
lastPos: null,
svg: null,
lastElements: {},
_render_bg_canvas: function (svg, items, limits) {
var rowHeight = gantt.config.row_height;
var cfg = gantt._tasks;
var widths = cfg.width;
var fullHeight = rowHeight * (limits.toY - limits.fromY);
var fullWidth = 0;
var width;
var partWidth;
for (var i = limits.fromX; i < limits.toX; i++) {
fullWidth += widths[i];
}
svg.size(fullWidth, fullHeight);
svg.node.style.left = cfg.left[limits.fromX] + "px";
svg.node.style.top = rowHeight * limits.fromY + "px";
// -- CLEARING --
svg.clear();
// -- SELECTED --
for (i = limits.fromY; i < limits.toY; i++) {
if (gantt.getState().selected_task == items[i].id) {
svg.rect(fullWidth, rowHeight).x(0).y((i - limits.fromY) * rowHeight).attr('fill', colors.selected);
break;
}
}
// -- HORIZONTAL LINES --
var commands = [];
var lineCmd = "l " + fullWidth + " 0";
for (i = 1; i <= limits.toY - limits.fromY; i++) {
commands.push("M 0 " + (i * rowHeight - 0.5));
commands.push(lineCmd);
}
// -- VERTICAL LINES --
partWidth = -0.5;
lineCmd = "l 0 " + fullHeight;
for (i = limits.fromX; i < limits.toX; i++) {
width = widths[i];
if (width <= 0) continue; //do not render skipped columns
partWidth += width;
commands.push("M " + partWidth + " 0");
commands.push(lineCmd);
}
svg.path(commands.join("")).attr("stroke", colors.line);
if (gantt.config.scale_unit === "day") {
var weekendGroup = svg.group().attr('fill', backgroundColor);
if (ysy.settings.resource.open) {
// -- USER WEEKENDS BACKGROUND --
partWidth = 0;
for (i = limits.fromX; i < limits.toX; i++) {
width = widths[i];
var top = 0;
var mDate = moment(cfg.trace_x[i]);
var iDate = mDate.format("YYYY-MM-DD");
var lastWeekend = false;
var firstEntity = items[limits.fromY];
if (firstEntity.type !== "assignee") {
var assignee = ysy.data.assignees.getByID(firstEntity.widget.model.assigned_to_id || "unassigned");
if (assignee) {
lastWeekend = assignee.getMaxHours(iDate, mDate) === 0;
}
}
for (var j = limits.fromY; j < limits.toY; j++) {
if (items[j].type !== "assignee") continue;
var hours = items[j].widget.model.getMaxHours(iDate, mDate);
if ((hours === 0) === lastWeekend) continue;
if (lastWeekend) {
weekendGroup.rect(width, (j - limits.fromY) * rowHeight - top).x(partWidth).y(top);
} else {
top = (j - limits.fromY) * rowHeight;
}
lastWeekend = !lastWeekend;
}
if (lastWeekend) {
weekendGroup.rect(width, (limits.toY + 1) * rowHeight).x(partWidth).y(top);
}
partWidth += width;
}
} else {
// -- WEEKENDS BACKGROUND --
if (!cfg.weekends) {
cfg.weekends = [];
for (var d = 0; d < cfg.trace_x.length; d++) {
cfg.weekends.push(!gantt._working_time_helper.is_working_day(cfg.trace_x[d]));
}
}
partWidth = 0;
for (i = limits.fromX; i < limits.toX; i++) {
width = widths[i];
if (cfg.weekends[i]) {
weekendGroup.rect(width, fullHeight).x(partWidth);
}
partWidth += width;
}
}
}
if (ysy.settings.resource.open) {
// -- ASSIGNEE BACKGROUND --
var assigneeGroup = svg.group().attr('fill', backgroundColor);
for (i = limits.fromY; i < limits.toY; i++) {
if (items[i].type === "assignee") {
assigneeGroup.rect(fullWidth, rowHeight).y((i - limits.fromY) * rowHeight);
}
}
// -- DARK LIMITS --
var darkLimitGroup = svg.group().attr('fill', backgroundColor.replace("0.2)", "0.3)"));
var ganttLimits = ysy.data.limits;
if (ganttLimits.start_date) {
var left = gantt.posFromDate(ganttLimits.start_date) - gantt.posFromDate(cfg.trace_x[limits.fromX]);
if (left > 0) {
darkLimitGroup.rect(left, fullHeight);
}
}
if (ganttLimits.end_date) {
var right = gantt.posFromDate(ganttLimits.end_date) - gantt.posFromDate(cfg.trace_x[limits.fromX]);
if (right > 0 && right < fullWidth) {
darkLimitGroup.rect(fullWidth - right, fullHeight).x(right);
}
}
}
// -- BLUE LINE --
if (gantt.config.scale_unit === "day") {
partWidth = -0.5;
commands = [];
lineCmd = "l 0 " + fullHeight;
for (i = limits.fromX; i < limits.toX; i++) {
width = cfg.width[i];
var first = moment(cfg.trace_x[i]).date() === 1;
if (first) {
commands.push("M " + partWidth + " 0");
commands.push(lineCmd);
}
partWidth += width;
}
svg.path(commands.join("")).attr("stroke", colors.line_month);
}
},
render_bg_line: function (canvas, index, item) {
},
render_item: function (item, container) {
ysy.log.debug("render_item BG", "canvas_bg");
},
render_items: function (items, container) {
ysy.log.debug("render_items FULL BG", "canvas_bg");
container = container || this.node;
if (items) {
this.lastItems = items;
} else {
items = this.lastItems;
if (!items) return;
}
if (this.fullCanvasRender) {
this.render_full_svg(items, container);
} else {
this.render_shrunken_svg(items, container);
}
var fullHeight = gantt.config.row_height * items.length;
container.style.height = fullHeight + "px";
var lastEvent;
$(container)
.off("mousedown.bg")
.on("mousedown.bg", function (e) {
lastEvent = e;
})
.off("click.bg")
.on("click.bg", function (e) {
if (!lastEvent) return;
if (Math.abs(lastEvent.pageX - e.pageX) > 2 || Math.abs(lastEvent.pageY - e.pageY) > 2) return;
var order = gantt._order;
var offsetTop = $(container).offset().top;
var index = Math.floor((e.pageY - offsetTop) / gantt.config.row_height);
if (index < 0 || index >= order.length) return;
var taskId = order[index];
if (!gantt.isTaskExists(taskId)) return;
if (gantt._selected_task == taskId) {
gantt.unselectTask();
} else {
gantt.selectTask(taskId);
}
})
},
render_shrunken_svg: function (items, container) {
var cfg = gantt._tasks;
var scrollPos = gantt.getCachedScroll();
// var nodeWidth = this.node.innerWidth;
// if(scrollPos.x > Math.max(nodeWidth - window.innerWidth, 0)){
// scrollPos.x = gantt.$task.scrollLeft;
// }
this.lastPos = scrollPos;
//ysy.log.debug("render_one_canvas ["+scrollPos.x+","+scrollPos.y+"]","canvas_bg");
var rowHeight = gantt.config.row_height;
var colWidth = cfg.col_width;
var countX = cfg.count;
var countY = items.length;
var limits = this.getCanvasLimits();
var partCountX = Math.ceil(limits.x / colWidth),
partCountY = Math.ceil(limits.y / rowHeight);
var startX = Math.max(scrollPos.x - (limits.x - window.innerWidth) / 2, 0);
var startY = Math.max(scrollPos.y - (limits.y - window.innerHeight) / 2, 0);
var startCountX = Math.floor(startX / colWidth);
var startCountY = Math.floor(startY / rowHeight);
if (startCountX + partCountX > countX) {
startCountX = countX - partCountX;
}
if (startCountY + partCountY > countY) {
startCountY = countY - partCountY;
}
var svg = this.svg;
if (!svg) {
svg = this._createSvg(container);
}
this._render_bg_canvas(svg, items, {
fromX: Math.max(startCountX, 0),
toX: startCountX + partCountX,
fromY: Math.max(startCountY, 0),
toY: startCountY + partCountY
});
},
render_full_svg: function (items, container) {
ysy.log.debug("render_items FULL BG", "canvas_bg");
var cfg = gantt._tasks;
var countX = cfg.count;
var countY = items.length;
var svg = this.svg;
if (!svg) {
svg = this._createSvg(container);
}
this._render_bg_canvas(svg, items, {
fromX: 0,
toX: countX,
fromY: 0,
toY: countY
});
},
_createSvg: function (container) {
var svg = SVG(container);
$(svg.node).css({position: "absolute"});
this.svg = svg;
return svg;
},
switchFullRender: function (fullRender) {
if (this.fullCanvasRender === fullRender) return;
this.fullCanvasRender = fullRender;
this.render_items();
},
isScrolledOut: function (x, y) {
if (this.fullCanvasRender) return false;
if (this.forceRender) return true;
var lastPos = this.lastPos;
if (!lastPos) return true;
var limits = this.getCanvasLimits();
if (x !== undefined) {
var bufferX = (limits.x - window.innerWidth) / 2;
if (Math.abs(x - lastPos.x) > bufferX) return true;
}
if (y !== undefined) {
var bufferY = (limits.y - window.innerHeight) / 2;
if (Math.abs(y - lastPos.y) > bufferY) return true;
}
},
getCanvasLimits: function () {
return {x: window.innerWidth + 600, y: window.innerHeight + 600};
}
};
};

View File

@ -0,0 +1,278 @@
/* bars.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.view = ysy.view || {};
ysy.view.bars = ysy.view.bars || {};
$.extend(ysy.view.bars, {
_dateCache: {}, // for faster parsing YYYY-MM-DD to moment
_rendererStack: {},
registerRenderer: function (entity, renderer) {
if (this._rendererStack[entity] === undefined) {
this._rendererStack[entity] = [];
}
var renderers = this._rendererStack[entity];
var found = false;
for (var i = 0; i < renderers.length; i++) {
if (renderers[i] === renderer) found = true;
}
if (found) return;
renderers.push(renderer);
this.reconstructRenderer(entity);
},
removeRenderer: function (entity, renderer) {
var renderers = this._rendererStack[entity];
if (!renderers) return;
for (var i = 0; i < renderers.length; i++) {
if (renderers[i] === renderer) {
renderers.splice(i, 1);
this.reconstructRenderer(entity);
return;
}
}
},
reconstructRenderer: function (entity) {
var renderers = this._rendererStack[entity];
if (renderers.length === 0) {
gantt.config.type_renderers[entity] = gantt._task_default_render;
return;
}
gantt.config.type_renderers[entity] = function (task) {
var i = renderers.length - 1;
var nextRenderer = function () {
if (i < 0) return gantt._task_default_render;
return renderers[i--];
};
return nextRenderer().call(this, task, nextRenderer);
}
},
getFromDateCache: function (allodate) {
var alloMoment = this._dateCache[allodate];
if (alloMoment === undefined) {
alloMoment = moment(allodate);
this._dateCache[allodate] = alloMoment;
}
return alloMoment;
},
insertCanvas:function (canvas,rootDiv) {
var taskLeftElements = rootDiv.getElementsByClassName("task_left");
if (taskLeftElements.length === 0) {
rootDiv.appendChild(canvas);
} else {
rootDiv.insertBefore(canvas, taskLeftElements[0]);
}
},
canvasListBuilder: function () {
return {
__proto__: this.canvasListPrototype
};
//return canvasList;
},
canvasListPrototype: {
limit: 8170,
build: function (task, gantt, start_date, end_date) {
// initialization
this.canvases = [];
this.contexts = [];
this.starts = [];
this.gantt = gantt;
this.isAssignee = task.type === "assignee";
this.el = null;
this.height = this.isAssignee ? gantt.config.row_height : gantt._tasks.bar_height;
this.columnWidth = gantt._tasks.col_width;
var startX = gantt.posFromDate(start_date || task.start_date);
var endX = gantt.posFromDate(end_date || task.end_date);
//var fullWidth = gantt._get_task_width(task);
var fullWidth = endX - startX;
this.startX = startX;
this.fullWidth = fullWidth;
var config = gantt._tasks;
if (fullWidth < this.limit) {
this.el = this.createCanvas(fullWidth);
this.starts.push(startX);
this.staticPack = {
ctx: this.contexts[0],
canvas: this.el,
start: startX,
end: startX + fullWidth
};
} else {
this.el = document.createElement("div");
var lefts = config.left;
for (var i = 0; i < lefts.length; i++) {
if (lefts[i] >= startX) break;
}
var partX = startX;
for (; i < lefts.length; i++) {
if (lefts[i] > fullWidth + startX) break;
if (lefts[i] >= partX + this.limit) {
var canvas = this.createCanvas(lefts[i - 1] - partX);
this.el.appendChild(canvas);
this.starts.push(partX);
partX = lefts[i - 1];
}
}
canvas = this.createCanvas(startX + fullWidth - partX);
this.el.appendChild(canvas);
this.starts.push(partX);
}
this.el.className += " gantt-task-bar-line";
if (this.isAssignee) {
var y = this.gantt.getTaskTop(task.id);
this.el.style.left = startX + "px";
this.el.style.top = y + "px";
}
},
createCanvas: function (width) {
var el = document.createElement("canvas");
//var height = this.gantt._tasks.bar_height;
width = Math.round(width);
el.style.width = width + "px";
el.width = width;
el.height = this.height - 1;
el.className = "gantt-task-bar-canvas";
this.canvases.push(el);
var ctx = el.getContext("2d");
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
this.contexts.push(ctx);
return el;
},
getElement: function () {
return this.el;
},
inRange: function (date) {
var pos = gantt.posFromDateCached(date);
return pos + this.columnWidth >= this.startX && pos < this.fullWidth + this.startX;
},
fillTextAt: function (date, text, styles) {
var x = gantt.posFromDateCached(date);
var pack = this.getPack(x);
var posPack = this.getPosPack(x, pack);
var ctx = pack.ctx;
if (styles.backgroundColor) {
this.fillRectAtPosPack(posPack, pack, styles.backgroundColor);
}
ctx.font = styles.fontStyle;
ctx.fillStyle = styles.textColor;
text = this.fitTextInWidth(text, posPack.width, ctx);
ctx.fillText(text, posPack.middle, this.height / 2 + 1);
},
fillFormattedTextAt: function (date, formatter, value, styles) {
var x = gantt.posFromDateCached(date);
var pack = this.getPack(x);
var posPack = this.getPosPack(x, pack);
var ctx = pack.ctx;
if (styles.backgroundColor) {
this.fillRectAtPosPack(posPack, pack, styles.backgroundColor, styles.shrink);
}
ctx.font = styles.fontStyle;
ctx.fillStyle = styles.textColor;
var text = formatter(value, posPack.width);
text = this.fitTextInWidth(text, posPack.width, ctx);
ctx.fillText(text, posPack.middle, this.height / 2 + 1);
},
fillTwoTextAt: function (date, textUpper, textBottom, styles) {
var x = gantt.posFromDateCached(date);
var pack = this.getPack(x);
var posPack = this.getPosPack(x, pack);
var ctx = pack.ctx;
if (styles.backgroundColor) {
this.fillRectAtPosPack(posPack, pack, styles.backgroundColor, styles.shrink);
}
var bottomLine = this.height / 2 + 1;
ctx.fillStyle = styles.textColor;
if (textUpper) {
ctx.font = styles.fontStyle.replace("12px", "9px");
bottomLine = bottomLine * 13.0 / 10;
textUpper = this.fitTextInWidth(textUpper, posPack.width, ctx);
ctx.fillText(textUpper, posPack.middle, this.height * 3 / 12);
}
if (textBottom) {
ctx.font = styles.fontStyle;
// ctx.fillStyle = styles.textColor;
textBottom = this.fitTextInWidth(textBottom, posPack.width, ctx);
ctx.fillText(textBottom, posPack.middle, bottomLine);
}
},
fillRectAtPosPack: function (posPack, pack, fillColor, shrink) {
pack.ctx.fillStyle = fillColor;
if (shrink) {
pack.ctx.fillRect(posPack.start + 1, 1, posPack.width - 3, this.height - 3);
} else {
pack.ctx.fillRect(posPack.start, 0, posPack.width, this.height);
}
},
roundTo1: function (number) {
if (number === undefined) return "";
var modulated = number % 1;
if (modulated < 0) {
modulated += 1;
}
if (modulated < this.MARGIN || modulated > (1 - this.MARGIN)) {
return number.toFixed();
}
return number.toFixed(1);
},
fitTextInWidth: function (text, width, ctx) {
width -= 2;
if (text.length * 7.2 < width) return text;
ctx.font = ctx.font.replace("12px", "9px");
if (text.length * 5.3 < width) return text;
var splitPos = Math.floor(width / 5.3 - 1);
return text.substring(0, splitPos) + "#";
},
getPosPack: function (x, pack) {
var start, end, width = this.columnWidth;
if (!pack) return null;
start = x - pack.start;
if (x < pack.start || x > pack.end - width) {
end = start + width + Math.min(0, pack.end - width - x);
start = Math.max(start, 0);
return {
start: start,
end: end,
middle: Math.floor((start + end) / 2),
width: end - start
};
} else {
return {
start: start,
end: start + width,
middle: Math.floor(start + width / 2),
width: width
};
}
},
getPack: function (pos) {
if (this.staticPack) return this.staticPack;
//var pos = gantt.posFromDateCached(date);
// var min = this.startX;
var mid = pos + this.columnWidth / 2;
// if (pos + width < min) return null;
// if (pos >= this.fullWidth + min) return null;
for (var i = 1; i < this.starts.length; i++) {
if (this.starts[i] > mid) break;
}
if (i >= this.starts.length) {
i = this.starts.length;
var end = this.startX + this.fullWidth;
} else {
end = this.starts[i];
}
return {
ctx: this.contexts[i - 1],
canvas: this.canvases[i - 1],
start: this.starts[i - 1],
end: end
};
}
}
});

View File

@ -0,0 +1,148 @@
/* collapsor.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.pro = ysy.pro || {};
ysy.pro.collapsor = ysy.pro.collapsor || {};
$.extend(ysy.pro.collapsor, {
templateHtml: null,
patch: function () {
var $sourceDiv = $("#close_all_something");
this.templateHtml = '<div id="gantt_grid_collapsors" class="gantt-grid-header-collapse-buttons">' + $sourceDiv.html() + '</div>';
$sourceDiv.remove();
},
extendees: [
{
id: "close_all_parent_issues",
bind: function () {
this.model = ysy.data.limits;
},
func: function () {
var openings = this.model.openings;
var issues = ysy.data.issues.getArray();
this.model.parentsIssuesClosed = !this.model.parentsIssuesClosed;
if (this.model.parentsIssuesClosed) {
for (var i = 0; i < issues.length; i++) {
openings[issues[i].getID()] = false;
}
} else {
for (i = 0; i < issues.length; i++) {
delete openings[issues[i].getID()];
}
}
this.model._fireChanges(this, "close_all_parent_issues");
return false;
},
isOn: function () {
return this.model.parentsIssuesClosed;
}
},
{
id: "close_all_milestones",
bind: function () {
this.model = ysy.data.limits;
},
func: function () {
var openings = this.model.openings;
var milestones = ysy.data.milestones.getArray();
this.model.milestonesClosed = !this.model.milestonesClosed;
if (this.model.milestonesClosed) {
for (var i = 0; i < milestones.length; i++) {
openings[milestones[i].getID()] = false;
}
} else {
for (i = 0; i < milestones.length; i++) {
delete openings[milestones[i].getID()];
}
}
this.model._fireChanges(this, "close_all_milestones");
return false;
},
isOn: function () {
return this.model.milestonesClosed;
}
},
{
id: "close_all_projects",
bind: function () {
this.model = ysy.data.limits;
},
func: function () {
var openings = this.model.openings;
var projects = ysy.data.projects.getArray();
this.model.projectsClosed = !this.model.projectsClosed;
if (this.model.projectsClosed) {
for (var i = 0; i < projects.length; i++) {
if (projects[i].id === ysy.settings.projectID) continue;
delete openings[projects[i].getID()];
// gantt.close(projects[i].getID());
}
} else {
for (i = 0; i < projects.length; i++) {
if (!projects[i].needLoad) {
openings[projects[i].getID()] = true;
}
//gantt.open(projects[i].getID());
}
}
this.model._fireChanges(this, "close_all_projects");
return false;
},
isOn: function () {
return this.model.projectsClosed;
}
}
]
});
//#############################################################################################
ysy.view.Collapsors = function () {
ysy.view.Widget.call(this);
};
ysy.main.extender(ysy.view.Widget, ysy.view.Collapsors, {
name: "CollapsorsWidget",
_postInit:function(){
this.model = ysy.settings.resource;
this.model.unregister(this);
this.model.register(this.requestRepaint,this);
},
_updateChildren: function () {
for (var i = 0; i < this.children.length; i++) {
this.children.destroy();
}
this.children = [];
var collapsorClass = ysy.pro.collapsor;
for (i = 0; i < collapsorClass.extendees.length; i++) {
var extendee = collapsorClass.extendees[i];
var button = new ysy.view.Button();
$.extend(button, extendee);
button.init();
this.children.push(button);
}
},
repaint: function (force) {
var $target = $("#gantt_grid_collapsors");
if(this.repaintRequested){
if(this.model.open){
$target.hide();
return;
}else{
$target.show();
}
$target.off("click").on("click",function(){
return false;
});
}
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
child.$target = this.getChildTarget(child);
if(!child.$target.length) continue;
child.repaint(force || this.repaintRequested);
}
this.repaintRequested=false;
},
getChildTarget: function (child) {
return this.$target.find("#" + child.elementPrefix + child.id);
}
});

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,478 @@
/* dhtml_addons.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.view = ysy.view || {};
ysy.view.addGanttAddons = function () {
gantt.ascStop = function (task, start_date, end_date, ancestorLink) {
var diff;
if (task.soonest_start && start_date && start_date.isBefore(task.soonest_start)) {
diff = task.soonest_start.diff(start_date, "seconds");
start_date.add(diff, "seconds");
if (end_date) end_date.add(diff, "seconds");
}
if (task.latest_due && end_date && end_date.isAfter(task.latest_due)) {
diff = task.latest_due.diff(end_date, "seconds");
end_date.add(diff, "seconds");
if (start_date) start_date.add(diff, "seconds");
}
var sumMove = 0;
for (var i = 0; i < task.$target.length; i++) {
var lid = task.$target[i];
if (ancestorLink && parseInt(lid) === ancestorLink.id) continue; // skip link sourcing moved parent
var link = gantt._lpull[lid];
if (link.isSimple) continue;
var targetDate;
if (link.type === "precedes" || link.type == "start_to_start") {
if (!start_date) continue;
targetDate = start_date;
} else if (link.type === "finish_to_finish" || link.type == "start_to_finish") {
if (!end_date) continue;
targetDate = end_date;
} else continue;
//if (link.type !== "precedes") continue;
var source = gantt._pull[link.source];
var sourceDate = gantt.getLinkSourceDate(source, link.type);
if (ysy.settings.workDayDelays) {
var linkLast = gantt._working_time_helper.add_worktime(sourceDate, link.delay, "day", targetDate._isEndDate === true);
diff = -targetDate.diff(linkLast, "seconds");
} else {
diff = -targetDate.diff(sourceDate, "seconds") + (link.delay + gantt.getLinkCorrection(link.type)) * 24 * 60 * 60;
}
// ysy.log.debug("sourceDate="+sourceDate.toISOString()+" diff="+diff);
if (diff > 0) {
sumMove += diff;
//ysy.log.debug("ascStop linkLast=" + linkLast.format("YYYY-MM-DD") + " diff=" + diff, "task_drag");
if (start_date) {
start_date.add(diff, "seconds");
}
if (end_date) {
end_date.add(diff, "seconds");
}
}
}
return sumMove;
};
gantt.multiStop = gantt.ascStop;
gantt.moveDesc = function (task, diff, ancestorLink, resizing) {
if (typeof(diff) === "object") {
diff = task.start_date.diff(diff.old_start, "seconds");
}
// runs after task dates are already modified.
ysy.log.debug("moveDesc(): task=" + task.text + " diff=" + (diff / 86400) + (ancestorLink ? " ancestorLink=" + ancestorLink.id : ""), "task_drag");
var first = !ancestorLink;
if (first && task.type === "milestone") {
var oldTask = gantt._pull[task.id];
oldTask.end_date = task.end_date;
}
var bothDir = false;
// diff in seconds
if (diff === 0) return 0;
if (diff <= 0 && !bothDir) {
gantt.moveChildren(task, diff, first);
return 0;
}
var mileBack = 0;
if (diff > 0) {
if (ysy.settings.milestonePush) {
mileBack = gantt.milestoneDescStop(task, first ? 0 : diff);
if (mileBack !== 0) {
diff -= mileBack;
ysy.log.debug("task=" + task.text + " oldDiff=" + ((diff + mileBack) / 86400) + " newDiff=" + (diff / 86400) + " mileDiff=" + (mileBack / 86400), "task_drag_milestone");
}
} else {
gantt.milestoneMoveBy(task, first ? 0 : diff);
}
}
if (first && mileBack !== 0) {
if (resizing !== "right") {
task.start_date.add(Math.floor(-mileBack), 'seconds');
}
if (resizing !== "left") {
task.end_date.add(Math.floor(-mileBack), 'seconds');
}
gantt.refreshTask(task.id);
ysy.log.debug("FIRST " + task.text + " corrected by mileDiff=" + (mileBack / 3600 / 24) + " to " + task.start_date.format("YYYY-MM-DD"), "task_drag_milestone");
}
var movedByChildren = gantt.moveChildren(task, diff, first);
if (!first && (diff > 0 || bothDir)) {
if(!movedByChildren){
ysy.log.debug("Task " + task.text + " pushed by " + (diff / 86400) + " days", "task_drag");
task.start_date.add(Math.floor(diff), 'seconds');
task.end_date.add(Math.floor(diff), 'seconds');
}
// var oldStartDate = moment(task.start_date);
task._changed = gantt.config.drag_mode.move;
gantt.refreshTask(task.id);
}
if (!first && diff < 0) {
var ascDiff = gantt.ascStop(task, task.start_date, task.end_date, ancestorLink);
if (ascDiff !== 0) {
// ysy.log.debug("diff=" + diff + " ascStopDiff=" + ascDiff);
diff += ascDiff;
}
}
var start_date = +task.start_date / 1000;
var end_date = +task.end_date / 1000;
for (var i = 0; i < task.$source.length; i++) {
var lid = task.$source[i];
var link = gantt._lpull[lid];
if (link.isSimple) continue;
var desc = gantt._pull[link.target];
if (diff < 0 && bothDir) {
// ysy.log.debug("desc=" + desc.text +" diff="+diff);
gantt.moveDesc(desc, diff, link);
// ysy.log.debug("task=" + task.text + " diff=" + diff + " reduced by " + backDiff);
} else {
var descDiff = gantt.getFreeDelay(link, desc, start_date, end_date);
if (descDiff <= 0) continue;
// ysy.log.debug("desc=" + desc.text +" diff="+diff+" descDiff="+descDiff);
gantt.moveDesc(desc, descDiff, link);
}
}
//ysy.log.debug("Task " + task.text + " pushed back by " + (diff / 86400) + " days", "task_drag");
return 0;
};
gantt.moveChildren = function (task, shift, first) {
if (!(gantt._get_safe_type(task.type) === "task" && ysy.settings.parentIssueDates)) {
if (task.$open && gantt.isTaskVisible(task.id)) {
if (task.type === "milestone") gantt.moveMilestoneChildren(task);
return;
}
}
var branch = gantt._branches[task.id];
if (!branch || branch.length === 0) return;
ysy.log.debug("Shift children of \"" + task.text + "\" by " + shift + " seconds", "parent");
ysy.log.debug("moveChildren(): of \"" + task.text + "\" by " + shift + " seconds", "task_drag");
var parentStartDate = +task.start_date;
if (first) {
parentStartDate -= shift * 1000;
}
var shiftedParentDate = moment(parentStartDate + shift * 1000);
for (var i = 0; i < branch.length; i++) {
var childId = branch[i];
//if(gantt.isTaskVisible(childId)){continue;}
var child = gantt.getTask(childId);
if (!child._parent_offset) {
child._parent_offset = gantt._working_time_helper.get_work_units_between(parentStartDate, child.start_date, "day");
}
var childStartDiff = gantt._working_time_helper.add_worktime(
shiftedParentDate, child._parent_offset, "day", false
) - child.start_date;
child.start_date.add(childStartDiff, 'milliseconds');
var childEndDiff = gantt._working_time_helper.add_worktime(child.start_date, child.duration, 'day', true) - child.end_date;
child.end_date.add(childEndDiff, 'milliseconds');
gantt.ascStop(child, child.start_date, child.end_date);
child._changed = gantt.config.drag_mode.move;
gantt.refreshTask(child.id);
gantt.moveDesc(child, childStartDiff);
}
};
gantt.moveMilestoneChildren = function (milestone) {
var branch = gantt._branches[milestone.id];
if (!branch || branch.length === 0) return 0;
// ysy.log.debug("Shift children of \"" + milestone.text + "\" by " + shift + " seconds", "parent");
// ysy.log.debug("moveChildren(): of \"" + milestone.text + "\" by " + shift + " seconds", "task_drag");
for (var i = 0; i < branch.length; i++) {
var childId = branch[i];
var child = gantt.getTask(childId);
if (child.end_date.isAfter(milestone.end_date)) {
var shift = milestone.end_date.diff(child.end_date, "seconds");
child.start_date.add(shift, 'seconds');
child.end_date.add(shift, 'seconds');
child._changed = gantt.config.drag_mode.move;
gantt.refreshTask(child.id);
gantt.moveDesc(child, shift);
}
}
return 0;
};
gantt.milestoneStop = function (task, diff) {
var issue = task.widget && task.widget.model;
if (!issue) return 0;
var milestone = ysy.data.milestones.getByID(issue.fixed_version_id);
if (!milestone) return 0;
var ganttMilestone = gantt._pull[milestone.getID()];
if (ganttMilestone) {
var milDiff = ganttMilestone.end_date.diff(task.end_date, "seconds");
} else {
milDiff = milestone.start_date.diff(task.end_date, "seconds");
}
milDiff -= diff;
if (milDiff < 0) {
ysy.log.debug("milestoneStop() for " + task.text + " milDiff=" + (milDiff / 86400) +
" diff=" + (diff / 86400) + " at " + milestone.start_date.format("YYYY-MM-DD"), "task_drag_milestone");
return -milDiff;
}
return 0;
};
gantt.milestoneDescStop = function (task, diff) {
ysy.log.debug("milestoneDescStop(): task " + task.text + " moving by " + (diff / 86400), "task_drag_milestone");
var backDiff = gantt.milestoneStop(task, diff);
var start_date = +task.start_date / 1000 + diff;
var end_date = +task.end_date / 1000 + diff;
for (var i = 0; i < task.$source.length; i++) {
var lid = task.$source[i];
var link = gantt._lpull[lid];
if (link.isSimple) continue;
var desc = gantt._pull[link.target];
var descDiff = gantt.getFreeDelay(link, desc, start_date, end_date);
if (descDiff <= 0) continue;
backDiff = Math.max(backDiff, gantt.milestoneDescStop(desc, descDiff));
}
return backDiff;
};
gantt.milestoneMoveBy = function (task, diff) {
ysy.log.debug("milestoneMoveBy(): task " + task.text + " moving by " + (diff / 86400), "task_drag");
var issue = task.widget && task.widget.model;
if (!issue) return;
var milestone = ysy.data.milestones.getByID(issue.fixed_version_id);
if (!milestone) return;
var ganttMilestone = gantt._pull[milestone.getID()];
var taskDate;
if (diff === 0) {
taskDate = task.end_date;
} else {
taskDate = moment(task.end_date).add(diff, "seconds");
}
if (ganttMilestone) {
if (ganttMilestone.end_date.isBefore(taskDate)) {
var moveDiff = taskDate.diff(ganttMilestone.end_date);
ganttMilestone.end_date.add(moveDiff, "milliseconds");
ganttMilestone.start_date.add(moveDiff, "milliseconds");
ganttMilestone._changed = gantt.config.drag_mode.move;
gantt.refreshTask(ganttMilestone.id);
}
}
};
gantt.getLinkSourceDate = function (source, type) {
if (type === "precedes") return source.end_date;
if (type === "finish_to_finish") return source.end_date;
if (type === "start_to_start") return source.start_date;
if (type === "start_to_finish") return source.start_date;
return null;
};
gantt.getLinkTargetDate = function (target, type) {
if (type === "precedes") return target.start_date;
if (type === "finish_to_finish") return target.end_date;
if (type === "start_to_start") return target.start_date;
if (type === "start_to_finish") return target.end_date;
return null;
};
gantt.getLinkCorrection = function (type) {
if (type === "precedes") return 1;
if (type === "start_to_finish") return -1;
return 0;
};
gantt.getFreeDelay = function (link, desc, ascStartDate, ascEndDate) {
if (!desc) desc = gantt._pull[link.target];
var sourceDate;
var daysToSeconds = 60 * 60 * 24;
if (!ascStartDate) {
var asc = gantt._pull[link.source];
ascStartDate = asc.start_date / 1000;
ascEndDate = asc.end_date / 1000;
}
if (link.type === "precedes" || link.type === "finish_to_finish") {
if (!ascEndDate) return 0;
sourceDate = ascEndDate;
} else if (link.type === "start_to_finish" || link.type === "start_to_start") {
if (!ascStartDate) return 0;
sourceDate = ascStartDate;
} else return 0;
var targetDate = gantt.getLinkTargetDate(desc, link.type);
var correction = gantt.getLinkCorrection(link.type);
var delay = (targetDate / 1000 - sourceDate) / daysToSeconds;
return (link.delay + correction - delay) * daysToSeconds;
};
gantt.updateAllTask = function (seed_task) {
ysy.history.openBrack();
var toUpdate = {};
// sort + reverse in order to process milestones before tasks
var pullIds = Object.getOwnPropertyNames(gantt._pull).sort().reverse();
var allRequests = {};
if (ysy.settings.fixedRelations) {
for (var i = 0; i < pullIds.length; i++) {
var task = gantt._pull[pullIds[i]];
if (task._changed) {
//gantt._tasks_dnd._fix_dnd_scale_time(task,{mode:task._changed});
gantt._tasks_dnd._fix_working_times(task, {mode: task._changed});
gantt._update_parents(task.id, false);
delete task._parent_offset;
var parentId = gantt.getParent(task.id);
while (parentId) {
var parent = gantt._pull[parentId];
if (!parent) break;
toUpdate[parentId] = parent;
parentId = gantt.getParent(parentId);
}
toUpdate[task.id] = task;
// var issue = task.widget.model;
// if (issue.getMoveRequest) {
// var request = issue.getMoveRequest(allRequests);
// request.setPosition(task.start_date, task.end_date, true);
// }
task._changed = false;
}
}
} else {
for (i = 0; i < pullIds.length; i++) {
task = gantt._pull[pullIds[i]];
if (task._changed) {
//gantt._tasks_dnd._fix_dnd_scale_time(task,{mode:task._changed});
gantt._tasks_dnd._fix_working_times(task, {mode: task._changed});
gantt._update_parents(task.id, false);
delete task._parent_offset;
toUpdate[task.id] = task;
var issue = task.widget.model;
if (issue.getMoveRequest) {
var request = issue.getMoveRequest(allRequests);
request.setPosition(task.start_date, task.end_date, true);
}
task._changed = false;
ysy.log.debug("UpdateAllTask update " + task.text, "task_drag");
}
}
}
for (var id in allRequests) {
if (!allRequests.hasOwnProperty(id)) continue;
request = allRequests[id];
request.entity.correctPosition(allRequests);
}
for (id in allRequests) {
if (!allRequests.hasOwnProperty(id)) continue;
request = allRequests[id];
task = toUpdate[id];
if (task) {
$.extend(task, {start_date: request.softStart, end_date: request.softEnd});
} else {
if (!request.entity.set({start_date: request.softStart, end_date: request.softEnd})) {
request.entity._fireChanges({_name: "UpdateAll"}, "updateAll");
}
}
}
for (id in toUpdate) {
if (!toUpdate.hasOwnProperty(id)) continue;
task = toUpdate[id];
ysy.log.debug("UpdateAllTask update " + task.text, "task_drag");
task.widget.update(task);
// for (var j = 0; j < task.$target.length; j++) {
// var link = gantt._lpull[task.$target[j]];
// if (!link) continue;
// if (!link.unlocked) continue;
// var source = gantt._pull[link.source];
// if (!source) continue;
// var targetDate = gantt.getLinkTargetDate(task, link.type);
// var sourceDate = gantt.getLinkSourceDate(source, link.type);
// var correction = gantt.getLinkCorrection(link.type);
// var delay = targetDate.diff(sourceDate, "days") - correction;
// // ysy.log.debug("Link from "+source.id+" to "+task.id+" delay="+delay );
// var relation = link.widget.model;
// if (!relation) continue;
// relation.set("delay", delay);
// }
}
ysy.history.closeBrack();
};
gantt.applyMoveRequests = function (allRequests) {
for (var id in allRequests) {
if (!allRequests.hasOwnProperty(id)) continue;
var request = allRequests[id];
if (!request.entity.set({start_date: request.softStart, end_date: request.softEnd})) {
request.entity._fireChanges({_name: "applyMoveRequests"}, "applyMoveRequests");
}
}
};
gantt.checkLoopedLink = function (target, bannedId) {
var relations = ysy.data.relations.getArray();
for (var i = 0; i < relations.length; i++) {
if (relations[i].source_id !== target.id) continue;
var relation = relations[i];
if (relation.target_id == bannedId) return false;
var nextTarget = relation.getTarget();
if (!gantt.checkLoopedLink(nextTarget, bannedId)) return false;
}
return true;
};
//###############################################################################
gantt.render_delay_element = function (link, pos) {
if (link.widget && link.widget.model.isSimple) return null;
//if(link.delay===0){return null;}
var sourceDate = gantt.getLinkSourceDate(gantt._pull[link.source], link.type);
var targetDate = gantt.getLinkTargetDate(gantt._pull[link.target], link.type);
if (ysy.settings.workDayDelays) {
var actualDelay = gantt._working_time_helper.get_work_units_between(sourceDate, targetDate, "day");
actualDelay = Math.round(actualDelay);
} else {
actualDelay = targetDate.diff(sourceDate, "hours") / 24;
actualDelay = Math.round(actualDelay) - gantt.getLinkCorrection(link.type);
}
var text = (link.delay ? link.delay : '') + (actualDelay !== link.delay ? ' (' + actualDelay + ')' : '');
return $('<div>')
.css({position: "absolute", left: pos.x, top: pos.y})
// .html(link.delay+" ("+actualDelay + ")")[0];
.html(text)[0];
};
//##############################################################################
/*
* Přepsané funkce z dhtmlxganttu, kvůli efektivnějšímu napojení či kvůli odstranění bugů
*/
//##########################################################################################
gantt.allowedParent = function (child, parent) {
if (child === parent) return false;
var type = child.type;
if (!type) {
type = "task";
}
var allowed = gantt.config["allowedParent_" + type];
if (!allowed) return false;
if (parent.real_id > 1000000000000) return false;
var parentType = parent.type || "task";
return allowed.indexOf(parentType) >= 0;
};
gantt.getShowDate = function () {
var pos = gantt._restore_scroll_state();
if (!pos) return null;
return this.dateFromPos(pos.x + this.config.task_scroll_offset);
};
gantt.silentMoveTask = function (task, parentId) {
ysy.log.debug("silentMoveTask", "move_task");
var id = task.id;
var sourceId = this.getParent(id);
if (sourceId == parentId) return;
this._replace_branch_child(sourceId, id);
var tbranch = this.getChildren(parentId);
tbranch.push(id);
this.setParent(task, parentId);
this._branches[parentId] = tbranch;
var childTree = this._getTaskTree(id);
for (var i = 0; i < childTree.length; i++) {
var item = this._pull[childTree[i]];
if (item)
item.$level = this.calculateTaskLevel(item);
}
task.$level = gantt.calculateTaskLevel(task);
this.refreshData();
};
gantt.getCachedScroll = function () {
if (!gantt._cached_scroll_pos) return {x: 0, y: 0};
return {x: gantt._cached_scroll_pos.x || 0, y: gantt._cached_scroll_pos.y || 0};
};
gantt.reconstructTree = function () {
var tasks = gantt._pull;
var ids = Object.getOwnPropertyNames(tasks);
for (var i = 0; i < ids.length; i++) {
var task = tasks[ids[i]];
if (task.realParent === undefined) continue;
gantt.silentMoveTask(task, task.realParent);
delete task.realParent;
}
}
};

View File

@ -0,0 +1,696 @@
/* dhtml_modif.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.view = ysy.view || {};
ysy.view.initGantt = function () {
var toMomentFormat = function (rubyFormat) {
switch (rubyFormat) {
case '%Y-%m-%d':
return 'YYYY-MM-DD';
case '%Y/%m/%d':
return 'YYYY/MM/DD';
case '%d/%m/%Y':
return 'DD/MM/YYYY';
case '%d.%m.%Y':
return 'DD.MM.YYYY';
case '%d-%m-%Y':
return 'DD-MM-YYYY';
case '%m/%d/%Y':
return 'MM/DD/YYYY';
case '%d %b %Y':
return 'DD MMM YYYY';
case '%d %B %Y':
return 'DD MMMM YYYY';
case '%b %d, %Y':
return 'MMM DD, YYYY';
case '%B %d, %Y':
return 'MMMM DD, YYYY';
default:
return 'D. M. YYYY';
}
};
function getERUISassValue(varName, defaultValue) {
if (window.ERUI && ERUI.sassData !== undefined && ERUI.sassData[varName] !== undefined) {
return parseInt(ERUI.sassData[varName]);
}
return defaultValue;
}
$.extend(gantt.config, {
//xml_date: "%Y-%m-%d",
//scale_unit: "week",
//date_scale: "Week #%W",
//autosize:"y",
details_on_dblclick: false,
readonly_project: true,
//autofit:true,
drag_empty: true,
work_time: true,
//min_duration:24*60*60*1000, // 1*24*60*60*1000s = 1 day
correct_work_time: true,
//date_grid: "%j %M %Y",
date_format: toMomentFormat(ysy.settings.dateFormat),
date_grid: "%j.%n.%Y",
links: {
finish_to_start: "precedes",
start_to_start: "start_to_start",
start_to_finish: "start_to_finish",
finish_to_finish: "finish_to_finish"
},
step: 1,
duration_unit: "day",
fit_tasks: true,
row_height: getERUISassValue('gantt-row-height', 25),
task_height: getERUISassValue('gantt-task-height', 20),
min_column_width: 36,
autosize: "y",
link_line_width: 0,
scale_height: 60,
start_on_monday: true,
order_branch: true,
rearrange_branch: true,
grid_resize: true,
grid_width: ysy.data.limits.columnsWidth.grid_width,
task_scroll_offset: 250,
controls_task: {progress: true, resize: true, links: true},
controls_milestone: {},
start_date: ysy.data.limits.start_date,
end_date: ysy.data.limits.end_date,
controls_project: {show_progress: true, resize: false},
allowedParent_task: ["project", "milestone", "empty"],
allowedParent_task_global: ["project", "milestone"],
allowedParent_milestone: ["project"],
allowedParent_project: ["empty"]
});
gantt.config.columns = ysy.view.leftGrid.constructColumns(ysy.data.columns);
ysy.proManager.fireEvent("ganttConfig", gantt.config);
gantt._pull["empty"] = {
type: "empty",
id: "empty",
$target: [],
$source: [],
columns: {},
text: "",
start_date: moment()
};
};
ysy.view.applyGanttPatch = function () {
ysy.view.leftGrid.patch();
gantt.locale.date = ysy.settings.labels.date;
$.extend(gantt.templates, {
task_cell_class: function (item, date) {
if (gantt.config.scale_unit === "day") {
//var css="";
if (moment(date).date() === 1) {
return true;
// css+=" first-date";
}
//return css;
}
return false;
},
scale_cell_class: function (date) {
if (gantt.config.scale_unit === "day") {
var css = "";
if (!gantt._working_time_helper.is_working_day(date)) {
css += " weekend";
}
//if(date.getDate()===1){
if (moment(date).date() === 1) {
css += " first-date";
}
return css;
}
},
task_text: function (start, end, task) {
return "";
},
task_class: function (start, end, task) {
var css = "";
if (task.css) {
css = task.css;
}
css += " " + (task.type || "task") + "-type";
if (task.widget && task.widget.model) {
var problems = task.widget.model.getProblems();
if (problems) {
css += " wrong";
}
}
return css;
},
grid_row_class: function (start, end, task) {
var ret = "";
if (task.css) {
ret = task.css;
}
if (task.widget && task.widget.model) {
var problems = task.widget.model.getProblems();
if (problems) {
ret += " wrong";
}
}
ret += " " + (task.type || "task") + "-type";
return ret;//+'" data-url="/issues/'+task.id+' data-none="';
//return task.css+" "+task.type+"-type";
},
/*grid_file: function (item) {
return "";
//return "<div class='gantt_tree_icon gantt_file'></div>";
},*/
link_class: function (link) {
var css = "type-" + link.type;
if (link.widget) {
var relation = link.widget.model;
if (relation) {
if (!relation.checkDelay()) {
css += " wrong";
}
if (relation.isSimple) {
css += " gantt-relation-simple";
}
if (link.unlocked) {
css += " gantt-relation-unlocked";
}
}
}
return css;
},
drag_link: function (from, from_start, to, to_start) {
var labels = ysy.view.getLabel("links");
if (!gantt._get_link_type(from_start, to_start)) {
var reason = "unsupported_link_type";
} else if (from === to) {
reason = "loop_link";
} else if (to && to.length > 12) {
reason = "link_target_new";
} else if (to && gantt.getTask(to).readonly) {
reason = "link_target_readonly";
} else {
reason = "other";
}
var obj = {
errorReason: ysy.view.getLabel("errors2")[reason],
from: gantt.getTask(from).text
};
if (to) {
obj.to = gantt.getTask(to).text;
var ganttLinkType = (from_start ? "start" : "finish") + "_to_" + (to_start ? "start" : "finish");
obj.type = labels[gantt.config.links[ganttLinkType]];
}
return Mustache.render(ysy.view.templates.linkDragModal, obj);
},
scale_row_class: function (scale) {
return scale.className || "";
}
});
gantt.attachEvent("onRowDragStart", function (id /*, elem*/) {
//$(".gantt_grid_data").addClass("dragging");
var task = gantt.getTask(id);
$(".gantt_row").each(function () {
var target = gantt._pull[$(this).attr("task_id")];
if (!target) return;
if (gantt.allowedParent(task, target)) {
$(this).addClass("gantt_drag_to_allowed");
}
});
return true;
});
gantt.attachEvent("onRowDragEnd", function (id, elem) {
//$(".gantt_grid_data").removeClass("dragging");
$(".gantt_drag_to_allowed").removeClass("gantt_drag_to_allowed");
});
// Funkce pro vytvoření a posunování Today markeru
function initTodayMarker() {
var date_to_str = gantt.date.date_to_str(gantt.config.task_date);
var id = gantt.addMarker({start_date: new Date(), css: "today", title: date_to_str(new Date())});
setInterval(function () {
var today = gantt.getMarker(id);
today.start_date = new Date();
today.title = date_to_str(today.start_date);
gantt.updateMarker(id);
}, 1000 * 60 * 60);
}
initTodayMarker();
//gantt.initProjectMarker=function initProjectMarker(start,end) {
// if(start&&start.isValid()){
// var startMarker = gantt.addMarker({start_date: start.toDate(), css: "start", title: "Project start"});
// }
// if(end&&end.isValid()){
// var endMarker = gantt.addMarker({start_date: end.toDate(), css: "end", title: "Project due time"});
// }
//};
//initProjectMarker();
//##################################################################################
if (!ysy.settings.fixedRelations) {
gantt.attachEvent("onLinkClick", function (id, mouseEvent) {
if (!gantt.config.drag_links) return;
ysy.log.debug("LinkClick on " + id, "link_config");
var link = gantt.getLink(id);
if (gantt._is_readonly(link)) return;
var source = gantt._pull[link.source];
if (!source) return;
var target = gantt._pull[link.target];
if (!target) return;
if (source.readonly && target.readonly) return;
var linkConfigWidget = new ysy.view.LinkPopup().init(link.widget.model, link);
linkConfigWidget.$target = $("#ajax-modal");//$dialog;
linkConfigWidget.repaint();
showModal("ajax-modal", "auto");
return false;
});
}
gantt.attachEvent("onAfterLinkDelete", function (id, elem) {
if (elem.deleted) return;
if (!elem.widget.model._deleted) {
elem.widget.model.remove();
}
});
gantt.attachEvent("onBeforeLinkAdd", function (id, link) {
if (link.widget) return true;
var relations = ysy.data.relations;
var data;
data = {
id: id,
source_id: parseInt(link.source),
target_id: parseInt(link.target),
delay: 0,
unlocked: true,
permissions: {
editable: true
},
type: link.type
};
var relArray = relations.getArray();
for (var i = 0; i < relArray.length; i++) {
var relation = relArray[i];
if (relation.source_id === data.source_id && relation.target_id === data.target_id) {
dhtmlx.message(ysy.view.getLabel("errors2", "duplicate_link"), "error");
return false;
}
}
var rel = new ysy.data.Relation();
rel.init(data, relations);
//rel.delay=rel.getActDelay(); // created link have maximal delay
if (!gantt.checkLoopedLink(rel.getTarget(), rel.source_id)) {
dhtmlx.message(ysy.view.getLabel("errors2", "loop_link"), "error");
return false;
}
ysy.history.openBrack();
relations.push(rel);
var allRequests = {};
rel.sendMoveRequest(allRequests);
gantt.applyMoveRequests(allRequests);
ysy.history.closeBrack();
return false;
});
ysy.view.taskTooltip.taskTooltipInit();
dhtmlx.message = function (msg, type, delay) {
if (!type) {
type = msg.type;
msg = msg.text;
delay = msg.delay;
}
window.showFlashMessage(type, msg, delay && delay > 0 ? delay : undefined);
//if (type !== "notice") {
// var flashElement = $("#content").children(".flash")[0];
// var adjust = -10;
// if (ysy.settings.easyRedmine) {
// $(document).scrollTop(flashElement.offsetTop + adjust + "px");
// //window.scrollTo(".flash",adjust);
// } else {
// window.scrollTo(0, flashElement.offsetTop + adjust);
// }
//}
};
if (!window.showFlashMessage) {
window.showFlashMessage = function (type, message) {
var $content = $("#content");
$content.find(".flash").remove();
var template = '<div class="flash {{type}}"><a href="javascript:void(0)" class="close-icon close_button" style="float:right"></a><span>{{{message}}}</span></div>';
var closeFunction = function (event) {
$(this)
.closest('.flash')
.fadeOut(500, function () {
$(this).remove();
})
};
var rendered = Mustache.render(template, {message: message, type: type});
$content.prepend($(rendered));
$content.find(".close_button").click(closeFunction);
}
}
if (!dhtmlx.dragScroll) {
dhtmlx.dragScroll = function () {
var $background = $(".gantt_task_bg");
if (!$background.hasClass("inited")) {
$background.addClass("inited");
var dnd = new dhtmlxDnD($background[0], {});
var lastScroll = null;
dnd.attachEvent("onDragStart", function () {
lastScroll = gantt.getCachedScroll();
});
dnd.attachEvent("onDragMove", function () {
var diff = dnd.getDiff();
gantt.scrollTo(lastScroll.x - diff.x, undefined);
});
}
};
}
gantt.attachEvent("onTaskOpened", function (id) {
ysy.data.limits.openings[id] = true;
var task = gantt._pull[id];
if (!task || !task.widget) return true;
var entity = task.widget.model;
if (entity.needLoad) {
entity.needLoad = false;
ysy.data.loader.loadSubEntity(task.type, entity.id);
}
});
gantt.attachEvent("onTaskClosed", function (id) {
ysy.data.limits.openings[id] = false;
});
gantt.attachEvent("onTaskSelected", function (id) {
var data = gantt._get_tasks_data();
gantt._backgroundRenderer.render_items(data);
});
gantt.attachEvent("onTaskUnselected", function (id, ignore) {
if (ignore) return;
var data = gantt._get_tasks_data();
gantt._backgroundRenderer.render_items(data);
});
gantt.attachEvent("onLinkValidation", function (link) {
if (link.source.length > 12) return false;
if (link.target.length > 12) return false;
var source = gantt.getTask(link.source);
var target = gantt.getTask(link.target);
if (source.readonly && target.readonly) return false;
var parentId = source.id;
while (parentId !== 0) {
var parent = gantt.getTask(parentId);
if (parent === target) return false;
parentId = parent.parent;
}
parentId = target.id;
while (parentId !== 0) {
parent = gantt.getTask(parentId);
if (parent === source) return false;
parentId = parent.parent;
}
return true;
});
gantt.attachEvent("onAfterTaskMove", function (sid, parent, tindex) {
this.open(parent);
return true;
});
gantt._filter_task = function (id, task) {
// commented out because pushing task out of bounds removed the task and its project
//var min = null, max = null;
//if(this.config.start_date && this.config.end_date){
// min = this.config.start_date.valueOf();
// max = this.config.end_date.valueOf();
//
// if(+task.start_date > max || +task.end_date < +min)
// return false;
//}
return ysy.proManager.eventFilterTask(id, task);
};
//var oldPosFromDate = gantt.posFromDate;
//gantt.posFromDate = function(date){
// ysy.log.debug("old: "+oldPosFromDate.call(gantt,date)+" new: "+gantt.posFromDate2(date));
// return gantt.posFromDate2(date);
//};
gantt.posFromDate = function (date) {
var scale = this._tasks;
if (typeof date === "string") {
date = moment(date);
}
var tdate = date.valueOf();
var units = {
day: 86400000, // 24 * 60 * 60 * 1000
week: 604800000, // 7 * 24 * 60 * 60 * 1000
//month: 2592000000 // 30 * 24 * 60 * 60 * 1000
month: 2629800000, // 30.4375 * 24 * 60 * 60 * 1000
quarter: 7889400000, // 3 * 30.4375 * 24 * 60 * 60 * 1000
year: 31557600000 // 12 * 30.4375 * 24 * 60 * 60 * 1000
};
if (date._isEndDate) {
tdate += units.day;
}
if (tdate <= this._min_date)
return 0;
if (tdate >= this._max_date)
return scale.full_width;
var unitRatio = (tdate - scale.trace_x[0]) / units[scale.unit];
var index = Math.floor(unitRatio);
index = Math.min(scale.count - 1, Math.max(0, index));
if (scale.count === index + 1) {
return scale.left[index]
+ scale.width[index]
* (tdate - scale.trace_x[index])
/ (gantt._max_date - scale.trace_x[index]);
}
if (tdate > scale.trace_x[index + 1]) {
index++;
if (scale.count === index + 1) {
return scale.left[index]
+ scale.width[index]
* (tdate - scale.trace_x[index])
/ (gantt._max_date - scale.trace_x[index]);
}
} else {
while (index !== 0 && tdate < scale.trace_x[index]) index--;
}
var restRatio = (tdate - scale.trace_x[index]) / (scale.trace_x[index + 1] - scale.trace_x[index]);
return scale.left[index] + scale.width[index] * restRatio;
};
gantt.dateFromPos2 = function (x) {
// TODO tasks ends
var scale = this._tasks;
if (x < 0 || x > scale.full_width || !scale.full_width) {
scale.needRescale = true;
ysy.log.debug("needRescale", "outer");
}
if (!scale.trace_x.length) {
return 0;
}
// var units = {
// day: 86400000, // 24 * 60 * 60 * 1000
// week: 604800000, // 7 * 24 * 60 * 60 * 1000
// //month: 2592000000 // 30 * 24 * 60 * 60 * 1000
// month: 2629800000 // 30.4375 * 24 * 60 * 60 * 1000
// };
var unitRatio = x / (scale.full_width / scale.count);
var index = Math.floor(unitRatio);
index = Math.min(scale.count - 1, Math.max(0, index));
if (index === scale.count - 1) {
return gantt.date.Date(
scale.trace_x[index].valueOf()
+ (gantt._max_date - scale.trace_x[index])
* (x - scale.left[index])
/ scale.width[index]);
}
if (x > scale.left[index + 1]) {
index++;
if (index === scale.count - 1) {
return gantt.date.Date(
scale.trace_x[index].valueOf()
+ (gantt._max_date - scale.trace_x[index])
* (x - scale.left[index])
/ scale.width[index]);
}
}
return gantt.date.Date(
scale.trace_x[index].valueOf()
+ (scale.trace_x[index + 1] - scale.trace_x[index])
* (x - scale.left[index])
/ scale.width[index]);
};
ysy.view.bars.registerRenderer("task", function (task, next) {
var $div = $(next().call(this, task, next));
if (this.hasChild(task.id) || $div.hasClass("parent")) {
$div.addClass("gantt_parent_task-subtype");
var $ticks = $("<div class='gantt_task_ticks'></div>");
var width = $div.width();
if (width < 20) {
$ticks.css({borderLeftWidth: width / 2, borderRightWidth: width / 2});
}
$div.append($ticks);
}
if (task.latest_due) {
var stop_x = this.posFromDate(task.widget.model.latest_due);
var issue_x = this.posFromDate(task.start_date);
var pos_x = stop_x - issue_x;
var $preStop = $(ysy.view.templates.endBlocker.replace("{{pos_x}}", pos_x.toString()));
$div.prepend($preStop);
}
if (task.soonest_start) {
var stop_x = this.posFromDate(task.widget.model.soonest_start);
var issue_x = this.posFromDate(task.start_date);
var pos_x = stop_x - issue_x;
var $preStop = $(ysy.view.templates.preBlocker.replace("{{pos_x}}", pos_x.toString()));
$div.prepend($preStop);
}
return $div[0];
});
// var progressRenderer = gantt._render_task_progress;
// gantt._render_task_progress = function (task, element, maxWidth) {
// var width = progressRenderer.call(this, task, element, maxWidth);
// if (task.type !== "project") return width;
// var pos = gantt.posFromDate(task.start_date);
// var todayPos = gantt.posFromDate(moment());
// if (task.progress < 1 && pos + width < todayPos) {
// element.className += " gantt-project-overdue";
// }
// return width;
// };
gantt._default_task_date = function (item, parent_id) {
return moment();
};
gantt.attachEvent("onScrollTo", function (x, y) {
var renderer = gantt._backgroundRenderer;
var needRender = renderer.isScrolledOut(x, y);
if (needRender) {
//ysy.log.debug("render_one_canvas on [" + x + "," + y + "]", "scrollRender");
renderer.render_items();
}
});
var ganttOffsetTop;
$(document).add("#content").on("scroll", function (e) {
if (!ganttOffsetTop) {
if (!gantt.$task) return;
ganttOffsetTop = $(gantt.$task).offset().top;
}
var scroll = $(this).scrollTop();
gantt.scrollTo(undefined, scroll - ganttOffsetTop);
});
gantt.showTask = function (id) {
var el = this.getTaskNode(id);
if (!el) return;
var left = Math.max(el.offsetLeft - this.config.task_scroll_offset, 0);
var top = $(el).offset().top - 200;
$(window).scrollTop(top);
this.scrollTo(left, top);
};
gantt.getScrollState = function () {
if (!this.$task || !this.$task_data) return null;
return {x: this.$task.scrollLeft, y: $(window).scrollTop()};
};
gantt._path_builder.get_endpoint = function (link) {
var types = gantt.config.links;
var from_start = false, to_start = false;
if (link.type == types.start_to_start) {
from_start = to_start = true;
} else if (link.type == types.finish_to_finish) {
from_start = to_start = false;
} else if (link.type == types.finish_to_start) {
from_start = false;
to_start = true;
} else if (link.type == types.start_to_finish) {
from_start = true;
to_start = false;
} else {
dhtmlx.assert(false, "Invalid link type");
}
var source = gantt._pull[link.source];
var target = gantt._pull[link.target];
var sourceShift = 0, targetShift = 0;
var fromMount = from_start ? source.$startMount : source.$endMount;
var toMount = to_start ? target.$startMount : target.$endMount;
if (fromMount.length > 1) {
for (var i = 0; i < fromMount.length; i++) {
if (link.id == fromMount[i]) break;
}
sourceShift = (i * 2) / (fromMount.length - 1) * 6 - 6;
}
if (toMount.length > 1) {
for (i = 0; i < toMount.length; i++) {
if (link.id == toMount[i]) break;
}
targetShift = (i * 2) / (toMount.length - 1) * 6 - 6;
}
var from = gantt._get_task_visible_pos(gantt._pull[link.source], from_start);
var to = gantt._get_task_visible_pos(gantt._pull[link.target], to_start);
return {
x: from.x,
e_x: to.x,
y: from.y + sourceShift,
e_y: to.y + targetShift
};
};
gantt._sync_links = function () {
for (var id in this._pull) {
if (!this._pull.hasOwnProperty(id)) continue;
var task = this._pull[id];
task.$source = [];
task.$target = [];
task.$startMount = [];
task.$endMount = [];
}
for (id in this._lpull) {
if (!this._lpull.hasOwnProperty(id)) continue;
var link = this._lpull[id];
var types = gantt.config.links;
if (this._pull[link.source]) {
this._pull[link.source].$source.push(id);
if (link.type == types.start_to_start || link.type == types.start_to_finish) {
this._pull[link.source].$startMount.push(id);
} else {
this._pull[link.source].$endMount.push(id);
}
}
if (this._pull[link.target]) {
this._pull[link.target].$target.push(id);
if (link.type == types.start_to_start || link.type == types.finish_to_start) {
this._pull[link.target].$startMount.push(id);
} else {
this._pull[link.target].$endMount.push(id);
}
}
}
};
gantt._has_children = function (id) {
var item = gantt._pull[id];
if (item.widget && item.widget.model && item.widget.model.needLoad) {
return true;
}
return this.getChildren(id).length > 0;
};
gantt.setParent = function (task, new_pid) {
if (ysy.settings.parentIssueDates) {
var parentTask = this._pull[new_pid];
if (parentTask && gantt._get_safe_type(parentTask.type) === "task") {
parentTask.$no_start = true;
parentTask.$no_end = true;
}
}
task.parent = new_pid;
};
gantt.attachEvent("onAfterTaskMove", function (taskId) {
var task = gantt._pull[taskId];
if (!task) return;
task._parentChanged = true;
});
$("#main").on("resize", function () {
gantt.render();
});
};

View File

@ -0,0 +1,623 @@
/* dhtml_relations.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.pro = ysy.pro || {};
ysy.pro.relations = {
patch: function () {
if (ysy.settings.fixedRelations) {
ysy.pro.relations = null;
return;
}
var patch = function () {
gantt.multiStop = function (task, start_date, end_date, previous) {
var diff;
var sumMove = 0;
if (!previous) {
previous = {
visitedLinks: [],
visitedParents: [],
alreadyMoved: []
};
// ysy.log.debug("previous created");
}
if (task.soonest_start && start_date && start_date.isBefore(task.soonest_start)) {
diff = task.soonest_start.diff(start_date, "seconds");
start_date.add(diff, "seconds");
if (end_date) end_date.add(diff, "seconds");
sumMove += diff;
ysy.log.debug("AscStop(): soonest_start task=" + task.text + " diff=" + diff, "asc");
}
if (task.latest_due && end_date && end_date.isAfter(task.latest_due)) {
diff = task.latest_due.diff(end_date, "seconds");
end_date.add(diff, "seconds");
if (start_date) start_date.add(diff, "seconds");
sumMove += diff;
ysy.log.debug("AscStop(): latest_end task=" + task.text + " diff=" + diff, "asc");
}
if (end_date) {
if (ysy.settings.milestonePush) {
var newStartDate = gantt.descStartByMilestone(task, +start_date, +end_date);
if (newStartDate) {
ysy.log.debug("AscStop(): milePush task=" + task.text + " start_date=" + newStartDate.format("YYYY-MM-DD"), "asc");
var newEndDate = gantt._working_time_helper.add_worktime(newStartDate, task.duration, "day", true);
var mileDiff = (newEndDate - end_date) / 1000;
end_date.add(mileDiff, "seconds");
if (start_date) {
mileDiff = (newStartDate - start_date) / 1000;
start_date.add(mileDiff, "seconds");
}
ysy.log.debug("task=" + task.text + " mileDiff=" + (mileDiff / 86400), "task_drag_milestone");
sumMove += mileDiff;
}
}
}
// ####################
sumMove += gantt.ascStop(task, start_date, end_date, previous);
var parentId = gantt.getParent(task.id);
var parent = gantt._pull[parentId];
if (parent && gantt._get_safe_type(parent.type) === "task") {
// if(parent.start_date.isAfter(start_date) || parent.end_date.isAfter(end_date)){
var branch = gantt._branches[parent.id];
if (branch && branch.length > 0) {
var minDate = start_date;
var maxDate = end_date;
for (var i = 0; i < branch.length; i++) {
var childId = branch[i];
var child = gantt.getTask(childId);
if (child.id === task.id) continue;
if (!minDate || minDate.isAfter(child.start_date)) {
minDate = child.start_date;
}
if (!maxDate || maxDate.isBefore(child.end_date)) {
maxDate = child.end_date;
}
}
}
var parentSumMove = gantt.multiStop(parent, moment(minDate), moment(maxDate));
if (start_date) {
start_date.add(parentSumMove, "seconds");
if (end_date) {
var new_end = gantt._working_time_helper.add_worktime(start_date, task.duration, "day", true); //< HOSEKP
end_date.add(new_end - end_date, "milliseconds");
}
} else {
end_date.add(parentSumMove, "seconds");
}
if (parentSumMove > sumMove) {
ysy.log.debug("AscStop(): parent task=" + task.text + " diff=" + parentSumMove, "asc");
sumMove = parentSumMove;
}
// }
}
return sumMove;
};
gantt.ascStop = function (task, start_date, end_date, previous) {
var shortestDiff;
var diff, sumMove = 0;
for (var i = 0; i < task.$target.length; i++) {
var lid = task.$target[i];
if (previous.visitedLinks.indexOf(lid) > -1) continue; // skip link sourcing moved parent
var link = gantt._lpull[lid];
if (link.isSimple) continue;
var targetDate;
if (link.type === "precedes" || link.type === "start_to_start") {
if (!start_date) continue;
targetDate = start_date;
} else if (link.type === "finish_to_finish" || link.type === "start_to_finish") {
if (!end_date) continue;
targetDate = end_date;
} else continue;
var source = gantt._pull[link.source];
var sourceDate = gantt.getLinkSourceDate(source, link.type);
diff = -targetDate.diff(sourceDate, "seconds") + gantt.getLinkCorrection(link.type) * 24 * 60 * 60;
if (!link.unlocked) {
diff += link.delay * 24 * 60 * 60;
if (diff <= 0) {
if (shortestDiff === undefined || shortestDiff < diff) {
shortestDiff = diff;
}
}
}
if (diff > 0) {
sumMove += diff;
ysy.log.debug("AscStop(): relDiff<0 task=" + task.text + " diff=" + diff, "asc");
if (start_date) {
start_date.add(diff, "seconds");
}
if (end_date) {
var new_end = gantt._working_time_helper.add_worktime(start_date, task.duration, "day", true); //< HOSEKP
end_date.add(new_end - end_date, "milliseconds");
// end_date.add(diff, "seconds");
}
shortestDiff = 0;
}
}
if (shortestDiff) {
sumMove += shortestDiff;
ysy.log.debug("AscStop(): shortest_diff task=" + task.text + " diff=" + shortestDiff, "asc");
if (start_date) {
start_date.add(shortestDiff, "seconds");
}
if (end_date) {
new_end = gantt._working_time_helper.add_worktime(start_date, task.duration, "day", true); //< HOSEKP
end_date.add(new_end - end_date, "milliseconds");
// end_date.add(shortestDiff, "seconds");
}
}
return sumMove;
};
/**
*
* @param task
* @param {{[old_start]:{},[old_end]:{},[fromParent]:boolean,[fromChild]:boolean,[asc]:boolean}} options
* @param previous
* @return {number}
*/
gantt.moveDesc = function (task, options, previous/*, resizing*/) {
// runs after task dates are already modified.
if (!previous) {
previous = {
visitedLinks: [],
visitedParents: [],
alreadyMovedFrom: {},
central: task,
parentsToRecalculate: []
};
previous.alreadyMovedFrom[task.id] = options.old_start;
// ysy.log.debug("previous created");
}
if (!options.old_start) {
options.old_start = previous.alreadyMovedFrom[task.id];
}
var shouldMove = gantt.shouldMoveChildren(task);
if (!options.fromChild && shouldMove.move) {
var children = gantt.moveChildren(task, $.extend({}, options, {fromParent: true}), previous);
} else if (shouldMove.milestoneMove) {
this.moveMilestoneChildren(task, {old_start: options.old_start}, previous);
}
if (shouldMove.adjust) {
if (!children) {
var branch = gantt._branches[task.id];
if (branch && branch.length !== 0) {
children = [];
for (i = 0; i < branch.length; i++) {
children.push(gantt.getTask(branch[i]));
}
}
}
if (children && children.length) {
var dates = {start_date: null, end_date: null};
for (i = 0; i < children.length; i++) {
var child = children[i];
if (dates.start_date === null || dates.start_date.isAfter(child.start_date)) {
dates.start_date = child.start_date;
}
if (dates.end_date === null || dates.end_date.isBefore(child.end_date)) {
dates.end_date = child.end_date;
}
}
task.start_date.add(dates.start_date - task.start_date, "milliseconds");
task.end_date.add(dates.end_date - task.end_date, "milliseconds");
}
}
var start_date = +task.start_date;
var end_date = +task.end_date;
if (!options.asc) {
/** DESCENDANTS */
for (var i = 0; i < task.$source.length; i++) {
var lid = task.$source[i];
var link = gantt._lpull[lid];
if (previous.visitedLinks.indexOf(lid) > -1) continue;
previous.visitedLinks.push(lid);
if (link.isSimple) continue;
var desc = gantt._pull[link.target];
// var isTargetingEnd = link.type === "finish_to_finish" || link.type === "start_to_finish";
if (!link.unlocked) {
var descDates = this.getDescDates(link, start_date, end_date);
// var diff = gantt.getFreeDelay(link, desc, start_date, end_date);
if (descDates.end_date) {
debugger
} else {
gantt.safeMoveToStartDate(desc, descDates.start_date, previous);
}
//ysy.log.debug("pushing "+desc.text+" by freeDelay "+diff);
gantt.moveDesc(desc, {}, previous);
} else {
descDates = this.getDescDates(link, start_date, end_date);
// var descDiff = gantt.getFreeDelay(link, desc, start_date, end_date);
// if (descDiff <= 0) continue;
// console.log("OVER");
if (descDates.start_date && descDates.start_date.isAfter(desc.start_date)) {
gantt.safeMoveToStartDate(desc, descDates.start_date, previous);
}
if (descDates.end_date && descDates.end_date.isAfter(desc.end_date)) {
debugger;
gantt.safeMoveToStartDate(desc, descDates.start_date, previous);
}
// ysy.log.debug("desc=" + desc.text +" diff="+diff+" descDiff="+descDiff);
gantt.moveDesc(desc, {}, previous);
}
}
} else {
/** ASCENDANTS */
for (i = 0; i < task.$target.length; i++) {
lid = task.$target[i];
link = gantt._lpull[lid];
if (previous.visitedLinks.indexOf(lid) > -1) continue;
previous.visitedLinks.push(lid);
if (link.isSimple) continue;
var asc = gantt._pull[link.source];
// var isTargetingEnd = link.type === "finish_to_finish" || link.type === "start_to_finish";
if (!link.unlocked) {
var ascDates = this.getAscDates(link, start_date, end_date);
// var diff = gantt.getFreeDelay(link, desc, start_date, end_date);
if (ascDates.end_date) {
debugger
} else {
gantt.safeMoveToStartDate(asc, ascDates.start_date, previous);
}
//ysy.log.debug("pushing "+desc.text+" by freeDelay "+diff);
gantt.moveDesc(asc, {asc: true}, previous);
} else {
var ascDiff = gantt.getFreeDelay(link, task, asc.start_date, asc.end_date);
if (ascDiff <= 0) continue;
// ysy.log.debug("desc=" + desc.text +" diff="+diff+" descDiff="+descDiff);
gantt.moveDesc(asc, {asc: true}, previous);
}
}
}
if (!options.fromParent) {
gantt.moveParent(task, {}, previous);
}
};
gantt.moveChildren = function (task, options, previous) {
var branch = gantt._branches[task.id];
if (!branch || branch.length === 0) return null;
var children = [];
for (var i = 0; i < branch.length; i++) {
var childId = branch[i];
//if(gantt.isTaskVisible(childId)){continue;}
var child = gantt.getTask(childId);
if (!child._parent_offset) {
child._parent_offset = gantt._working_time_helper.get_work_units_between(options.old_start, child.start_date, "day");
}
children.push(child);
if (previous.alreadyMovedFrom[childId]) continue;
var childOldStart = previous.alreadyMovedFrom[childId] || child.start_date;
var childNewStart = gantt._working_time_helper.add_worktime(task.start_date, child._parent_offset, "day", false);
gantt.safeMoveToStartDate(child, childNewStart, previous);
// child.start_date.add(childNewStart - child.start_date, "milliseconds");
child._changed = gantt.config.drag_mode.move;
gantt.moveDesc(child, {old_start: childOldStart, fromParent: options.fromParent}, previous);
gantt.refreshTask(childId);
}
// gantt._update_parents(task.id);
return children;
};
gantt.shouldMoveChildren = function (task) {
if (task.type === "milestone") return {milestoneMove: true};
if (gantt._get_safe_type(task.type) === "task" && ysy.settings.parentIssueDates) return {
move: true,
adjust: true
};
if (task.$open && gantt.isTaskVisible(task.id)) return {move: true};
return false;
};
gantt.safeMoveToStartDate = function (task, start_date, previous) {
if (task.start_date.isSame(start_date)) {
previous.alreadyMovedFrom[task.id] = moment(start_date);
return 0;
}
previous.alreadyMovedFrom[task.id] = moment(task.start_date);
if (task.start_date.isAfter(start_date)) {
// moved forward
var end_date = gantt._working_time_helper.add_worktime(start_date, task.duration, "day", true);
task.start_date.add(start_date - task.start_date, "milliseconds");
task.end_date.add(end_date - task.end_date, "milliseconds");
task._changed = gantt.config.drag_mode.move;
gantt.refreshTask(task.id);
return 0;
} else {
// moved backward
end_date = gantt._working_time_helper.add_worktime(start_date, task.duration, "day", true);
task.start_date.add(start_date - task.start_date, "milliseconds");
task.end_date.add(end_date - task.end_date, "milliseconds");
task._changed = gantt.config.drag_mode.move;
gantt.refreshTask(task.id);
var ascDiff = gantt.ascStop(task, task.start_date, task.end_date, previous);
if (ascDiff !== 0) {
// ysy.log.debug("diff=" + diff + " ascStopDiff=" + ascDiff);
return ascDiff;
}
}
};
gantt.moveMilestoneChildren = function (milestone, options, previous) {
var branch = gantt._branches[milestone.id];
if (!branch || branch.length === 0) return 0;
// ysy.log.debug("Shift children of \"" + milestone.text + "\" by " + shift + " seconds", "parent");
ysy.log.debug("moveChildren(): of \"" + milestone.text + "\"(" + milestone.end_date.toISOString() + ") from " + options.old_start.toISOString(), "task_drag");
// var milestoneEndDate=moment(milestone.end_date).add(shift,"seconds");
// milestoneEndDate._isEndDate=true;
for (var i = 0; i < branch.length; i++) {
var childId = branch[i];
var child = gantt.getTask(childId);
if (child.end_date.isAfter(milestone.end_date)) {
// var shift = milestone.end_date.diff(child.end_date, "seconds");
// child.start_date.add(shift, 'seconds');
var startDateValue = +child.start_date;
// child.end_date = moment(milestone.end_date);
// child.end_date._isEndDate = true;
child.end_date.add(milestone.end_date - child.end_date, "milliseconds");
var childNewStart = gantt._working_time_helper.add_worktime(child.end_date, -child.duration, "day", false);
var childOldStart = moment(child.start_date);
child.start_date.add(childNewStart - child.start_date, "milliseconds");
// ysy.log.debug(child.start_date.toISOString()+" "+child.end_date.toISOString());
child._changed = gantt.config.drag_mode.move;
gantt.refreshTask(child.id);
previous.alreadyMovedFrom[child.id] = previous.alreadyMovedFrom[child.id] || childOldStart;
gantt.moveDesc(child, {old_date: moment(startDateValue), asc: true}, previous);
}
}
return 0;
};
gantt.moveParent = function (child, option, previous) {
if (!ysy.settings.parentIssueDates) return;
var parentId = gantt.getParent(child.id);
if (previous.central.id === parentId) {
parent = previous.central;
} else {
var parent = gantt._pull[parentId];
}
if (gantt._get_safe_type(parent.type) !== "task") return 0;
// previous.visitedParents.push(parent.id);
// if (parent.end_date.isBefore(child.end_date)) {
// parent.end_date.add(child.end_date - parent.end_date, "milliseconds");
// parent._changed = gantt.config.drag_mode.move;
// gantt.refreshTask(parent.id);
// // if(option.skipParent)
// }
gantt.moveDesc(parent, {fromChild: true/*old_start:moment(parent.start_date)*/}, previous);
};
gantt.startByMilestone = function (task, end_date) {
var issue = task.widget && task.widget.model;
if (!issue) return 0;
var milestone = ysy.data.milestones.getByID(issue.fixed_version_id);
if (!milestone) return 0;
var ganttMilestone = gantt._pull[milestone.getID()];
if (ganttMilestone) {
var milestoneDate = ganttMilestone.end_date;
} else {
milestoneDate = milestone.start_date;
}
if (milestoneDate.isBefore(end_date)) {
ysy.log.debug("milestoneStop() for " + task.text +
" at " + milestone.start_date.format("YYYY-MM-DD"), "task_drag_milestone");
return gantt._working_time_helper.toMoment(
gantt._working_time_helper.add_worktime(milestoneDate, -task.duration, "day", false)
);
}
return null;
};
gantt.descStartByMilestone = function (task, start_date, end_date) {
var newStartDate = gantt.startByMilestone(task, end_date);
// var start_date = +task.start_date / 1000 + diff;
// var end_date = +task.end_date / 1000 + diff;
for (var i = 0; i < task.$source.length; i++) {
var lid = task.$source[i];
var link = gantt._lpull[lid];
if (link.isSimple) continue;
var desc = gantt._pull[link.target];
var descDiff = gantt.getFreeDelay(link, desc, start_date, end_date);
if (descDiff <= 0) continue;
var descEndDate = gantt._working_time_helper.add_worktime(desc.start_date + descDiff * 1000, desc.duration, "day", true);
var correctedDescStartDate = gantt.descStartByMilestone(desc, desc.start_date + descDiff * 1000, descEndDate);
if (!correctedDescStartDate) continue;
switch (link.type) {
case "precedes":
if (!link.unlocked) {
correctedDescStartDate.subtract(link.delay, "days");
}
var correctedStartDate = gantt._working_time_helper.add_worktime(correctedDescStartDate, -task.duration, "day", false);
break;
default:
debugger;
}
if (!newStartDate || (correctedStartDate && correctedStartDate.isBefore(newStartDate))) {
newStartDate = correctedStartDate;
}
}
var childrenStartDate = gantt.childrenStartByMilestone(task, (newStartDate ? newStartDate : start_date) - task.start_date);
if (childrenStartDate) {
newStartDate = childrenStartDate;
}
if (newStartDate) {
ysy.log.debug("milestoneDescStop(): task " + task.text + " start set to " + newStartDate.format("YYYY-MM-DD"), "task_drag_milestone");
}
return newStartDate;
};
gantt.childrenStartByMilestone = function (task, diff) {
if (task.type === "milestone") return null;
var branch = gantt._branches[task.id];
if (!branch || branch.length === 0) return 0;
var newStartDate;
for (var i = 0; i < branch.length; i++) {
var childId = branch[i];
//if(gantt.isTaskVisible(childId)){continue;}
var child = gantt.getTask(childId);
var childEndDate = gantt._working_time_helper.add_worktime(child.start_date + diff, child.duration, "day", true);
var correctedStartDate = gantt.descStartByMilestone(child, child.start_date + diff, childEndDate);
if (!newStartDate || (correctedStartDate && correctedStartDate.isBefore(newStartDate))) {
newStartDate = correctedStartDate;
}
}
if (newStartDate) {
ysy.log.debug("milestoneChildrenStop(): \"" + task.text + "\" start_date set to " + newStartDate.format("YYYY-MM-DD"), "task_drag");
}
return newStartDate;
};
gantt.getLinkSourceDate = function (source, type) {
if (type === "precedes") return source.end_date;
if (type === "finish_to_finish") return source.end_date;
if (type === "start_to_start") return source.start_date;
if (type === "start_to_finish") return source.start_date;
return null;
};
gantt.getLinkTargetDate = function (target, type) {
if (type === "precedes") return target.start_date;
if (type === "finish_to_finish") return target.end_date;
if (type === "start_to_start") return target.start_date;
if (type === "start_to_finish") return target.end_date;
return null;
};
gantt.getLinkCorrection = function (type) {
if (type === "precedes") return 1;
if (type === "start_to_finish") return -1;
return 0;
};
/**
* How much can be distance between two task shortened
* @param link - gantt link
* @param desc - gantt task
* @param {number} ascStartDate - number of milliseconds since epoch
* @param {number} ascEndDate - number of milliseconds since epoch
* @return {number} - number of seconds
*/
gantt.getFreeDelay = function (link, desc, ascStartDate, ascEndDate) {
if (!desc) desc = gantt._pull[link.target];
var sourceDate;
var daysToSeconds = 60 * 60 * 24;
if (!ascStartDate) {
var asc = gantt._pull[link.source];
ascStartDate = +asc.start_date;
ascEndDate = +asc.end_date;
}
if (link.type === "precedes" || link.type === "finish_to_finish") {
if (!ascEndDate) return 0;
sourceDate = ascEndDate;
} else if (link.type === "start_to_finish" || link.type === "start_to_start") {
if (!ascStartDate) return 0;
sourceDate = ascStartDate;
} else return 0;
var targetDate = +gantt.getLinkTargetDate(desc, link.type);
var correction = gantt.getLinkCorrection(link.type);
var delay = (targetDate - sourceDate) / daysToSeconds / 1000;
return ((link.unlocked ? 0 : link.delay) + correction - delay) * daysToSeconds;
};
/**
*
* @param {{type:String,delay:int,source:int,target:int,unlocked:boolean}} link
* @param {int} ascStartDate
* @param {int} ascEndDate
* @return {{[start_date]:Object,[end_date]:Object}}
*/
gantt.getDescDates = function (link, ascStartDate, ascEndDate) {
//if (!desc) desc = gantt._pull[link.target];
var sourceDate;
if (!ascStartDate) {
var asc = gantt._pull[link.source];
ascStartDate = +asc.start_date;
ascEndDate = +asc.end_date;
}
if (link.type === "precedes" || link.type === "finish_to_finish") {
if (!ascEndDate) return {};
sourceDate = ascEndDate;
} else if (link.type === "start_to_finish" || link.type === "start_to_start") {
if (!ascStartDate) return {};
sourceDate = ascStartDate;
} else return {};
var correction = gantt.getLinkCorrection(link.type);
if (link.type === "finish_to_finish" || link.type === "start_to_finish") {
var descEndDate = moment(sourceDate).add((link.unlocked ? 0 : link.delay) + correction, "days");
descEndDate._isEndDate = true;
var descSafeEnd = gantt._working_time_helper.get_closest_worktime({
dir: "future",
date: descEndDate
});
return {end_date: descSafeEnd};
} else {
var descStartDate = moment(sourceDate).add((link.unlocked ? 0 : link.delay) + correction, "days");
var descSafeStart = gantt._working_time_helper.get_closest_worktime({
dir: "future",
date: descStartDate
});
return {start_date: descSafeStart};
}
};
/**
*
* @param {{type:String,delay:int,source:int,target:int,unlocked:boolean}} link
* @param {int} descStartDate
* @param {int} descEndDate
* @return {{[start_date]:moment,[end_date]:moment}}
*/
gantt.getAscDates = function (link, descStartDate, descEndDate) {
var targetDate;
if (!descStartDate) {
var desc = gantt._pull[link.target];
descStartDate = +desc.start_date;
descEndDate = +desc.end_date;
}
if (link.type === "start_to_finish" || link.type === "finish_to_finish") {
if (!descEndDate) return {};
targetDate = descEndDate;
} else if (link.type === "precedes" || link.type === "start_to_start") {
if (!descStartDate) return {};
targetDate = descStartDate;
} else return {};
var correction = gantt.getLinkCorrection(link.type);
if (link.type === "finish_to_finish" || link.type === "start_to_finish") {
var ascEndDate = moment(targetDate).subtract((link.unlocked ? 0 : link.delay) + correction, "days");
ascEndDate._isEndDate = true;
var ascSafeEnd = gantt._working_time_helper.get_closest_worktime({
dir: "past",
date: ascEndDate
});
return {end_date: ascSafeEnd};
} else {
var ascStartDate = moment(targetDate).subtract((link.unlocked ? 0 : link.delay) + correction, "days");
var ascSafeStart = gantt._working_time_helper.get_closest_worktime({
dir: "past",
date: ascStartDate
});
return {start_date: ascSafeStart};
}
};
//##################################################################################################################
gantt.attachEvent("onLinkClick", function (id, mouseEvent) {
// if (!gantt.config.drag_links) return;
ysy.log.debug("LinkClick on " + id, "link_config");
var link = gantt.getLink(id);
if (gantt._is_readonly(link)) return;
var source = gantt._pull[link.source];
if (!source) return;
var target = gantt._pull[link.target];
if (!target) return;
if (source.readonly && target.readonly) return;
var relation = link.widget.model;
var isUnlocked = relation.unlocked;
relation.set({unlocked: !isUnlocked, delay: isUnlocked ? relation.getActDelay() : 0});
return false;
});
gantt.attachEvent("onContextMenu", function (taskId, id /*, mouseEvent*/) {
if (taskId) return;
if (!gantt.config.drag_links) return;
ysy.log.debug("LinkClick on " + id, "link_config");
var link = gantt.getLink(id);
if (gantt._is_readonly(link)) return;
var source = gantt._pull[link.source];
if (!source) return;
var target = gantt._pull[link.target];
if (!target) return;
if (source.readonly && target.readonly) return;
var linkConfigWidget = new ysy.view.LinkPopup().init(link.widget.model, link);
linkConfigWidget.$target = $("#ajax-modal");//$dialog;
linkConfigWidget.repaint();
showModal("ajax-modal", "auto");
});
};
patch();
}
};

View File

@ -0,0 +1,703 @@
/* dhtml_rewrite.js */
/* global ysy */
/**
* @external Moment
*/
// noinspection JSCommentMatchesSignature
/**
* @function moment
* @param {*} [arg1]
* @return {Moment}
*/
window.ysy = window.ysy || {};
ysy.view = ysy.view || {};
ysy.view.applyGanttRewritePatch = function () {
ysy.view.initNonworkingDays = function () {
var work_helper = gantt._working_time_helper;
work_helper.defHours = ysy.settings.hoursPerDay;
var i;
// Now we specify working days
var nonWorking = ysy.settings.nonWorkingWeekDays;
for (i in nonWorking) {
work_helper.set_time({day: nonWorking[i] % 7, hours: false});
}
work_helper._cache = {};
};
gantt._working_time_helper = {
defHours: 8,
timeformat: "YYYY-MM-DD",
days: {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true},
dates: {},
_cache: {},
oneDaySeconds: 1000 * 60 * 60 * 24,
oneHourSeconds: 1000 * 60 * 60,
//formatDate: function (date) {
// if (date._isAMomentObject) {
// return date.format(this.timeformat);
// }
// return moment(date).format(this.timeformat);
//},
toMoment: function (date) {
if (date._isAMomentObject) {
return date;
}
return moment(date);
},
set_time: function (settings) {
var hours = settings.hours !== undefined ? settings.hours : true;
if (settings.day !== undefined) {
this.days[settings.day] = hours;
} else if (settings.date !== undefined) {
this.dates[+settings.date] = hours;
}
},
is_weekend: function (date) {
date = this.toMoment(date);
return !this.days[date.day()];
},
is_working_day: function (date) {
date = this.toMoment(date);
if (!this.days[date.day()]) {
return false;//week day
}
var val = this.get_working_hours(date);
return val > 0;
},
get_working_hours: function (date) {
//return 8;
//console.log("get_working_hours: "+date.toString());
//var t = this._timestamp({date: date});
date = this.toMoment(date);
var t = +date;
var hours = true;
//date = moment(date);
if (this.dates[t] !== undefined) {
hours = this.dates[t];//custom day
} else if (this.days[date.day()] !== undefined) {
hours = this.days[date.day()];//week day
}
if (hours === true) {
return this.defHours;
} else if (hours) {
return hours;
}
return 0;
},
is_working_unit: function (date, unit, order) {
if (!gantt.config.work_time)
return true;
return this.is_working_day(date);
},
save_working_unit: function (first_date, end_date, unit) {
var weekID = first_date.isoWeek();
var workDays = this.get_work_units_between(first_date, end_date, "day");
var workHours = this.get_work_units_between(first_date, end_date, "hour");
this.weeks[weekID] = {days: workDays, hours: workHours};
},
_work_times_between: function (from, to) {
var spanID = from.valueOf() + "_" + to.valueOf();
if (this._cache[spanID]) {
this._cache[spanID].cached = true;
return this._cache[spanID];
}
if (from.isBefore(to)) {
var ret = this._work_times_forward(from, to);
} else {
ret = this._work_times_backward(from, to);
}
this._cache[spanID] = ret;
return ret;
},
_work_times_forward: function (from, to) {
var sumHours = 0;
var sumDays = 0;
if ((+from % this.oneHourSeconds) !== 0 || from.hours()!==0) {
var mover = moment(from).startOf("day");
var first = true;
} else {
mover = from;
}
var count = 0;
while (mover.isBefore(to)) {
if ((count++) > 3000) {
ysy.log.error("_work_times_forward: Probably task with start_date=" + from.format("YYYY-MM-DD")
+ " and end_date=" + to.format("YYYY-MM-DD") + " is too long");
break;
}
var hours = this.get_working_hours(mover);
if (hours > 0) {
if (first) {
var rest = 1 - (from - mover) / this.oneDaySeconds;
sumDays += rest;
sumHours += hours * rest;
} else {
sumDays++;
sumHours += hours;
}
}
first = false;
mover.add(1, "days");
}
if (hours > 0 && mover.isAfter(to)) {
rest = (mover - to) / this.oneDaySeconds;
sumDays -= rest;
sumHours -= hours * rest;
}
return {days: sumDays, hours: sumHours};
},
_work_times_backward: function (from, to) {
var sumHours = 0;
var sumDays = 0;
if ((+from % this.oneHourSeconds) !== 0 || from.hours()!==0) {
var mover = moment(from).startOf("day");
var first = true;
mover.add(1, "day");
} else {
mover = from;
}
var count = 0;
while (mover.isAfter(to)) {
mover.subtract(1, "days");
if ((count++) > 3000) {
ysy.log.error("_work_times_backward: Probably task with start_date=" + to.format("YYYY-MM-DD")
+ " and end_date=" + from.format("YYYY-MM-DD") + " is too long");
break;
}
var hours = this.get_working_hours(mover);
if (hours > 0) {
if (first) {
var rest = (from - mover) / this.oneDaySeconds;
sumDays += rest;
sumHours += hours * rest;
} else {
sumDays++;
sumHours += hours;
}
}
first = false;
}
if (hours > 0 && mover.isBefore(to)) {
var rest2 = (to - mover) / this.oneDaySeconds;
sumDays -= rest2;
sumHours -= hours * rest2;
}
//ysy.log.debug(mover.format() + " hours=" + hours + " rest=" + rest + " rest2=" + rest2);
return {days: -1 * sumDays, hours: -1 * sumHours};
},
get_work_units_between: function (from, to, unit) {
if (!unit) {
ysy.log.error("missing unit");
return 0;
}
var safeFrom = moment(from);
if (to._isEndDate) {
var safeTo = moment(to).add(1, "days");
}else{
safeTo = moment(to)
}
if (from._isEndDate) {
safeFrom = safeFrom.add(1, "days");
}
var workSums = this._work_times_between(safeFrom, safeTo);
ysy.log.debug("get_work_units_between: " + this.toMoment(from).format("DD.MM.YYYY") + "(" + from._isEndDate + ") " + this.toMoment(to).format("DD.MM.YYYY") + "(" + to._isEndDate + ") " + unit + " " + (workSums.cached ? "(cached)" : ""), "date_helper");
if (unit === "day") {
return workSums.days;
} else if (unit === "all") {
return workSums;
} else {
return workSums.hours;
}
},
is_work_units_between: function (from, to, unit) {
if (!unit) {
return false;
}
return this.get_work_units_between(from, to, unit) > 0;
},
/**
*
* @param {Moment|Date} from
* @param {boolean} from._isEndDate
* @param {int} duration
* @param {string} unit
* @param {boolean} toIsEndDate
* @return {Moment|Date}
*/
add_worktime: function (from, duration, unit, toIsEndDate) {
var hours;
ysy.log.debug("add_worktime: " + from.toString() + " " + duration + " " + unit, "date_helper");
if (!unit) {
throw "Missing unit";
} else {
unit = unit + "s";
}
var added = 0;
var safeFrom = moment(from);
if (from._isEndDate) {
safeFrom.add(1, "days");
}
if ((+from % this.oneHourSeconds) !== 0 || safeFrom.hours()!==0) {
var mover = moment(safeFrom).startOf("day");
var diff = safeFrom - mover;
var first = true;
} else {
mover = safeFrom;
}
//if (!gantt.config.work_time||unit==="weeks") {
// console.log(mover.format("YYYY-MM-DD HH:mm")+" mover before");
if (gantt.config.work_time && (unit === "days" || unit === "hours")) {
var count = 0;
if (duration === 0) {
while (true) {
if (count++ > 3000) {
ysy.log.error("_add_worktime: Probably task with start_date=" + moment(from).format("YYYY-MM-DD")
+ " and duration " + duration + " is too long");
break;
}
hours = this.get_working_hours(mover);
if (hours) {
if (first) {
mover.add(diff, "milliseconds");
}
break;
}
first = false;
mover.add(1, "days");
}
} else if (duration > 0) {
while (added < duration) {
if (count++ > 3000) {
ysy.log.error("_add_worktime: Probably task with start_date=" + moment(from).format("YYYY-MM-DD")
+ " and duration " + duration + " is too long");
break;
}
hours = this.get_working_hours(mover);
if (hours > 0) {
var rest = 1;
if (first) {
rest = 1 - diff / this.oneDaySeconds;
}
if (unit === "hours") {
added += rest * hours;
} else {
added += rest;
}
}
first = false;
mover.add(1, "days");
}
if (hours && added > duration) {
mover.subtract((added - duration) * (unit === "hours" ? 3600 : 3600 * 24), "seconds");
}
} else {
while (added < -duration) {
if (count++ > 3000) {
ysy.log.error("_add_worktime: Probably task with end_date=" + moment(from).format("YYYY-MM-DD")
+ " and duration " + duration + " is too long");
break;
}
if (!first || !diff) {
mover.add(-1, "days");
}
hours = this.get_working_hours(mover);
if (hours > 0) {
rest = 1;
if (first) {
rest = diff / this.oneDaySeconds;
}
if (unit === "hours") {
added += rest * hours;
} else {
added += rest;
}
// console.log(mover.format("YYYY-MM-DD HH:mm")+" moved rest="+rest+" added="+added);
}
first = false;
}
if (hours && added > -duration) {
mover.add((added + duration) * (unit === "hours" ? 3600 : 3600 * 24), "seconds");
}
}
} else {
mover.add(duration, unit);
}
// console.log(mover.format("YYYY-MM-DD HH:mm")+" mover after");
if (toIsEndDate || !from._isEndDate && toIsEndDate === undefined) {
mover.add(-1, "days");
mover._isEndDate = true;
}
// console.log(mover.format("YYYY-MM-DD HH:mm")+" mover endDated");
if (moment.isMoment(from)) {
return mover;
}
return mover.toDate();
},
round_date: function (date, direction) {
ysy.log.debug("round_date: " + date.toString(), "date_helper");
if (date._isAMomentObject) {
var momentDate = date;
} else {
momentDate = moment(date);
}
momentDate.add(12, "hours").startOf("day");
var count = 0;
if (gantt.config.work_time) {
if (direction === 'past') {
while (!this.is_working_day(momentDate) && (count++) < 1000) {
momentDate.subtract(1, "days");
}
} else {
while (!this.is_working_day(momentDate) && (count++) < 1000) {
momentDate.add(1, "days");
}
}
}
if (!date._isAMomentObject) {
date.setTime(momentDate.valueOf());
}
//end.add(12,"hours").startOf("day");
},
/**
* @param {String} settings.dir
* @param {Moment|int} settings.date
* @param {String} [settings.unit]
* @param {int} [settings.length] - minimal size of working span
* @return {*}
*/
get_closest_worktime: function (settings) {
ysy.log.debug("get_closest_worktime: " + settings.date.toString(), "date_helper");
var isMoment = moment.isMoment(settings.date);
var unit = settings.unit || "day";
var dayStart = moment(settings.date).startOf(unit);
var diff = settings.date - dayStart; // in milliseconds
var goFuture = settings.dir === 'any' || settings.dir === 'future',
goPast = settings.dir === 'any' || settings.dir === 'past';
if (!settings.length) {
if (this.is_working_day(dayStart)) {
dayStart.add(diff, "milliseconds");
if (isMoment) return dayStart;
return dayStart.toDate();
}
}
if (goPast) {
var past_target = moment(dayStart);
if (settings.length) {
past_target.add(settings.length, "days");
}
}
if (goFuture) {
var future_target = dayStart;
if (diff !== 0) {
future_target.add(1, unit);
}
}
if (goPast) {
// ysy.log.debug("checking past " + past_target.format("YYYY-MM-DD"));
if (this.is_working_day(past_target)) {
if (!settings.length) {
past_target.add(diff, "milliseconds");
if (isMoment) return past_target;
return past_target.toDate();
} else {
past_target.subtract(1, "days");
if (this.is_working_day(past_target)) {
past_target.add(diff, "milliseconds");
if (isMoment) return past_target;
return past_target.toDate();
}
}
}
past_target.add(-1, "days");
}
//will seek closest working hour in future or in past, one step in both direction per iteration
for (var count = 0; count < 3000; count++) { //be extra sure we won't fall into infinite loop, 3k seems big enough
if (goPast) {
// ysy.log.debug("checking past " + past_target.format("YYYY-MM-DD"));
if (this.is_working_day(past_target)) {
if (isMoment) return past_target;
return past_target.toDate();
}
past_target.add(-1, "days");
}
if (goFuture) {
// ysy.log.debug("checking future " + future_target.format("YYYY-MM-DD"));
if (this.is_working_day(future_target)) {
if (isMoment) return future_target;
return future_target.toDate();
}
future_target.add(1, "days");
}
}
dhtmlx.assert(false, "Invalid working time check");
return false;
}
};
//#######################################################################
gantt.date = {
now: function () {
return moment();
},
Date: function (date, isEndDate) {
if (!date) {
//return moment();
return new Date();
}
if (date._isAMomentObject/*||!isNaN(date)*/) {
var ndate = moment(date);
if (isEndDate === undefined) {
isEndDate = date._isEndDate;
}
} else {
//ysy.log.warning("date created as new Date(), not as moment()");
ndate = moment(date).toDate();
}
ndate._isEndDate = isEndDate;
return ndate;
},
toMoment: function (date) {
if (!date) {
ysy.log.error("No date to convert to Moment");
return;
}
if (date._isAMomentObject) {
return date;
}
return moment(date);
},
fromMoment: function (date, momentDate) {
if (date._isAMomentObject) {
return date;
}
date.setTime(momentDate.valueOf());
return date;
},
init: function () {
return;
var s = gantt.locale.date.month_short;
var t = gantt.locale.date.month_short_hash = {};
for (var i = 0; i < s.length; i++)
t[s[i]] = i;
var s = gantt.locale.date.month_full;
var t = gantt.locale.date.month_full_hash = {};
for (var i = 0; i < s.length; i++)
t[s[i]] = i;
},
_startOf: function (date, unit) {
var momentDate = this.toMoment(date);
momentDate.startOf(unit);
return this.fromMoment(date, momentDate);
},
date_part: function (date) {
return this._startOf(date, "day");
},
time_part: function (date) {
alert("Forbidden function");
return (date.valueOf() / 1000 - date.getTimezoneOffset() * 60) % 86400;
},
week_start: function (date) {
return this._startOf(date, "isoweek");
},
month_start: function (date) {
return this._startOf(date, "month");
},
quarter_start: function (date) {
return this._startOf(date, "quarter");
},
year_start: function (date) {
return this._startOf(date, "year");
},
day_start: function (date) {
return this._startOf(date, "day");
},
hour_start: function (date) {
alert("Forbidden function");
if (date.getMinutes())
date.setMinutes(0);
this.minute_start(date);
return date;
},
minute_start: function (date) {
alert("Forbidden function");
if (date.getSeconds())
date.setSeconds(0);
if (date.getMilliseconds())
date.setMilliseconds(0);
return date;
},
/*_add_days: function (date, inc) {
var ndate = new Date(date.valueOf());
ndate.setDate(ndate.getDate() + inc);
if (inc >= 0 && (!date.getHours() && ndate.getHours()) && //shift to yesterday on dst
(ndate.getDate() < date.getDate() || ndate.getMonth() < date.getMonth() || ndate.getFullYear() < date.getFullYear()))
ndate.setTime(ndate.getTime() + 60 * 60 * 1000 * (24 - ndate.getHours()));
return ndate;
},*/
add: function (date, inc, mode) {
var momentDate = this.toMoment(date);
momentDate.add(inc, mode + "s");
return momentDate.toDate();
},
to_fixed: function (num) {
if (num < 10)
return "0" + num;
return num;
},
copy: function (date) {
var momentDate = moment(date);
if (date._isAMomentObject) {
return momentDate;
}
return momentDate.toDate();
//return new Date(date.valueOf());
},
date_to_str: function (format, utc) {
ysy.log.debug("date_to_str " + format, "date_format");
format = format.replace(/%[a-zA-Z]/g, function (a) {
switch (a) {
case "%d":
return "\"+gantt.date.to_fixed(date.getDate())+\"";
case "%m":
return "\"+gantt.date.to_fixed((date.getMonth()+1))+\"";
case "%j":
return "\"+date.getDate()+\"";
case "%n":
return "\"+(date.getMonth()+1)+\"";
case "%y":
return "\"+gantt.date.to_fixed(date.getFullYear()%100)+\"";
case "%Y":
return "\"+date.getFullYear()+\"";
case "%D":
return "\"+gantt.locale.date.day_short[date.getDay()]+\"";
case "%l":
return "\"+gantt.locale.date.day_full[date.getDay()]+\"";
case "%M":
return "\"+gantt.locale.date.month_short[date.getMonth()]+\"";
case "%F":
return "\"+gantt.locale.date.month_full[date.getMonth()]+\"";
case "%h":
return "\"+gantt.date.to_fixed((date.getHours()+11)%12+1)+\"";
case "%g":
return "\"+((date.getHours()+11)%12+1)+\"";
case "%G":
return "\"+date.getHours()+\"";
case "%Q":
return "\"+((date.getMonth() / 3) + 1)+\"";
case "%H":
return "\"+gantt.date.to_fixed(date.getHours())+\"";
case "%i":
return "\"+gantt.date.to_fixed(date.getMinutes())+\"";
case "%a":
return "\"+(date.getHours()>11?\"pm\":\"am\")+\"";
case "%A":
return "\"+(date.getHours()>11?\"PM\":\"AM\")+\"";
case "%s":
return "\"+gantt.date.to_fixed(date.getSeconds())+\"";
case "%W":
return "\"+gantt.date.to_fixed(gantt.date.getISOWeek(date))+\"";
default:
return a;
}
});
if (utc)
format = format.replace(/date\.get/g, "date.getUTC");
return new Function("date", "return \"" + format + "\";");
},
str_to_date: function (format, utc) {
ysy.log.debug("str_to_date " + format, "date_format");
var splt = "var temp=date.match(/[a-zA-Z]+|[0-9]+/g);";
var mask = format.match(/%[a-zA-Z]/g);
for (var i = 0; i < mask.length; i++) {
switch (mask[i]) {
case "%j":
case "%d":
splt += "set[2]=temp[" + i + "]||1;";
break;
case "%n":
case "%m":
splt += "set[1]=(temp[" + i + "]||1)-1;";
break;
case "%y":
splt += "set[0]=temp[" + i + "]*1+(temp[" + i + "]>50?1900:2000);";
break;
case "%g":
case "%G":
case "%h":
case "%H":
splt += "set[3]=temp[" + i + "]||0;";
break;
case "%i":
splt += "set[4]=temp[" + i + "]||0;";
break;
case "%Y":
splt += "set[0]=temp[" + i + "]||0;";
break;
case "%a":
case "%A":
splt += "set[3]=set[3]%12+((temp[" + i + "]||'').toLowerCase()=='am'?0:12);";
break;
case "%s":
splt += "set[5]=temp[" + i + "]||0;";
break;
case "%M":
splt += "set[1]=gantt.locale.date.month_short_hash[temp[" + i + "]]||0;";
break;
case "%F":
splt += "set[1]=gantt.locale.date.month_full_hash[temp[" + i + "]]||0;";
break;
default:
break;
}
}
var code = "set[0],set[1],set[2],set[3],set[4],set[5]";
if (utc)
code = " Date.UTC(" + code + ")";
return new Function("date", "var set=[0,0,1,0,0,0]; " + splt + " return new Date(" + code + ");");
},
getISOWeek: function (ndate) {
if (!ndate)
return false;
var mom = this.toMoment(ndate);
return mom.isoWeek();
},
getUTCISOWeek: function (ndate) {
return this.getISOWeek(ndate);
},
convert_to_utc: function (date) {
var mom = this.toMoment(date);
mom.utc();
return this.fromMoment(date, mom);
//return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
},
parseDate: function (date, format) {
if (typeof (date) == "string") {
ysy.log.debug("parseDate() " + date + " " + format, "date_format");
if (dhtmlx.defined(format)) {
if (typeof (format) == "string")
format = dhtmlx.defined(gantt.templates[format]) ? gantt.templates[format] : gantt.date.str_to_date(format);
else
format = gantt.templates.xml_date;
}
if (date)
date = format(date);
else
date = null;
}
return this.toMoment(date);
}
};
ysy.view.initNonworkingDays();
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,127 @@
/*
@license
dhtmlxGantt v.3.2.1 Stardard
This software is covered by GPL license. You also can obtain Commercial or Enterprise license to use it in non-GPL project - please contact sales@dhtmlx.com. Usage without proper license is prohibited.
(c) Dinamenta, UAB.
*/
if(!gantt._markers)
gantt._markers = {};
gantt.config.show_markers = true;
gantt.attachEvent("onClear", function(){
gantt._markers = {};
});
gantt.attachEvent("onGanttReady", function(){
/*if(!gantt.$marker_area){ // HOSEK
var markerArea=$(".gantt_marker_area");
if(markerArea.length===0){
markerArea = document.createElement("div");
markerArea.className = "gantt_marker_area";
gantt.$task_data.appendChild(markerArea);
}else{
markerArea=markerArea[0];
}
gantt.$marker_area = markerArea;
}*/ // HOSEK
//gantt._markerRenderer = gantt._task_renderer("markers", render_marker, gantt.$marker_area, null);
gantt._markerRenderer = gantt._task_renderer({id:"markers",renderer: render_marker,container: gantt.$marker_area,filter: null});
function render_marker(marker){
if(!gantt.config.show_markers)
return false;
if(!marker.start_date)
return false;
var state = gantt.getState();
if(+marker.start_date > +state.max_date)
return;
if(+marker.end_date && +marker.end_date < +state.min_date || +marker.start_date < +state.min_date)
return;
var div = document.createElement("div");
div.setAttribute("marker_id", marker.id);
var css = "gantt_marker";
if(gantt.templates.marker_class)
css += " " + gantt.templates.marker_class(marker);
if(marker.css){
css += " " + marker.css;
}
if(marker.title){
div.title = marker.title;
}
div.className = css;
var start = gantt.posFromDate(marker.start_date);
div.style.left = start + "px";
div.style.height = Math.max(gantt._y_from_ind(gantt._order.length), 0) + "px";
if(marker.end_date){
var end = gantt.posFromDate(marker.end_date);
div.style.width = Math.max((end - start), 0) + "px";
}
if(marker.text){
div.innerHTML = "<div class='gantt_marker_content' >" + marker.text + "</div>";
}
return div;
}
});
gantt.attachEvent("onDataRender", function(){
gantt.renderMarkers();
});
gantt.getMarker = function(id){
if(!this._markers) return null;
return this._markers[id];
};
gantt.addMarker = function(marker){
marker.id = marker.id || dhtmlx.uid();
this._markers[marker.id] = marker;
return marker.id;
};
gantt.deleteMarker = function(id){
if(!this._markers || !this._markers[id])
return false;
delete this._markers[id];
return true;
};
gantt.updateMarker = function(id){
if(this._markerRenderer)
this._markerRenderer.render_item(id);
};
gantt.renderMarkers = function(){
if(!this._markers)
return false;
if(!this._markerRenderer)
return false;
var to_render = [];
for(var id in this._markers)
to_render.push(this._markers[id]);
this._markerRenderer.render_items(to_render);
return true;
};

View File

@ -0,0 +1,9 @@
/*
* = require_directory ./libs
* = require easy_gantt/utils
* = require easy_gantt/data
* = require easy_gantt/widget
* = require_directory .
* = stub easy_gantt/sample
* = stub easy_gantt/libs/moment
*/

View File

@ -0,0 +1,37 @@
window.showFlashMessage = (function (type, message, delay) {
var $content = $("#content");
$content.find(".flash").remove();
var element = document.createElement("div");
element.className = 'fixed flash ' + type;
element.style.position = 'fixed';
element.style.zIndex = '10001';
element.style.right = '5px';
element.style.top = '5px';
element.setAttribute("onclick", "closeFlashMessage($(this))");
var close = document.createElement("a");
close.className = 'icon-close close-icon';
close.setAttribute("href", "javascript:void(0)");
close.style.float = 'right';
close.style.marginLeft = '5px';
// close.setAttribute("onclick", "closeFlashMessage($(this))");
var span = document.createElement("span");
span.innerHTML = message;
element.appendChild(close);
element.appendChild(span);
$content.prepend(element);
var $element = $(element);
if (delay) {
setTimeout(function () {
window.requestAnimationFrame(function () {
closeFlashMessage($element);
});
}, delay);
}
return $element;
});
window.closeFlashMessage = (function ($element) {
$element.closest('.flash').fadeOut(500, function () {
$element.remove();
});
});

View File

@ -0,0 +1,589 @@
/* gantt_widget.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.view = ysy.view || {};
//#####################################################################
ysy.view.Gantt = function () {
ysy.view.Widget.call(this);
this.name = "GanttInitWidget";
ysy.log.message("widget Gantt created");
};
ysy.main.extender(ysy.view.Widget, ysy.view.Gantt, {
_updateChildren: function () {
if (this.children.length > 0) {
return;
}
var renderer = new ysy.view.GanttRender();
renderer.init(
ysy.data.limits,
ysy.settings.critical,
ysy.settings.zoom,
ysy.settings.sumRow
);
this.children.push(renderer);
},
_postInit: function () {
//gantt.initProjectMarker(this.model.start,this.model.end);
},
_repaintCore: function () {
if (this.$target === null) {
throw "Target is null for " + this.name;
}
if (!ysy.data.columns) {
//ysy.log.log("GanttInitWidget: columns are missing");
return true;
}
ysy.data.limits.setSilent("zoomDate", gantt.getShowDate() || moment());
ysy.view.initGantt();
this.addBaselineLayer();
gantt.init(this.$target); // REPAINT
ysy.log.debug("gantt.init()", "load");
this.tideFunctionality(); // TIDE FUNCTIONALITY
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
child.$target = this.$target; // SET CHILD TARGET
child.repaint(true); // CHILD REPAINT
}
if (!ysy.settings.controls.controls) {
$(".gantt_bars_area").addClass("no_task_controls");
}
dhtmlx.dragScroll();
},
addBaselineLayer: function () {
}
});
//##############################################################################
ysy.view.GanttRender = function () {
ysy.view.Widget.call(this);
this.name = "GanttRenderWidget";
};
ysy.main.extender(ysy.view.Widget, ysy.view.GanttRender, {
_updateChildren: function () {
if (!this.tasks) {
this.tasks = new ysy.view.GanttTasks();
this.tasks.init(
ysy.data.issues,
ysy.data.milestones,
ysy.data.projects,
ysy.settings.resource,
ysy.data.assignees,
ysy.settings.scheme
);
this.children.push(this.tasks);
}
if (!this.links) {
this.links = new ysy.view.GanttLinks();
this.links.init(
ysy.data.relations,
ysy.settings.resource
);
this.children.push(this.links);
}
if (!this.refresher) {
this.refresher = new ysy.view.GanttRefresher();
this.refresher.init(gantt);
this.children.push(this.refresher);
}
if (!this.sumRow && ysy.settings.sumRow.active) {
this.sumRow = new ysy.view.SumRow();
this.sumRow.init();
this.children.push(this.sumRow);
}
},
zoomTo: function (timespan) {
if (timespan === "year") {
$.extend(gantt.config, {
scale_unit: "year",
date_scale: "%Y",
subscales: [
]
});
} else if (timespan === "quarter") {
$.extend(gantt.config, {
scale_unit: "quarter",
date_scale: "%Q",
subscales: [
{unit: "year", step: 1, date: "%Y"}
]
});
} else if (timespan === "month") {
$.extend(gantt.config, {
scale_unit: "month",
date_scale: "%M",
subscales: [
{unit: "year", step: 1, date: "%Y"}
]
});
} else if (timespan === "week") {
$.extend(gantt.config, {
scale_unit: "week",
date_scale: "%W",
subscales: [
{unit: "month", step: 1, date: "%F %Y"}
]
});
} else if (timespan === "day") {
$.extend(gantt.config, {
scale_unit: "day",
date_scale: "%d",
subscales: [
{unit: "month", step: 1, date: "%F %Y"}
]
});
}
if (this.sumRow && ysy.settings.sumRow.active) {
gantt.config.subscales.push(this.sumRow.getSubScale(timespan));
}
},
_repaintCore: function () {
if (this.$target === null) {
throw "Target is null for " + this.name;
}
this.zoomTo(ysy.settings.zoom.zoom);
//this.addBaselineLayer();
//ysy.data.limits.setSilent("pos", gantt.getScrollState());
//var pos = ysy.data.limits.pos;
//if (pos)ysy.log.debug("scrollSave pos={x:" + pos.x + ",y:" + pos.y + "}", "scroll");
// gantt.render();
this.tideFunctionality(); // TIDE FUNCTIONALITY
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
child.repaint(true); // CHILD REPAINT
}
},
addBaselineLayer: function () {
}
});
//##############################################################################
ysy.view.GanttTasks = function () {
ysy.view.Widget.call(this);
this.name = "GanttTasksWidget";
ysy.view.ganttTasks = this;
};
ysy.main.extender(ysy.view.Widget, ysy.view.GanttTasks, {
_selectChildren: function () {
var issues = this.model.getArray();
var milestones = ysy.data.milestones.getArray();
var projects = ysy.data.projects.getArray();
return issues.concat(milestones,projects);
},
_updateChildren: function () {
var combined = this._selectChildren();
//var combined=issues.concat(milestones);
var i, model, task;
if (this.children.length === 0) {
for (i = 0; i < combined.length; i++) {
model = combined[i];
task = new ysy.view.GanttTask();
task.init(model);
task.parent = this;
task.order = i + 1;
this.children.push(task);
}
} else {
var narr = [];
var temp = {};
for (i = 0; i < this.children.length; i++) {
var child = this.children[i];
temp[child.model.getID()] = child;
}
for (i = 0; i < combined.length; i++) {
model = combined[i];
task = temp[model.getID()];
if (!task) {
task = new ysy.view.GanttTask();
task.init(model);
task.parent = this;
} else {
delete temp[model.getID()];
}
task.order = i + 1;
narr.push(task);
}
for (var key in temp) {
if (temp.hasOwnProperty(key)) {
temp[key].destroy(true);
}
}
//var narr = [];
this.children = narr;
}
ysy.log.log("-- " + this.children.length + " Children updated in " + this.name);
},
_repaintCore: function () {
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
//this.setChildTarget(child, i); // SET CHILD TARGET
child.repaint(true); // CHILD REPAINT
}
gantt._sync_links();
gantt.reconstructTree();
gantt.sort(gantt._sort && gantt._sort.criteria);
//window.initInlineEditForContainer($("#gantt_cont")); // TODO
}
});
//##############################################################################
ysy.view.GanttTask = function () {
ysy.view.Widget.call(this);
this.name = "GanttTaskWidget";
};
ysy.main.extender(ysy.view.Widget, ysy.view.GanttTask, {
_repaintCore: function () {
var issue = this.model;
var gantt_issue = this._constructDhData(issue);
if (gantt._pull[gantt_issue.id]) {
if (this.dhdata.parent != gantt_issue.realParent) {
gantt.silentMoveTask(this.dhdata, gantt_issue.realParent);
delete gantt_issue.realParent;
}
$.extend(this.dhdata, gantt_issue);
gantt.refreshTask(gantt_issue.id);
} else {
this.destroyDhData();
this.dhdata = gantt_issue;
ysy.log.debug("addTaskNoDraw()", "load");
gantt.addTaskFaster(gantt_issue);
}
//window.initInlineEditForContainer($("#gantt_cont")); // TODO
},
destroyDhData: function (silent) {
if (!this.dhdata) return;
this.dhdata.deleted = true;
if (gantt.isTaskExists(this.dhdata.id)) {
gantt._deleteTask(this.dhdata.id, silent);
}
this.dhdata = null;
ysy.log.debug("Destroy for " + this.name, "widget_destroy");
},
destroy: function (silent) {
this.destroyDhData(silent);
this.deleted = true;
},
_constructDhData: function (issue) {
// var parent = issue.getParent() || 0;
var gantt_issue = {
id: issue.getID(),
real_id: issue.id,
text: issue.name,
css: (issue.css || '') + (issue.closed ? ' closed' : ''),
//model:issue,
widget: this,
order: this.order,
open: issue.isOpened(),
start_date: issue.start_date ? moment(issue.start_date) : undefined,
$ignore: issue._ignore || false,
columns: issue.columns,
readonly: !issue.isEditable(),
realParent: issue.getParent() || 0,
type: issue.ganttType
};
gantt_issue.$open = gantt_issue.open;
if (issue.isProject) {
// -- PROJECT --
$.extend(gantt_issue, {
progress: issue.getProgress(),
maximal_start: issue.start_date,
minimal_end: issue.end_date,
start_date: issue.start_date,
end_date: issue.end_date
});
} else if (issue.isIssue) {
// -- ISSUE --
var end_date = moment(issue._end_date);
//if (!issue._end_date.isValid()) {
// console.error("_end_date is not valid");
// end_date = moment(issue._start_date).add(1, "d");
//}
end_date._isEndDate = true;
$.extend(gantt_issue, {
start_date: moment(issue._start_date),
end_date: end_date,
progress: (issue.done_ratio || 0) / 100.0,
//duration: issue.end_date.diff(issue.start_date, 'days'),
assigned_to: issue.assigned_to,
estimated: issue.estimated_hours || 0,
soonest_start: issue.soonest_start,
latest_due: issue.latest_due
});
} else if (issue.milestone) {
// -- MILESTONE --
gantt_issue.end_date = moment(gantt_issue.start_date);
gantt_issue.end_date._isEndDate = true;
} else {
// -- ASSIGNEE --
}
ysy.proManager.fireEvent("extendGanttTask", issue, gantt_issue);
return gantt_issue;
},
update: function (item, keys) {
var obj;
if (item.type === "milestone") {
this.model.set({
name: item.text,
start_date: moment(item.start_date)
});
} else if (item.type === "project") {
obj = {
start_date: moment(item.start_date),
end_date: moment(item.end_date),
_shift: item.start_date.diff(this.model.start_date, "days") + (this.model._shift || 0)
};
obj.end_date._isEndDate = true;
this.model.set(obj);
} else {
var fullObj = {
name: item.text,
//assignedto: item.assignee,
estimated_hours: item.estimated,
done_ratio: Math.round(item.progress * 10) * 10,
start_date: moment(item.start_date),
end_date: moment(item.end_date)
};
fullObj.end_date._isEndDate = true;
if (item._parentChanged) {
$.extend(fullObj, this._constructParentUpdate(item.parent));
item._parentChanged = false;
}
obj = fullObj;
if (keys !== undefined) {
obj = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key === "fixed_version_id") {
if (typeof item.parent === "string") {
obj.fixed_version_id = parseInt(item.parent.substring(1));
} else {
obj.parent = item.parent; // TODO subtask žížaly musí mít parent nebo něco
}
//this.parent.requestRepaint();
} else {
obj[key] = fullObj[key];
}
}
}
this.model.set(obj);
}
this.requestRepaint();
},
_constructParentUpdate: function (parentId) {
if (typeof parentId !== "string") {
var parent = gantt._pull[parentId];
if (!parent) return {};
var parentModel = parent.widget.model;
if (!parentModel) return {};
if (parentModel.fixed_version_id) {
return {
parent_issue_id: parentId,
fixed_version_id: parentModel.fixed_version_id,
project_id: parentModel.project_id
};
} else {
return {parent_issue_id: parentId, project_id: parentModel.project_id};
}
} else if (ysy.main.startsWith(parentId, "p")) {
return {
parent_issue_id: null, project_id: parseInt(parentId.substring(1)), fixed_version_id: null
};
} else if (ysy.main.startsWith(parentId, "m")) {
return {
parent_issue_id: null, fixed_version_id: parseInt(parentId.substring(1))
};
} else if (parentId === "empty") {
return {
parent_issue_id: null, project_id: ysy.settings.projectID, fixed_version_id: null
};
} else return null;
}
});
//##############################################################################
ysy.view.GanttLinks = function () {
ysy.view.Widget.call(this);
this.name = "GanttLinksWidget";
ysy.view.ganttLinks = this;
};
ysy.main.extender(ysy.view.Widget, ysy.view.GanttLinks, {
_updateChildren: function () {
var rela, link, i;
var model = this.model.getArray();
if (this.children.length === 0) {
for (i = 0; i < model.length; i++) {
rela = model[i];
if (rela.isHalfLink()) continue;
link = new ysy.view.GanttLink();
link.init(rela);
this.children.push(link);
}
} else {
var narr = [];
var temp = {};
for (i = 0; i < this.children.length; i++) {
var child = this.children[i];
temp[child.model.id] = child;
}
for (i = 0; i < model.length; i++) {
rela = model[i];
if (rela.isHalfLink()) continue;
link = temp[rela.id];
if (!link) {
link = new ysy.view.GanttLink();
link.init(rela);
} else {
delete temp[rela.id];
}
narr.push(link);
}
for (var key in temp) {
if (temp.hasOwnProperty(key)) {
temp[key].destroy(true);
}
}
this.children = narr;
}
ysy.log.log("-- " + this.children.length + " Children updated in " + this.name);
},
_repaintCore: function () {
//this._updateTaskInGantt();
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
//this.setChildTarget(child, i); // SET CHILD TARGET
child.repaint(true); // CHILD REPAINT
}
//gantt.refreshData();
}
});
//##############################################################################
ysy.view.GanttLink = function () {
ysy.view.Widget.call(this);
this.name = "GanttLinkWidget";
};
ysy.main.extender(ysy.view.Widget, ysy.view.GanttLink, {
_repaintCore: function () {
var rela = this.model;
var link = this._constructDhData(rela);
if (gantt._lpull[link.id]) {
$.extend(this.dhdata, link);
gantt.refreshLink(link.id);
gantt.refreshTask(link.source);
gantt.refreshTask(link.target);
} else {
this.dhdata = link;
gantt.addLink(link);
}
//gantt.sort();
},
destroy: function (silent) {
if (this.dhdata) {
this.dhdata.deleted = true;
if (gantt.isLinkExists(this.model.id)) {
gantt._deleteLink(this.model.id, silent);
}
this.dhdata = null;
ysy.log.debug("Destroy for " + this.name, "widget_destroy");
}
this.deleted = true;
},
_constructDhData: function (model) {
return {
id: model.id,
source: model.source_id,
target: model.target_id,
type: model.isSimple ? "start_to_start" : model.type,
isSimple: model.isSimple,
unlocked: model.unlocked,
delay: model.delay,
readonly: !model.isEditable(),
widget: this
};
},
update: function (item) {
ysy.history.openBrack();
this.model.set({
// name: item.text,
// source_id: item.source,
// target_id: item.target,
type: this.model.type || item.type,
delay: item.delay
});
var allRequests = {};
this.model.sendMoveRequest(allRequests);
gantt.applyMoveRequests(allRequests);
ysy.history.closeBrack();
}
});
//##############################################################################
ysy.view.GanttRefresher = function () {
ysy.view.Widget.call(this);
this.name = "GanttRefresherWidget";
this.all = false;
this.data = false;
this.tasks = [];
this.links = [];
};
ysy.main.extender(ysy.view.Widget, ysy.view.GanttRefresher, {
_postInit: function () {
this.model.refresher = this;
},
_register: function () {
},
renderAll: function () {
this.all = true;
this.requestRepaint();
},
renderData: function () {
this.data = true;
this.requestRepaint();
},
refreshTask: function (taskId) {
for (var i = 0; i < this.tasks.length; i++) {
if (this.tasks[i] == taskId) return;
}
this.tasks.push(taskId);
this.requestRepaint();
},
refreshLink: function (linkId) {
for (var i = 0; i < this.links.length; i++) {
if (this.links[i] == linkId) return;
}
this.links.push(linkId);
this.requestRepaint();
},
_repaintCore: function () {
if (this.all) {
ysy.log.debug("---- Refresher: _renderAll", "refresher");
var visibleDate = gantt.getShowDate();
if (!visibleDate) {
visibleDate = ysy.data.limits.zoomDate;
}
gantt._backgroundRenderer.forceRender = false;
this.model._render();
gantt._backgroundRenderer.forceRender = true;
//ysy.log.debug(moment(visibleDate).toISOString(), "refresher");
gantt.showDate(visibleDate);
delete gantt._backgroundRenderer.forceRender;
ysy.view.affix.requestRepaint();
} else if (this.data) {
ysy.log.debug("---- Refresher: _renderData", "refresher");
this.model._render_data();
if (this.all) return true;
} else {
ysy.log.debug("---- Refresher: _render for " + this.tasks.length + " tasks and " + this.links.length + " links", "refresher");
for (var i = 0; i < this.tasks.length; i++) {
var taskId = this.tasks[i];
this.model._refreshTask(taskId);
if (this.all || this.data) return true;
}
for (i = 0; i < this.links.length; i++) {
var linkId = this.links[i];
this.model._refreshLink(linkId);
if (this.all || this.data) return true;
}
}
this.all = false;
this.data = false;
this.tasks = [];
this.links = [];
}
});

View File

@ -0,0 +1,130 @@
/* history.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.history = ysy.history || {};
$.extend(ysy.history, {
_name: "History",
_inbrack: 0,
stack: [],
_binded: false,
add: function (diff, ctx) {
this.stack.push({diff: diff, ctx: ctx});
this._fireChanges(this, "add");
this._bind();
},
revert: function (who) {
var first = true;
if (this.stack.length === 0) return;
while (this._inbrack || first) {
first = false;
var rev = this.stack.pop();
if (!rev) return;
if (typeof rev === "string") {
if (rev === "close") {
this._inbrack++;
continue;
} else if (rev === "open") {
this._inbrack--;
break;
}
}
this._revertOne(rev);
}
//console.log("Revert by "+(typeof rev.diff));
if (this.stack.length === 0) {
this._unbind();
}
this._fireChanges(who, "revert");
},
_revertOne: function (rev) {
if (typeof rev.diff === "array") {
rev.ctx.array = rev.diff;
rev.ctx._fireChanges(this, "revert");
} else if (typeof rev.diff === "function") {
$.proxy(rev.diff, rev.ctx)();
rev.ctx._fireChanges(this, "revert");
} else {
//rev.ctx.set(rev.diff,true);
$.extend(rev.ctx, rev.diff);
rev.ctx._fireChanges(this, "revert");
}
},
clear: function (who) {
if (this.stack.length > 0) {
this._unbind();
}
this.stack = [];
this._inbrack = 0;
this._fireChanges(who, "clear");
},
openBrack: function () {
if (this._inbrack) {
} else {
this.stack.push("open");
}
this._inbrack++;
},
closeBrack: function () {
if (this._inbrack === 0) {
ysy.log.error("History bracket is not opened");
}
if (this._inbrack === 1) {
if (this.stack[this.stack.length - 1] === "open") {
this.stack.pop();
} else {
this.stack.push("close");
}
}
this._inbrack--;
},
_bind: function () {
if (this._binded)return;
$(window).bind('beforeunload', function (e) {
var message = "Some changes are not saved!";
e.returnValue = message;
return message;
});
},
_unbind: function () {
$(window).unbind('beforeunload');
this._binded = false;
},
_onChange: [],
register: function (func, ctx) {
this._onChange.push({func: func, ctx: ctx});
},
inBracket: function () {
return this._inbrack > 0
},
isEmpty: function () {
return !this.stack.length;
},
_fireChanges: function (who, reason) {
if (who) {
var rest = "";
if (reason) {
rest = " because of " + reason;
}
ysy.log.log("* " + who._name + " ordered repaint on " + this._name + "" + rest);
}
if (this._onChange.length > 0) {
ysy.log.log("- " + this._name + " onChange fired for " + this._onChange.length + " widgets");
} else {
ysy.log.log("- no changes for " + this._name);
}
for (var i = 0; i < this._onChange.length; i++) {
var ctx = this._onChange[i].ctx;
if (!ctx || ctx.deleted) {
this._onChange.splice(i, 1);
continue;
}
//this.onChangeNew[i].func();
ysy.log.log("-- changes to " + ctx.name + " widget");
//console.log(ctx);
$.proxy(this._onChange[i].func, ctx)();
}
}
});

View File

@ -0,0 +1,331 @@
/* left_grid.js */
/* global ysy */
window.ysy = window.ysy || {};
ysy.view = ysy.view || {};
ysy.view.leftGrid = ysy.view.leftGrid || {};
$.extend(ysy.view.leftGrid, {
columnsWidth: {
id: 60,
subject: 200,
name: 200,
project: 140,
other: 70,
updated_on: 85,
assigned_to: 100,
grid_width: 400
},
patch: function () {
ysy.data.limits.columnsWidth = $.extend({}, this.columnsWidth);
ysy.view.columnBuilders = ysy.view.columnBuilders || {};
$.extend(ysy.view.columnBuilders, {
id: function (obj) {
if (obj.id > 1000000000000) return '';
var path = ysy.settings.paths.rootPath + "issues/";
return "<a href='" + path + obj.id + "' title='" + ysy.main.escapeText(obj.text) + "' target='_blank'>#" + obj.id + "</a>";
},
updated_on: function (obj) {
if (!obj.columns)return "";
var value = obj.columns.updated_on;
if (value) {
return moment.utc(value, 'YYYY-MM-DD HH:mm:ss ZZ').fromNow();
} else {
return "";
}
},
done_ratio: function (obj) {
if (!obj.columns)return "";
//return '<span class="multieditable">'+Math.round(obj.progress*10)*10+'</span>';
return '<span >' + Math.round(obj.progress * 10) * 10 + '</span>';
},
estimated_hours: function (obj) {
if (!obj.columns)return "";
return '<span >' + obj.estimated + '</span>';
},
subject: function (obj) {
var id = parseInt(obj.real_id);
var text = ysy.main.escapeText(obj.text);
if (isNaN(id) || id > 1000000000000) return text;
var path = ysy.settings.paths.rootPath + "issues/";
if (obj.type === "milestone") {
path = ysy.settings.paths.rootPath + "versions/"
} else if (obj.type === "project") {
path = ysy.settings.paths.rootPath + "projects/"
} else if (obj.type === "assignee") {
if (obj.subtype === "group") {
path = ysy.settings.paths.rootPath + "groups/"
} else {
path = ysy.settings.paths.rootPath + "users/"
}
}
return "<a href='" + path + id + "' title='" + text + "' target='_blank'>" + text + "</a>";
},
_default: function (col) {
return function (obj) {
if (!obj.columns) return "";
if (col.dont_escape) return obj.columns[col.name];
return ysy.main.escapeText(obj.columns[col.name] || "");
};
}
});
gantt._render_grid_superitem = function (item) {
var subjectColumn = ysy.view.columnBuilders.subject;
var tree = "";
for (var j = 0; j < item.$level; j++)
tree += this.templates.grid_indent(item);
var has_child = this._has_children(item.id);
if (has_child) {
tree += this.templates.grid_open(item);
tree += this.templates.grid_folder(item);
} else {
tree += this.templates.grid_blank(item);
tree += this.templates.grid_file(item);
}
var afterText = this.templates.superitem_after_text(item, has_child);
var odd = item.$index % 2 === 0;
var style = "";//"width:" + (col.width - (last ? 1 : 0)) + "px;";
var cell = "<div class='gantt_grid_superitem' style='" + style + "'>" + tree + subjectColumn(item) + afterText + "</div>";
var css = odd ? " odd" : "";
if (this.templates.grid_row_class) {
var css_template = this.templates.grid_row_class.call(this, item.start_date, item.end_date, item);
if (css_template)
css += " " + css_template;
}
if (this.getState().selected_task == item.id) {
css += " gantt_selected";
}
var el = document.createElement("div");
el.className = "gantt_row" + css;
//el.setAttribute("data-url","/issues/"+item.id+".json"); // HOSEK
el.style.height = this.config.row_height + "px";
el.style.lineHeight = (gantt.config.row_height) + "px";
el.setAttribute(this.config.task_attribute, item.id);
el.innerHTML = cell;
return el;
};
$.extend(gantt.templates, {
grid_open:function(item) {
return "<div class='gantt_tree_icon gantt_" + (item.$open ? "close" : "open") + " easy-gantt__icon easy-gantt__icon--" + (item.$open ? "close" : "open") + "'></div>";
},
grid_folder: function (item) {
/// = HAS CHILDREN
if (this["grid_bullet_" + gantt._get_safe_type(item.type)]) {
return this["grid_bullet_" + gantt._get_safe_type(item.type)](item, true);
}
// default fallback
if (item.$open || gantt._get_safe_type(item.type) !== gantt.config.types.task) {
return "<div class='gantt_tree_icon gantt_folder_" + (item.$open ? "open" : "closed") + "'></div>";
} else {
return "<div class='gantt_tree_icon'><div class='gantt_drag_handle gantt_subtask_arrow'></div></div>";
}
},
grid_file: function (item) {
// = HAS NO CHILDREN
if (this["grid_bullet_" + gantt._get_safe_type(item.type)]) {
return this["grid_bullet_" + gantt._get_safe_type(item.type)](item, false);
}
// default fallback
if (gantt._get_safe_type(item.type) === gantt.config.types.task)
return "<div class='gantt_tree_icon'><div class='gantt_drag_handle gantt_subtask_arrow'></div></div>";
return "<div class='gantt_tree_icon gantt_folder_open'></div>";
},
grid_bullet_milestone: function (item, has_children) {
var rearrangable = false;
return "<div class='gantt_tree_icon " + (rearrangable ? "gantt_drag_handle" : "") + "'>" +
"<div class='gantt-milestone-icon gantt-grid-milestone-bullet" + (rearrangable ? " gantt-bullet-hover-hide" : "") + "'></div></div>";
},
grid_bullet_project: function (item, has_children) {
if (item.$open || !has_children) {
return "<div class='gantt_tree_icon gantt_folder_open'></div>";
} else {
return "<div class='gantt_tree_icon gantt_folder_closed'></div>";
}
},
grid_bullet_task: function (item, has_children) {
if (has_children) {
return "<div class='gantt_tree_icon gantt_drag_handle gantt_folder_" + (item.$open ? "open" : "closed") + "'></div>";
} else {
return "<div class='gantt_tree_icon'><div class='gantt_drag_handle gantt_subtask_arrow'></div></div>";
}
},
superitem_after_text: function (item, has_children) {
if (this["superitem_after_" + gantt._get_safe_type(item.type)]) {
return this["superitem_after_" + gantt._get_safe_type(item.type)](item, has_children);
}
return "";
}
});
gantt._render_grid_header = function () {
var columns = this.getGridColumns();
var cells = [];
var width = 0,
labels = this.locale.labels;
var lineHeigth = this.config.scale_height - 2;
var resizes = [];
for (var i = 0; i < columns.length; i++) {
var last = i === columns.length - 1;
var col = columns[i];
if (last && this._get_grid_width() > width + col.width)
col.width = this._get_grid_width() - width;
width += col.width;
var sort = (this._sort && col.name === this._sort.name) ? ("<div class='gantt_sort gantt_" + this._sort.direction + "'></div>") : "";
if (col.tree) {
if (!this._sort) sort = '<div class="gantt_sort gantt_none"></div>';
if (ysy.pro.collapsor) {
sort += ysy.pro.collapsor.templateHtml;
}
}
var cssClass = ["gantt_grid_head_cell",
("gantt_grid_head_" + col.name),
(last ? "gantt_last_cell" : ""),
this.templates.grid_header_class(col.name, col)].join(" ");
var style = "width:" + (col.width - (last ? 1 : 0)) + "px;";
var label = (col.label || labels["column_" + col.name]);
label = label || "";
var cell = "<div class='" + cssClass + "' style='" + style + "' column_id='" + col.name + "'><div class='gantt-grid-header-multi'>" + label + sort + "</div></div>";
if (!last) {
resizes.push("<div style='left:" + (width - 6) + "px' class='gantt_grid_column_resize_wrap' data-column_id='" + col.name + "'></div>");
}
cells.push(cell);
//var resize='<div style="height:100%;background-color:red;width:10px;cursor: col-resize;position: absolute;left:'+(width-5)+'px;z-index:1"></div>';
/*var resize = '<div class="gantt_grid_column_resize_wrap" style="height:100%;left:' + (width - 7) + 'px;z-index:1" column-index="' + i + '">\
<div class="gantt_grid_column_resize"></div></div>';
resizes.push(resize);*/
}
//var resize = '<div class="gantt_grid_column_resize_wrap" style="height:100%;left:' + (this._get_grid_width() - 10) + 'px;z-index:1" >\
//<div class="gantt_grid_column_resize"></div></div>';
this.$grid_resize.style.left = (this._get_grid_width() - 6) + "px";
this.$grid_scale.style.height = (this.config.scale_height - 1) + "px";
this.$grid_scale.style.lineHeight = lineHeigth + "px";
this.$grid_scale.style.width = (width - 1) + "px";
this.$grid_scale.style.position = "relative";
this.$grid_scale.innerHTML = cells.join("") + resizes.join("");
ysy.view.leftGrid.resizeTable();
if (ysy.view.collapsors) {
ysy.view.collapsors.requestRepaint();
}
//resizeColumns();
};
gantt._calc_grid_width = function () {
var i;
var columns = this.getGridColumns();
var cols_width = 0;
var width = [];
for (i = 0; i < columns.length; i++) {
var v = parseInt(columns[i].min_width, 10);
width[i] = v;
cols_width += v;
}
var diff = this._get_grid_width() - cols_width;
if (this.config.autofit || diff > 0) {
var delta = Math.ceil(diff / (columns.length ? columns.length : 1));
//var ratio=1+diff/(cols_width?cols_width:1);
for (i = 0; i < width.length; i++) {
columns[i].width = columns[i].min_width + delta;//*ratio;
}
} else {
for (i = 0; i < columns.length; i++) {
columns[i].width = columns[i].min_width;
}
//this.config.grid_width = cols_width;
}
};
},
constructColumns: function (columns) {
var dcolumns = [];
var columnBuilders = ysy.view.columnBuilders;
var getBuilder = function (col) {
if (columnBuilders[col.name]) {
return columnBuilders[col.name];
} else if (columnBuilders[col.name + "Builder"]) {
return columnBuilders[col.name + "Builder"](col);
}
else return columnBuilders._default(col);
};
for (var i = 0; i < columns.length; i++) {
var col = columns[i];
var isMainColumn = col.name === "subject" || col.name === "name";
if (col.name === "id" && !ysy.settings.easyRedmine) continue;
var css = "gantt_grid_body_" + col.name;
if (col.name !== "") {
var width = ysy.data.limits.columnsWidth[col.name] || ysy.data.limits.columnsWidth["other"];
var dcolumn = {
name: col.name,
label: col.title,
min_width: width,
width: width,
tree: isMainColumn,
align: isMainColumn ? "left" : "center",
template: getBuilder(col),
css: css
};
if (isMainColumn) {
dcolumns.unshift(dcolumn);
} else {
dcolumns.push(dcolumn);
}
}
}
return dcolumns;
},
resizeTable: function () {
var $resizes = $(".gantt_grid_column_resize_wrap:not(inited)");
var colWidths = ysy.data.limits.columnsWidth;
var $gantt_grid = $(".gantt_grid");
var $gantt_grid_data = $(".gantt_grid_data");
var $gantt_grid_scale = $(".gantt_grid_scale");
$resizes.each(function (index, el) {
var config = {};
var $el = $(el);
var column = $el.data("column_id");
var dhtmlxDrag = new dhtmlxDnD(el, config);
var minWidth,
realWidth,
resizePos,
gridWidth;
dhtmlxDrag.attachEvent("onDragStart", function () {
if (this.config.started) return;
minWidth = colWidths[column] || colWidths.other;
realWidth = $gantt_grid.find(".gantt_grid_head_" + column).width();
gridWidth = $gantt_grid.width();
resizePos = $el.offset();
});
dhtmlxDrag.attachEvent("onDragMove", function (target, event) {
//var diff=Math.floor(event.pageX-lastPos);
var diff = Math.floor(dhtmlxDrag.getDiff().x);
ysy.log.debug("moveDrag diff=" + diff + "px width=" + realWidth + "px", "grid_resize");
$gantt_grid.width(gridWidth + diff);
$gantt_grid_data.width(gridWidth + diff);
$gantt_grid_scale.width(gridWidth + diff);
$el.offset({top: resizePos.top, left: resizePos.left + diff});
colWidths[column] = minWidth + diff;
var columns = gantt.config.columns;
if (index < columns.length - 1) {
gantt.config.columns[index].min_width = minWidth + diff;
gantt.config.columns[index].width = realWidth + diff + 1;
$gantt_grid.find(".gantt_grid_head_" + column + ", .gantt_grid_body_" + column).width(realWidth + diff + "px");
}
gantt.config.grid_width = gridWidth + diff;
colWidths.grid_width = gridWidth + diff;
});
dhtmlxDrag.attachEvent("onDragEnd", function (target, event) {
gantt.render();
//gantt._render_grid();
//var data = gantt._get_tasks_data();
//gantt._gridRenderer.render_items(data);
//ysy.view.ganttTasks.requestRepaint();
});
});
$resizes.addClass("inited");
}
});

Some files were not shown because too many files have changed in this diff Show More