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
70 changes: 25 additions & 45 deletions hrms/payroll/doctype/salary_slip/salary_slip.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from hrms.payroll.utils import (
COMPONENT_EVAL_GLOBALS,
COMPONENT_PARENTFIELDS,
SALARY_COMPONENT_VALUES,
_safe_eval,
get_component_eval_context,
throw_error_message,
Expand All @@ -65,7 +66,6 @@
# cache keys
HOLIDAYS_BETWEEN_DATES = "holidays_between_dates"
LEAVE_TYPE_MAP = "leave_type_map"
SALARY_COMPONENT_VALUES = "salary_component_values"
TAX_COMPONENTS_BY_COMPANY = "tax_components_by_company"


Expand Down Expand Up @@ -167,67 +167,47 @@ def autoname(self):

@property
def has_custom_naming_series(self):
if not hasattr(self, "__has_custom_naming_series"):
self.__has_custom_naming_series = frappe.db.exists(
"Property Setter",
{
"doc_type": "Salary Slip",
"property": "autoname",
},
)

return self.__has_custom_naming_series
return frappe.db.exists(
"Property Setter",
{
"doc_type": "Salary Slip",
"property": "autoname",
},
)

@property
def joining_date(self):
if not hasattr(self, "__joining_date"):
self.__joining_date = frappe.get_cached_value(
"Employee",
self.employee,
"date_of_joining",
)

return self.__joining_date
return frappe.get_cached_value(
"Employee",
self.employee,
"date_of_joining",
)

@property
def relieving_date(self):
if not hasattr(self, "__relieving_date"):
self.__relieving_date = frappe.get_cached_value(
"Employee",
self.employee,
"relieving_date",
)

return self.__relieving_date
return frappe.get_cached_value(
"Employee",
self.employee,
"relieving_date",
)

@property
def payroll_period(self):
if not hasattr(self, "__payroll_period"):
self.__payroll_period = get_payroll_period(self.start_date, self.end_date, self.company)

return self.__payroll_period
return get_payroll_period(self.start_date, self.end_date, self.company)

@property
def actual_start_date(self):
if not hasattr(self, "__actual_start_date"):
self.__actual_start_date = self.start_date

if self.joining_date and getdate(self.start_date) < self.joining_date <= getdate(self.end_date):
self.__actual_start_date = self.joining_date
if self.joining_date and getdate(self.start_date) < self.joining_date <= getdate(self.end_date):
return self.joining_date

return self.__actual_start_date
return self.start_date

@property
def actual_end_date(self):
if not hasattr(self, "__actual_end_date"):
self.__actual_end_date = self.end_date

if self.relieving_date and getdate(self.start_date) <= self.relieving_date < getdate(
self.end_date
):
self.__actual_end_date = self.relieving_date
if self.relieving_date and getdate(self.start_date) <= self.relieving_date < getdate(self.end_date):
return self.relieving_date

return self.__actual_end_date
return self.end_date

def validate(self):
self.check_salary_withholding()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ def _get_component_eval_context(self) -> frappe._dict:
period_days = date_diff(dates.end_date, dates.start_date) + 1
data.start_date = dates.start_date
data.end_date = dates.end_date
data.posting_date = dates.end_date
data.payment_days = period_days
data.total_working_days = period_days
data.leave_without_pay = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# See license.txt

import frappe
from frappe.utils import get_first_day, nowdate
from frappe.utils import get_first_day, get_last_day, nowdate

from erpnext.setup.doctype.employee.test_employee import make_employee

Expand All @@ -19,6 +19,20 @@ def _make_component(name, abbr, comp_type="Earning", **flags):
return doc.insert()


def _make_slip_custom_field(fieldname, fieldtype="Float", default=None):
if frappe.db.exists("Custom Field", {"dt": "Salary Slip", "fieldname": fieldname}):
return
return frappe.get_doc(
doctype="Custom Field",
dt="Salary Slip",
fieldname=fieldname,
label=fieldname.replace("_", " ").title(),
fieldtype=fieldtype,
default=default,
insert_after="net_pay",
).insert()


class TestSalaryStructureAssignment(HRMSTestSuite):
def test_ctc_and_annual_gross_exclude_statistical_and_include_employer(self):
"""base=50000; gross = Basic (50000) only - statistical earning (1000) is
Expand Down Expand Up @@ -169,6 +183,104 @@ def test_get_evaluated_components_resolves_uncovered_slip_fields(self):
components = {r.salary_component: r.default_amount for r in ssa.get_evaluated_components().deductions}
self.assertEqual(components["SSA Test YTD Guard"], 50000)

def test_get_evaluated_components_resolves_salary_slip_custom_field(self):
"""A formula referencing a Custom Field on Salary Slip must not raise NameError
when the assignment evaluates it without a slip (#5141)."""
emp = make_employee("ssa_custom_field@test.com", company="_Test Company")
_make_slip_custom_field("custom_shift_allowance_rate")

formula = "base + custom_shift_allowance_rate"
_make_component(
"SSA Test Shift Allowance", "SSATSA", "Earning", amount_based_on_formula=1, formula=formula
)
earnings = [
{
"salary_component": "SSA Test Shift Allowance",
"abbr": "SSATSA",
"amount_based_on_formula": 1,
"formula": formula,
},
]

make_salary_structure(
"SSA Test Custom Field Structure",
"Monthly",
employee=emp,
company="_Test Company",
base=50000,
earnings=earnings,
deductions=[],
)
ssa = frappe.get_last_doc("Salary Structure Assignment", filters={"employee": emp})

components = {r.salary_component: r.default_amount for r in ssa.get_evaluated_components().earnings}
self.assertEqual(components["SSA Test Shift Allowance"], 50000)

def test_get_evaluated_components_uses_declared_field_defaults(self):
"""A slip field's declared default must reach the formula. exchange_rate
defaults to 1.0, so seeding a bare 0 would zero out any formula using it."""
emp = make_employee("ssa_field_default@test.com", company="_Test Company")
_make_slip_custom_field("custom_shift_multiplier", fieldtype="Float", default="2")

formula = "base * exchange_rate * custom_shift_multiplier"
_make_component(
"SSA Test Shift Multiplier", "SSATSM", "Earning", amount_based_on_formula=1, formula=formula
)
earnings = [
{
"salary_component": "SSA Test Shift Multiplier",
"abbr": "SSATSM",
"amount_based_on_formula": 1,
"formula": formula,
},
]

make_salary_structure(
"SSA Test Field Default Structure",
"Monthly",
employee=emp,
company="_Test Company",
base=1000,
earnings=earnings,
deductions=[],
)
ssa = frappe.get_last_doc("Salary Structure Assignment", filters={"employee": emp})

components = {r.salary_component: r.default_amount for r in ssa.get_evaluated_components().earnings}
self.assertEqual(components["SSA Test Shift Multiplier"], 2000)

def test_get_evaluated_components_seeds_posting_date(self):
"""A full cycle seeds posting_date to the cycle end date."""
emp = make_employee("ssa_posting_date@test.com", company="_Test Company")

formula = "base * getdate(posting_date).day"
_make_component(
"SSA Test Posting Bonus", "SSATPOB", "Earning", amount_based_on_formula=1, formula=formula
)
earnings = [
{
"salary_component": "SSA Test Posting Bonus",
"abbr": "SSATPOB",
"amount_based_on_formula": 1,
"formula": formula,
},
]

make_salary_structure(
"SSA Test Posting Date Structure",
"Monthly",
employee=emp,
company="_Test Company",
base=1000,
earnings=earnings,
deductions=[],
)
ssa = frappe.get_last_doc("Salary Structure Assignment", filters={"employee": emp})

expected = 1000 * get_last_day(ssa.from_date).day
components = {r.salary_component: r.default_amount for r in ssa.get_evaluated_components().earnings}
self.assertEqual(components["SSA Test Posting Bonus"], expected)

def test_do_not_include_in_total_earning_is_in_ctc_but_not_gross(self):
"""A 'Do Not Include in Total' earning is part of CTC but not payable - it
must be excluded from annual_gross_earning yet included in ctc."""
Expand Down
47 changes: 18 additions & 29 deletions hrms/payroll/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

import frappe
from frappe import _
from frappe.model import numeric_fieldtypes
from frappe.model.create_new import get_new_doc
from frappe.utils import ceil, floor, get_first_day, get_last_day, get_link_to_form, getdate, rounded


Expand Down Expand Up @@ -57,42 +59,29 @@ def sanitize_expression(string: str | None = None) -> str | None:
}


SALARY_COMPONENT_VALUES = "salary_component_values"


def get_component_abbr_map() -> dict:
"""Cached {salary_component_abbr: 0} map, seeded into the formula eval context
so any component abbreviation referenced in a formula resolves (default 0).

Cache key matches salary_slip.SALARY_COMPONENT_VALUES (shared entry, invalidated
on Salary Component save)."""
Invalidated on Salary Component save."""

def _fetch_component_values():
return {abbr: 0 for abbr in frappe.get_all("Salary Component", pluck="salary_component_abbr")}

return frappe.cache().get_value("salary_component_values", generator=_fetch_component_values)


SALARY_SLIP_EVAL_DEFAULTS = {
"gross_pay": 0,
"net_pay": 0,
"total_deduction": 0,
"rounded_total": 0,
"total_working_hours": 0,
"hour_rate": 0,
"year_to_date": 0,
"month_to_date": 0,
"gross_year_to_date": 0,
"ctc": 0,
"total_earnings": 0,
"income_from_other_sources": 0,
"non_taxable_earnings": 0,
"deductions_before_tax_calculation": 0,
"tax_exemption_declaration": 0,
"standard_tax_exemption_amount": 0,
"annual_taxable_amount": 0,
"income_tax_deducted_till_date": 0,
"future_income_tax_deductions": 0,
"current_month_income_tax": 0,
"total_income_tax": 0,
}
return frappe.cache().get_value(SALARY_COMPONENT_VALUES, generator=_fetch_component_values)


def get_salary_slip_field_defaults() -> dict:
defaults = get_new_doc("Salary Slip", as_dict=True)

for df in frappe.get_meta("Salary Slip").fields:
if df.fieldtype in numeric_fieldtypes and defaults.get(df.fieldname) is None:
defaults[df.fieldname] = 0

return defaults


def get_component_eval_context(employee: str, ssa_as_dict: dict) -> frappe._dict:
Expand All @@ -104,7 +93,7 @@ def get_component_eval_context(employee: str, ssa_as_dict: dict) -> frappe._dict
"""
data = frappe._dict()
data.update(get_component_abbr_map())
data.update(SALARY_SLIP_EVAL_DEFAULTS)
data.update(get_salary_slip_field_defaults())
data.update(ssa_as_dict)
data.update(frappe.get_cached_doc("Employee", employee).as_dict())
return data
Expand Down
Loading