module Ecom module Core class AttendanceSheet < ApplicationRecord OPEN = 'Open'.freeze SUBMITTED = 'Submitted'.freeze APPROVED = 'Approved'.freeze validates :date, presence: true, uniqueness: true validates :status, inclusion: [OPEN, SUBMITTED, APPROVED] has_many :attendance_sheet_entries has_many :crew_times, through: :attendance_sheet_entries scope :open, -> { where(status: OPEN) } scope :current, -> { where(date: Date.today) } scope :current_open, -> { open.current } def self.open_for_date(date) AttendanceSheet.find_by(status: OPEN, date: date) end def self.open_exists? AttendanceSheet.open.exists? end def self.exists_for_today? AttendanceSheet.current.exists? end def self.open_exists_for_today? AttendanceSheet.current_open.exists? end # Attendance sheet should be created using the # method below only. This is because we need to # check if there is an open attendance already, # and also that we have only one attendace sheet # per day. def self.create_current raise 'Attendance sheet already created for the day.' if AttendanceSheet.exists_for_today? raise 'There is an open attendance sheet which needs to be submitted before creating a new one.' if AttendanceSheet.open_exists? AttendanceSheet.create(date: Date.today, opened_at: Time.now, status: OPEN) end def self.submit_current sheet = AttendanceSheet.find_by(date: Date.today, status: OPEN) raise 'There is no open attendance sheet to submit.' if sheet.nil? sheet.closed_at = Time.now sheet.status = SUBMITTED sheet.save sheet end # This method should be used by privileged users # to submit the attendance sheet after the date has # passed. Normally, timekeepers need to open and close # an attendance sheet of a date on the specific date. def self.submit(date) sheet = AttendanceSheet.open_for_date(date) raise 'There is no open attendance sheet to submit for the selected day.' unless sheet sheet.closed_at = Time.now sheet.status = SUBMITTED sheet.save sheet end end end end