Sha256: d41d6a4f1d61c13303de2a91876b543b8213b3676d9c264e1a8ef6e35f97b75b

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 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? ? 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.26 app/models/ecom/core/crew_time.rb