Class: HrLite::LeaveBalance

Inherits:
ApplicationRecord show all
Defined in:
app/models/hr_lite/leave_balance.rb

Overview

Hybrid balance: only carry-in and manual adjustments are stored; entitlement accrues as a pure function of the policy and used is recomputed live from approved requests — so a holiday added after an approval self-heals both the quota and payroll.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.for(user, leave_type, year) ⇒ Object



13
14
15
# File 'app/models/hr_lite/leave_balance.rb', line 13

def self.for(user, leave_type, year)
  find_or_initialize_by(user_id: user.id, leave_type: leave_type, year: year)
end

Instance Method Details

#available(as_of: Date.current) ⇒ Object



38
39
40
# File 'app/models/hr_lite/leave_balance.rb', line 38

def available(as_of: Date.current)
  entitled(as_of: as_of) - used
end

#entitled(as_of: Date.current) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/models/hr_lite/leave_balance.rb', line 17

def entitled(as_of: Date.current)
  return Float::INFINITY if leave_type.unlimited?

  quota = leave_type.annual_quota
  base =
    if leave_type.accrual == "monthly"
      months = as_of.year == year ? as_of.month : (as_of.year > year ? 12 : 0)
      ((quota / 12) * months).round(1)
    else
      quota
    end
  base + carried_forward + adjustment
end

#usedObject



31
32
33
34
35
36
# File 'app/models/hr_lite/leave_balance.rb', line 31

def used
  requests = LeaveRequest.approved
                         .where(user_id: user_id, leave_type_id: leave_type_id)
                         .where(start_date: Date.new(year, 1, 1)..Date.new(year, 12, 31))
  requests.sum { |request| LeaveDayCounter.count(request) }
end