module Ecom module Core class OvertimeSheet < ApplicationRecord OPEN = 'Open'.freeze SUBMITTED = 'Submitted'.freeze APPROVED = 'Approved'.freeze validates :date, :opened_at, presence: true, uniqueness: true validates :status, inclusion: [OPEN, SUBMITTED, APPROVED] has_many :overtime_sheet_entries scope :open, -> { find_by(status: OPEN) } def self.open_exists? OvertimeSheet.where(status: OPEN).exists? end # Overtime sheet should be created using the # method below only. This is because we need to # check if there is an open overtime already, # and also that we have only one open overtime # sheet at a time. def self.create_new(date) if OvertimeSheet.open_exists? raise 'There is already an open overtime sheet. It has to be submitted before creating a new one.' end OvertimeSheet.create(date: date, opened_at: Time.now, status: OPEN) end end end end