Sha256: d751d1d787bf787db190df0248bdd8855fbcfee558f58f5a729a65dad24eab2c

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

module Ecom
  module Core
    class CrewTime < ApplicationRecord
      # Time Ranges
      MORNING = '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

      belongs_to :attendance_sheet_entry
      belongs_to :revision_to, class_name: 'Ecom::Core::CrewTime', optional: true
      belongs_to :created_by, class_name: 'Ecom::Core::User'
      has_one :revision, class_name: 'Ecom::Core::CrewTime', foreign_key: :revision_to_id

      validates :hours, presence: true

      before_validation :calculate_hours

      def calculate_hours
        self.hours = (checkout_time.nil? || checkin_time.nil?) ? 0 : compute_hours
      end

      # A method to check if checkin and checkout range falls in the morning,
      # afternoon, or both.
      def find_range
        if checkin_time.before?(TIME_RANGE[MORNING][:end]) && checkout_time.before?(TIME_RANGE[AFTERNOON][:start])
          MORNING
        elsif checkin_time.after?(TIME_RANGE[MORNING][:end]) && checkout_time.after?(TIME_RANGE[AFTERNOON][:start])
          AFTERNOON
        else
          BOTH
        end
      end

      # A method to adjust time ranges by trimming any time value outside
      # of the defined morning and afternoon ranges
      def compute_hours
        range = find_range
        left = checkin_time.before?(TIME_RANGE[range][:start]) ? TIME_RANGE[range][:start] : checkin_time
        right = checkout_time.after?(TIME_RANGE[range][:end]) ? TIME_RANGE[range][:end] : checkout_time
        time = (right - left) / 1.hour
        time -= 1 if range == BOTH
        time
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ecom_core-1.1.27 app/models/ecom/core/crew_time.rb