Class: Ecom::Core::CrewTime

Inherits:
ApplicationRecord show all
Defined in:
app/models/ecom/core/crew_time.rb

Constant Summary collapse

MORNING =

Time Ranges

'Morning'.freeze
AFTERNOON =
'Afternoon'.freeze
BOTH =
'Both'.freeze
TIME_RANGE =
{
  MORNING => {start: Time.zone.parse('5:00 AM'), end: Time.zone.parse('9:00 AM')},
  AFTERNOON => {start: Time.zone.parse('10:00 AM'), end: Time.zone.parse('2:00 PM')},
  BOTH => {start: Time.zone.parse('5:00 AM'), end: Time.zone.parse('2:00 PM')}
}.freeze

Instance Method Summary collapse

Instance Method Details

#calculate_hoursObject



25
26
27
28
29
30
31
# File 'app/models/ecom/core/crew_time.rb', line 25

def calculate_hours
  self.hours = if checkout_time.nil? || checkin_time.nil?
                 0
               else
                 compute_hours
               end
end

#calculate_totalObject



33
34
35
# File 'app/models/ecom/core/crew_time.rb', line 33

def calculate_total
  compute_total_for_entry if saved_change_to_hours?
end

#compute_hoursObject

A method to adjust time ranges by trimming any time value outside of the defined morning and afternoon ranges



59
60
61
62
63
64
65
66
67
68
69
# File 'app/models/ecom/core/crew_time.rb', line 59

def compute_hours
  # Reparse time to avoid errors caused by date differences
  start = Time.zone.parse(checkin_time.strftime('%I:%M%p'))
  finish = Time.zone.parse(checkout_time.strftime('%I:%M%p'))
  range = find_range(start, finish)
  left = start.before?(TIME_RANGE[range][:start]) ? TIME_RANGE[range][:start] : start
  right = finish.after?(TIME_RANGE[range][:end]) ? TIME_RANGE[range][:end] : finish
  time = (right - left) / 1.hour
  time -= 1 if range == BOTH
  time
end

#compute_total_for_entryObject



37
38
39
40
41
42
43
# File 'app/models/ecom/core/crew_time.rb', line 37

def compute_total_for_entry
  attendance_sheet_entry.total_hours = Ecom::Core::CrewTime.where(
    attendance_sheet_entry: attendance_sheet_entry,
    revised: false
  ).sum(:hours)
  attendance_sheet_entry.save
end

#find_range(start, finish) ⇒ Object

A method to check if checkin and checkout range falls in the morning, afternoon, or both.



47
48
49
50
51
52
53
54
55
# File 'app/models/ecom/core/crew_time.rb', line 47

def find_range(start, finish)
  if start.before?(TIME_RANGE[MORNING][:end]) && finish.before?(TIME_RANGE[AFTERNOON][:start])
    MORNING
  elsif start.after?(TIME_RANGE[MORNING][:end]) && finish.after?(TIME_RANGE[AFTERNOON][:start])
    AFTERNOON
  else
    BOTH
  end
end