Sha256: f2a2748f5c7f2b2be9f326bc12b541052a91aa37e706fee68ce49042444b54e7

Contents?: true

Size: 1.81 KB

Versions: 2

Compression:

Stored size: 1.81 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.parse('8:00 AM'), end: Time.parse('12:00 PM')},
        AFTERNOON => {start: Time.parse('1:00 PM'), end: Time.parse('5:00 PM')},
        BOTH => {start: Time.parse('8:00 AM'), end: Time.parse('5: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_save :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

2 entries across 2 versions & 1 rubygems

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