Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 15 additions & 46 deletions hrms/hr/doctype/leave_allocation/leave_allocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,59 +465,28 @@ def retry_failed_allocations(self, failed_allocations: list) -> None:
if not frappe.has_permission(doctype="Leave Allocation", ptype="write", user=frappe.session.user):
frappe.throw(_("You do not have permission to complete this action"), frappe.PermissionError)

max_leaves_allowed, frequency = frappe.db.get_values(
"Leave Type", self.leave_type, ["max_leaves_allowed", "earned_leave_frequency"]
)[0]
from hrms.hr.utils import update_previous_leave_allocation

leave_type = frappe.get_cached_doc("Leave Type", self.leave_type)
annual_allocation = frappe.get_value(
"Leave Policy Detail",
{"parent": self.leave_policy, "leave_type": self.leave_type},
"annual_allocation",
)

for allocation in failed_allocations:
new_allocation = flt(self.total_leaves_allocated) + flt(allocation["number_of_leaves"])

new_allocation_without_cf = flt(self.get_existing_leave_count()) + flt(
allocation["number_of_leaves"]
requested_dates = {getdate(row["allocation_date"]) for row in failed_allocations}
self.reload()
for row in self.earned_leave_schedule:
if not (row.failed and row.attempted and getdate(row.allocation_date) in requested_dates):
continue
update_previous_leave_allocation(
self,
annual_allocation,
leave_type,
row.number_of_leaves,
row.allocation_date,
allocated_via="Manually",
)

if new_allocation > max_leaves_allowed and max_leaves_allowed > 0:
frappe.throw(
msg=_(
"Cannot allocate more leaves due to maximum leaves allowed limit of {0} in {1} leave type."
).format(frappe.bold(max_leaves_allowed), frappe.bold(self.leave_type)),
title=_("Retry Failed"),
)

elif new_allocation_without_cf > annual_allocation and frequency != "Yearly":
frappe.throw(
msg=_(
"Cannot allocate more leaves due to maximum leave allocation limit of {0} in leave policy assignment"
).format(frappe.bold(annual_allocation)),
title=_("Retry Failed"),
)

else:
self.db_set("total_leaves_allocated", new_allocation, update_modified=False)
create_additional_leave_ledger_entry(
self, allocation["number_of_leaves"], allocation["allocation_date"]
)
earned_leave_schedule = frappe.qb.DocType("Earned Leave Schedule")
(
frappe.qb.update(earned_leave_schedule)
.where(
(earned_leave_schedule.parent == self.name)
& (earned_leave_schedule.allocation_date == allocation["allocation_date"])
& (earned_leave_schedule.attempted == 1)
& (earned_leave_schedule.failed == 1)
)
.set(earned_leave_schedule.is_allocated, 1)
.set(earned_leave_schedule.attempted, 1)
.set(earned_leave_schedule.allocated_via, "Manually")
.set(earned_leave_schedule.failed, 0)
.set(earned_leave_schedule.failure_reason, "")
).run()
self.reload()


def get_previous_allocation(from_date, leave_type, employee):
Expand Down
38 changes: 38 additions & 0 deletions hrms/hr/doctype/leave_allocation/test_earned_leave_schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,42 @@ def test_schedule_when_doj_is_end_of_big_month(self):
self.employee.date_of_joining,
)

def test_schedule_does_not_exceed_annual_allocation_when_rounded_up(self):
"""Tests that rounding up the periodic leave does not schedule more leaves than the policy allows"""
frappe.flags.current_date = get_year_start(getdate())
earned_leave_schedule = create_earned_leave_schedule(
self.employee,
allocate_on_day="First Day",
earned_leave_frequency="Monthly",
annual_allocation=19,
assignment_based_on="Leave Period",
start_date=get_year_start(getdate()),
end_date=get_year_ending(getdate()),
rounding=1.0,
)

self.assertEqual(len(earned_leave_schedule), 10)
self.assertEqual(sum(row.number_of_leaves for row in earned_leave_schedule), 19)
self.assertEqual(earned_leave_schedule[-1].number_of_leaves, 1)
self.assertEqual(earned_leave_schedule[-1].allocation_date, add_months(get_year_start(getdate()), 9))

