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] belongs_to :project has_many :overtime_sheet_entries has_many :crew_overtimes, through: :overtime_sheet_entries scope :open, ->(id) { where(status: OPEN, project_id: id) } scope :submitted, ->(id) { where(status: SUBMITTED, project_id: id) } def self.open_exists?(project_id) OvertimeSheet.open(project_id).exists? end def self.open_for_date_exists?(date, project_id) OvertimeSheet.open(project_id).where(date: date).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, project_id) if OvertimeSheet.open_for_date_exists?(date, project_id) raise 'There is already an open overtime sheet for the selected date.' end if OvertimeSheet.open_exists?(project_id) 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, project_id: project_id) end end end end