summaryrefslogtreecommitdiffstats
path: root/lib/hcl/day_entry.rb
blob: 8485139f224065720e22378c63e4496146b0658a (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
module HCl 
  class DayEntry < TimesheetResource
    include Utility

    collection_name :day_entries
    resources :today, 'daily', load_cb:->(data) { Task.cache_tasks_hash data }
    resources(:daily) {|date| date ? "daily/#{date.strftime '%j/%Y'}" : 'daily' }
    resource(:project_info, class_name:'Project') { "projects/#{project_id}" }

    def to_s
      "#{client} - #{project} - #{task} (#{formatted_hours})"
    end

    def task
      @data[:task]
    end

    def cancel
      begin
        Net.delete("daily/delete/#{id}")
      rescue HarvestMiddleware::Failure
        return false
      end
      true
    end

    def notes
      super || @data[:notes] = ''
    end

    # Append a string to the notes for this task.
    def append_note new_notes
      # If I don't include hours it gets reset.
      # This doens't appear to be the case for task and project.
      (self.notes << "\n#{new_notes}").lstrip!
      Net.post "daily/update/#{id}", notes:notes, hours:hours
    end

    def self.with_timer date=nil
      daily(date).detect {|t| t.running? }
    end

    def self.last_by_task project_id, task_id
      today.sort {|a,b| b.updated_at<=>a.updated_at}.
        detect {|t| t.project_id == project_id && t.task_id == task_id }
    end

    def self.last
      today.sort {|a,b| a.updated_at<=>b.updated_at}[-1]
    end

    def running?
      !@data[:timer_started_at].nil? && !@data[:timer_started_at].empty?
    end

    def initialize *args
      super
      # TODO cache client/project names and ids
    end

    def toggle
      Net.get("daily/timer/#{id}")
      self
    end

    # Returns the hours formatted as "HH:MM"
    def formatted_hours
      as_hours hours
    end
  end
end