def test_schedule_for_yearly_earned_leave_is_exempted_from_annual_allocation(self):
"""Tests that a yearly schedule spanning multiple years is not capped to the annual allocation"""
frappe.flags.current_date = get_year_start(getdate())
earned_leave_schedule = create_earned_leave_schedule(
self.employee,
allocate_on_day="First Day",
earned_leave_frequency="Yearly",
annual_allocation=19,
assignment_based_on="Leave Period",
start_date=get_year_start(getdate()),
end_date=add_months(get_year_ending(getdate()), 12),
rounding=1.0,
)

self.assertEqual(len(earned_leave_schedule), 2)
self.assertEqual(sum(row.number_of_leaves for row in earned_leave_schedule), 38)

def test_absence_of_earned_leave_schedule_for_non_earned_leave_types(self):
leave_policy = frappe.get_doc(
{
Expand Down Expand Up @@ -406,6 +442,7 @@ def create_earned_leave_schedule(
assignment_based_on,
start_date,
end_date,
rounding=0.5,
):
assignment = make_policy_assignment(
employee,
Expand All @@ -415,6 +452,7 @@ def create_earned_leave_schedule(
assignment_based_on=assignment_based_on,
start_date=start_date,
end_date=end_date,
rounding=rounding,
)[0]
leave_allocation = frappe.get_value("Leave Allocation", {"leave_policy_assignment": assignment}, "name")
earned_leave_schedule = frappe.get_all(
Expand Down
102 changes: 101 additions & 1 deletion hrms/hr/doctype/leave_allocation/test_earned_leaves.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from unittest.mock import patch

import frappe
from frappe.utils import (
add_days,
Expand Down Expand Up @@ -207,10 +209,13 @@ def test_earned_leaves_creation(self):
)

# validate earned leaves creation without maximum leaves
# the leave period spans 13 allocation dates, but the schedule is capped to the
# annual allocation (6), so the leaves skipped due to the max leaves limit
# are not compensated by an extra allocation and have to be retried instead
frappe.db.set_value("Leave Type", self.leave_type, "max_leaves_allowed", 0)
allocate_earned_leaves_for_months(6)
self.assertEqual(
get_leave_balance_on(self.employee.name, self.leave_type, frappe.flags.current_date), 5
get_leave_balance_on(self.employee.name, self.leave_type, frappe.flags.current_date), 4.5
)

def test_overallocation(self):
Expand All @@ -237,6 +242,101 @@ def test_overallocation(self):
get_leave_balance_on(self.employee.name, self.leave_type, frappe.flags.current_date), 22
)

def test_overallocation_when_annual_allocation_is_not_divisible(self):
"""Tests earned leave allocation is capped to the annual allocation
when rounding up does not divide the annual allocation evenly"""
frappe.flags.current_date = get_year_start(getdate())
assignment = make_policy_assignment(
self.employee,
annual_allocation=19,
allocate_on_day="First Day",
start_date=frappe.flags.current_date,
rounding=1.0,
)[0]

# 19 leaves / 12 months = 1.58 rounded to 2 leaves per month
# the last allocation should be capped to the leaves left in the annual quota
allocate_earned_leaves_for_months(12)
self.assertEqual(get_allocated_leaves(assignment), 19)

# allocations should not be marked as failed since nothing was skipped
allocation = frappe.db.get_value("Leave Allocation", {"leave_policy_assignment": assignment}, "name")
self.assertEqual(frappe.db.count("Earned Leave Schedule", {"parent": allocation, "failed": 1}), 0)

def test_overallocation_without_earned_leave_schedule(self):
"""Tests earned leave allocation is capped to the annual allocation
for allocations created before the earned leave schedule was introduced"""
frappe.flags.current_date = get_year_start(getdate())
assignment = make_policy_assignment(
self.employee,
annual_allocation=19,
allocate_on_day="First Day",
start_date=frappe.flags.current_date,
rounding=1.0,
)[0]
allocation = frappe.db.get_value("Leave Allocation", {"leave_policy_assignment": assignment}, "name")
frappe.db.delete("Earned Leave Schedule", {"parent": allocation})

allocate_earned_leaves_for_months(12)
self.assertEqual(get_allocated_leaves(assignment), 19)

def make_capped_monthly_allocation(self):
start_date = get_year_start(getdate())
frappe.flags.current_date = add_days(start_date, -1)
assignment = make_policy_assignment(
self.employee,
annual_allocation=19,
allocate_on_day="First Day",
start_date=start_date,
end_date=get_year_ending(start_date),
rounding=1.0,
)[0]
frappe.flags.current_date = start_date
return frappe.get_doc("Leave Allocation", {"leave_policy_assignment": assignment})

def test_existing_schedule_completes_without_quota_failure(self):
allocation = self.make_capped_monthly_allocation()
# Existing schedules were generated before the annual cap was introduced.
for row in allocation.earned_leave_schedule:
row.db_set("number_of_leaves", 2)
with patch("hrms.hr.utils.send_email_for_failed_allocations") as notify:
allocate_earned_leaves()
allocate_earned_leaves_for_months(11)
notify.assert_not_called()
allocation.reload()
self.assertEqual(allocation.total_leaves_allocated, 19)
self.assertEqual([row.number_of_leaves for row in allocation.earned_leave_schedule[-2:]], [2, 1])
self.assertTrue(all(row.attempted and not row.failed for row in allocation.earned_leave_schedule))

def test_legacy_allocation_without_schedule_completes_without_quota_failure(self):
allocation = self.make_capped_monthly_allocation()
frappe.db.delete("Earned Leave Schedule", {"parent": allocation.name})
with patch("hrms.hr.utils.send_email_for_failed_allocations") as notify:
allocate_earned_leaves()
allocate_earned_leaves_for_months(11)
notify.assert_not_called()
allocation.reload()
self.assertEqual(allocation.total_leaves_allocated, 19)

def test_retry_failed_allocation_credits_remaining_annual_quota(self):
allocation = self.make_capped_monthly_allocation()
allocate_earned_leaves()
allocate_earned_leaves_for_months(8)
allocation.reload()
self.assertEqual(allocation.total_leaves_allocated, 18)
# Before upgrading, this two-day credit failed at the annual limit.
allocation.earned_leave_schedule[-1].db_set({"number_of_leaves": 2, "attempted": 1, "failed": 1})
allocation.reload()
failed = [row.as_dict() for row in allocation.earned_leave_schedule if row.failed]
allocation.retry_failed_allocations(failed)
self.assertEqual(allocation.total_leaves_allocated, 19)
self.assertEqual(allocation.earned_leave_schedule[-1].number_of_leaves, 1)
self.assertFalse(any(row.failed for row in allocation.earned_leave_schedule))
self.assertEqual(allocation.earned_leave_schedule[-1].allocated_via, "Manually")
# A repeated request must not credit the same failed row again.
allocation.retry_failed_allocations(failed)
self.assertEqual(allocation.total_leaves_allocated, 19)

def test_over_allocation_during_assignment_creation(self):
"""Tests backdated earned leave allocation does not exceed annual allocation"""
start_date = get_first_day(add_months(getdate(), -12))
Expand Down
30 changes: 30 additions & 0 deletions hrms/hr/doctype/leave_policy_assignment/leave_policy_assignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,9 +395,39 @@ def get_earned_leave_schedule(
pro_rated_period_end,
)
schedule[0]["number_of_leaves"] = pro_rated_earned_leave

# yearly earned leaves are exempted from the annual allocation limit
# since a single period already grants the entire annual allocation
if annual_allocation and leave_details.earned_leave_frequency != "Yearly":
schedule = cap_schedule_to_annual_allocation(schedule, annual_allocation)

return schedule


def cap_schedule_to_annual_allocation(schedule, annual_allocation):
from frappe.model.meta import get_field_precision

precision = get_field_precision(frappe.get_meta("Leave Allocation").get_field("new_leaves_allocated"))
annual_allocation = flt(annual_allocation, precision)

capped_schedule = []
scheduled_leaves = 0.0

for row in schedule:
# leaves allocated already have ledger entries against them, they cannot be trimmed
if not row.get("is_allocated"):
leaves_left_in_quota = flt(annual_allocation - scheduled_leaves, precision)
if leaves_left_in_quota <= 0:
break
if flt(row["number_of_leaves"], precision) > leaves_left_in_quota:
row["number_of_leaves"] = leaves_left_in_quota

scheduled_leaves = flt(scheduled_leaves + flt(row["number_of_leaves"], precision), precision)
capped_schedule.append(row)

return capped_schedule


def get_pro_rata_period_end_date(consider_current_month):
# for earned leave, pro-rata period ends on the last day of the month
# pro rata period end date is different for different periods
Expand Down
55 changes: 30 additions & 25 deletions hrms/hr/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,26 +415,21 @@ def calculate_upcoming_earned_leave(allocation, e_leave_type, date_of_joining):
return earned_leave


def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type, earned_leaves, today):
def update_previous_leave_allocation(
allocation, annual_allocation, e_leave_type, earned_leaves, today, allocated_via="Scheduler"
):
allocation = frappe.get_doc("Leave Allocation", allocation.name)
precision = allocation.precision("total_leaves_allocated")
annual_allocation = flt(annual_allocation, precision)
earned_leaves = flt(earned_leaves, precision)
new_leaves_to_allocate_without_cf = flt(
flt(allocation.get_existing_leave_count()) + earned_leaves,
precision,
)
if (
# annual allocation as per policy should not be exceeded except for yearly leaves
new_leaves_to_allocate_without_cf > annual_allocation
and e_leave_type.earned_leave_frequency != "Yearly"
):
frappe.throw(
_("Allocation was skipped due to exceeding annual allocation set in leave policy"),
OverAllocationError,

if earned_leaves > 0 and e_leave_type.earned_leave_frequency != "Yearly":
leaves_left_in_annual_quota = max(
flt(annual_allocation - allocation.get_existing_leave_count(), precision), 0
)
earned_leaves = min(earned_leaves, leaves_left_in_annual_quota)

if e_leave_type.max_leaves_allowed:
if earned_leaves > 0 and e_leave_type.max_leaves_allowed:
leaves_quota = flt(e_leave_type.max_leaves_allowed - allocation.total_leaves_allocated, precision)
if leaves_quota <= 0:
frappe.throw(
Expand All @@ -447,18 +442,28 @@ def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type
if leaves_quota < earned_leaves:
earned_leaves = leaves_quota

allocation.db_set(
"total_leaves_allocated",
earned_leaves + allocation.total_leaves_allocated,
update_modified=False,
)
create_additional_leave_ledger_entry(allocation, earned_leaves, today)
if earned_leaves:
allocation.db_set(
"total_leaves_allocated",
earned_leaves + allocation.total_leaves_allocated,
update_modified=False,
)
create_additional_leave_ledger_entry(allocation, earned_leaves, today)

earned_leave_schedule = qb.DocType("Earned Leave Schedule")
qb.update(earned_leave_schedule).where(
(earned_leave_schedule.parent == allocation.name) & (earned_leave_schedule.allocation_date == today)
).set(earned_leave_schedule.is_allocated, 1).set(earned_leave_schedule.attempted, 1).set(
earned_leave_schedule.allocated_via, "Scheduler"
).set(earned_leave_schedule.number_of_leaves, earned_leaves).run()
(
qb.update(earned_leave_schedule)
.where(
(earned_leave_schedule.parent == allocation.name)
& (earned_leave_schedule.allocation_date == today)
)
.set(earned_leave_schedule.is_allocated, 1)
.set(earned_leave_schedule.attempted, 1)
.set(earned_leave_schedule.allocated_via, allocated_via)
.set(earned_leave_schedule.number_of_leaves, earned_leaves)
.set(earned_leave_schedule.failed, 0)
.set(earned_leave_schedule.failure_reason, "")
).run()


def log_allocation_error(allocation_name, error):
Expand Down
Loading
Loading