summaryrefslogtreecommitdiffstats
path: root/app/models/time_entry.rb
blob: a763dc1bea89b1a15bf2e8dd5bfccbcc08dab1f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# frozen_string_literal: true

# Redmine - project management software
# Copyright (C) 2006-2020  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

class TimeEntry < ActiveRecord::Base
  include Redmine::SafeAttributes
  # could have used polymorphic association
  # project association here allows easy loading of time entries at project level with one database trip
  belongs_to :project
  belongs_to :issue
  belongs_to :user
  belongs_to :author, :class_name => 'User'
  belongs_to :activity, :class_name => 'TimeEntryActivity'

  acts_as_customizable
  acts_as_event :title =>
                  Proc.new {|o|
                    related   = o.issue if o.issue && o.issue.visible?
                    related ||= o.project
                    "#{l_hours(o.hours)} (#{related.event_title})"
                  },
                :url => Proc.new {|o| {:controller => 'timelog', :action => 'index', :project_id => o.project, :issue_id => o.issue}},
                :author => :user,
                :group => :issue,
                :description => :comments

  acts_as_activity_provider :timestamp => "#{table_name}.created_on",
                            :author_key => :user_id,
                            :scope => joins(:project).preload(:project)

  validates_presence_of :author_id, :user_id, :activity_id, :project_id, :hours, :spent_on
  validates_presence_of :issue_id, :if => lambda { Setting.timelog_required_fields.include?('issue_id') }
  validates_presence_of :comments, :if => lambda { Setting.timelog_required_fields.include?('comments') }
  validates_numericality_of :hours, :allow_nil => true, :message => :invalid
  validates_length_of :comments, :maximum => 1024, :allow_nil => true
  validates :spent_on, :date => true
  before_validation :set_project_if_nil
  before_validation :set_author_if_nil
  validate :validate_time_entry

  scope :visible, lambda {|*args|
    joins(:project).
    where(TimeEntry.visible_condition(args.shift || User.current, *args))
  }
  scope :left_join_issue, lambda {
    joins("LEFT OUTER JOIN #{Issue.table_name} ON #{Issue.table_name}.id = #{TimeEntry.table_name}.issue_id")
  }
  scope :on_issue, lambda {|issue|
    joins(:issue).
    where("#{Issue.table_name}.root_id = #{issue.root_id} AND #{Issue.table_name}.lft >= #{issue.lft} AND #{Issue.table_name}.rgt <= #{issue.rgt}")
  }

  safe_attributes 'user_id', 'hours', 'comments', 'project_id', 'issue_id', 'activity_id', 'spent_on', 'custom_field_values', 'custom_fields'

  # Returns a SQL conditions string used to find all time entries visible by the specified user
  def self.visible_condition(user, options={})
    Project.allowed_to_condition(user, :view_time_entries, options) do |role, user|
      if role.time_entries_visibility == 'all'
        nil
      elsif role.time_entries_visibility == 'own' && user.id && user.logged?
        "#{table_name}.user_id = #{user.id}"
      else
        '1=0'
      end
    end
  end

  # Returns true if user or current user is allowed to view the time entry
  def visible?(user=nil)
    (user || User.current).allowed_to?(:view_time_entries, self.project) do |role, user|
      if role.time_entries_visibility == 'all'
        true
      elsif role.time_entries_visibility == 'own'
        self.user == user
      else
        false
      end
    end
  end

  def initialize(attributes=nil, *args)
    super
    if new_record? && self.activity.nil?
      if default_activity = TimeEntryActivity.default
        self.activity_id = default_activity.id
      end
      self.hours = nil if hours == 0
    end
  end

  def safe_attributes=(attrs, user=User.current)
    if attrs
      attrs = super(attrs)
      if issue_id_changed? && issue
        if issue.visible?(user) && user.allowed_to?(:log_time, issue.project)
          if attrs[:project_id].blank? && issue.project_id != project_id
            self.project_id = issue.project_id
          end
          @invalid_issue_id = nil
        else
          @invalid_issue_id = issue_id
        end
      end
    end
    attrs
  end

  def set_project_if_nil
    self.project = issue.project if issue && project.nil?
  end

  def set_author_if_nil
    self.author = User.current if author.nil?
  end

  def validate_time_entry
    if hours
      errors.add :hours, :invalid if hours < 0
      errors.add :hours, :invalid if hours == 0.0 && hours_changed? && !Setting.timelog_accept_0_hours?

      max_hours = Setting.timelog_max_hours_per_day.to_f
      if hours_changed? && max_hours > 0.0
        logged_hours = other_hours_with_same_user_and_day
        if logged_hours + hours > max_hours
          errors.add(
            :base,
            I18n.t(:error_exceeds_maximum_hours_per_day,
                   :logged_hours => format_hours(logged_hours),
                   :max_hours => format_hours(max_hours)))
        end
      end
    end
    errors.add :project_id, :invalid if project.nil?
    errors.add :user_id, :invalid if user_id != author_id && !self.assignable_users.map(&:id).include?(user_id)
    errors.add :issue_id, :invalid if (issue_id && !issue) || (issue && project!=issue.project) || @invalid_issue_id
    errors.add :activity_id, :inclusion if activity_id_changed? && project && !project.activities.include?(activity)
    if spent_on_changed? && user
      errors.add :base, I18n.t(:error_spent_on_future_date) if !Setting.timelog_accept_future_dates? && (spent_on > user.today)
    end
  end

  def hours=(h)
    write_attribute :hours, (h.is_a?(String) ? (h.to_hours || h) : h)
  end

  def hours
    h = read_attribute(:hours)
    if h.is_a?(Float)
      h.round(2)
    else
      h
    end
  end

  # tyear, tmonth, tweek assigned where setting spent_on attributes
  # these attributes make time aggregations easier
  def spent_on=(date)
    super
    self.tyear = spent_on ? spent_on.year : nil
    self.tmonth = spent_on ? spent_on.month : nil
    self.tweek = spent_on ? Date.civil(spent_on.year, spent_on.month, spent_on.day).cweek : nil
  end

  # Returns true if the time entry can be edited by usr, otherwise false
  def editable_by?(usr)
    visible?(usr) && (
      (usr == user && usr.allowed_to?(:edit_own_time_entries, project)) || usr.allowed_to?(:edit_time_entries, project)
    )
  end

  # Returns the custom_field_values that can be edited by the given user
  def editable_custom_field_values(user=nil)
    visible_custom_field_values
  end

  # Returns the custom fields that can be edited by the given user
  def editable_custom_fields(user=nil)
    editable_custom_field_values(user).map(&:custom_field).uniq
  end

  def visible_custom_field_values(user = nil)
    user ||= User.current
    custom_field_values.select do |value|
      value.custom_field.visible_by?(project, user)
    end
  end

  def assignable_users
    users = []
    if project
      users = project.members.active.preload(:user)
      users = users.map(&:user).select{ |u| u.allowed_to?(:log_time, project) }
    end
    users << User.current if User.current.logged? && !users.include?(User.current)
    users
  end

  private

  # Returns the hours that were logged in other time entries for the same user and the same day
  def other_hours_with_same_user_and_day
    if user_id && spent_on
      TimeEntry.
        where(:user_id => user_id, :spent_on => spent_on).
        where.not(:id => id).
        sum(:hours).to_f
    else
      0.0
    end
  end
end