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
2 changes: 1 addition & 1 deletion .github/workflows/review-translation-changes.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ jobs:
pull-requests: write

steps:
- uses: alyf-de/po-review-action@5928f84d6bc9094f9ad6e2c5780f01c0044b800e # v1.1.1
- uses: alyf-de/po-review-action@57fff275f4a0518a2ca55869ec6776fa3813b3d5 # v1.2.0
with:
hidden-po-files: eo.po
24 changes: 7 additions & 17 deletions hrms/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,23 +680,13 @@ def get_employee_advance_balance() -> list[dict]:
# Company
@frappe.whitelist()
def get_company_currencies() -> dict:
Company = frappe.qb.DocType("Company")
Currency = frappe.qb.DocType("Currency")

query = (
frappe.qb.from_(Company)
.join(Currency)
.on(Company.default_currency == Currency.name)
.select(
Company.name,
Company.default_currency,
Currency.name.as_("currency"),
Currency.symbol.as_("symbol"),
)
)

companies = query.run(as_dict=True)
return {company.name: (company.default_currency, company.symbol) for company in companies}
companies = frappe.get_list("Company", fields=["name", "default_currency"])
symbols = get_currency_symbols()
return {
company.name: (company.default_currency, symbols.get(company.default_currency))
for company in companies
if company.default_currency in symbols
}


@frappe.whitelist()
Expand Down
36 changes: 36 additions & 0 deletions hrms/hr/doctype/attendance/attendance.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,13 +384,49 @@ def mark_attendance(
return attendance.name


def validate_employee_access(employees: list[str], company: str | None = None) -> None:
"""Single permission-aware query for all employees, run before any loop."""
if not employees:
return

if any(not isinstance(e, str) or not e for e in employees):
frappe.throw(_("Employee must be a non-empty string."), frappe.ValidationError)

employees = list(dict.fromkeys(employees))

accessible = frappe.get_list(
"Employee", filters={"name": ["in", employees]}, fields=["name", "company"], limit=0
)
company_map = {d.name: d.company for d in accessible}

if denied := [e for e in employees if e not in company_map]:
frappe.throw(
_("You do not have access to Employee {0}").format(", ".join(frappe.bold(e) for e in denied)),
frappe.PermissionError,
)

if company and (mismatched := [e for e, c in company_map.items() if c != company]):
frappe.throw(
_("Employee {0} does not belong to Company {1}").format(
", ".join(frappe.bold(e) for e in mismatched), frappe.bold(company)
)
)


@frappe.whitelist(methods=["POST"])
def mark_bulk_attendance(data: str | dict):
import json

if isinstance(data, str):
data = json.loads(data)
data = frappe._dict(data)
if not isinstance(data.employee, str) or not data.employee:
frappe.throw(_("Employee must be a non-empty string."), frappe.ValidationError)
if not isinstance(data.unmarked_days, list):
frappe.throw(_("Unmarked days must be a list of dates."), frappe.ValidationError)

frappe.has_permission("Attendance", "create", throw=True)
validate_employee_access([data.employee])
if not data.unmarked_days:
frappe.throw(_("Please select a date."))
return
Expand Down
43 changes: 35 additions & 8 deletions hrms/hr/doctype/attendance/test_attendance.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
getdate,
nowdate,
)
from frappe.utils.user import add_role

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

Expand All @@ -32,7 +31,7 @@
create_holiday_list_assignment,
)
from hrms.tests.test_utils import get_first_sunday
from hrms.tests.utils import HRMSTestSuite
from hrms.tests.utils import HRMSTestSuite, make_company_restricted_user, make_user


class TestAttendance(HRMSTestSuite):
Expand Down Expand Up @@ -297,12 +296,10 @@ def test_get_events_returns_attendance(self):
self.assertEqual(attendance_events[0].get("attendance_date"), getdate())

def test_bulk_attendance_marking_through_bg(self):
user1 = "test_bg1@example.com"
user2 = "test_bg2@example.com"
employee1 = make_employee("test_bg1@example.com", company="_Test Company")
employee2 = make_employee("test_bg2@example.com", company="_Test Company")
add_role(user1, "HR Manager")
add_role(user2, "HR Manager")
user1 = make_user("test_bg1@example.com")
user2 = make_user("test_bg2@example.com")
employee1 = make_employee("test_bg_employee1@example.com", company="_Test Company")
employee2 = make_employee("test_bg_employee2@example.com", company="_Test Company")
frappe.flags.test_bg_job = True
frappe.set_user(user1)
data1 = frappe._dict(unmarked_days=[getdate()], employee=employee1, status="Present", shift="")
Expand All @@ -326,5 +323,35 @@ def test_bulk_attendance_marking_through_bg(self):
attendance_records = frappe.get_all("Attendance", {"employee": employee2})
self.assertEqual(len(attendance_records), 1)

def test_bulk_attendance_rejects_malformed_input(self):
employee = make_employee("test_bulk_input@example.com", company="_Test Company")

for bad_employee in (None, "", 1, ["EMP-1"], {"name": employee}):
data = frappe._dict(unmarked_days=[getdate()], employee=bad_employee, status="Present")
self.assertRaises(frappe.ValidationError, mark_bulk_attendance, data)

data = frappe._dict(unmarked_days=str(getdate()), employee=employee, status="Present")
self.assertRaises(frappe.ValidationError, mark_bulk_attendance, data)

self.assertFalse(frappe.db.exists("Attendance", {"employee": employee}))

def test_bulk_attendance_outside_company_scope(self):
user = make_company_restricted_user("test_scoped_bulk_user@example.com", "_Test Company")
other_company_employee = make_employee(
"test_bulk_other_company@example.com", company="_Test Company 1"
)

frappe.set_user(user)
try:
data = frappe._dict(
unmarked_days=[getdate()], employee=other_company_employee, status="Present", shift=""
)
with self.assertRaises(frappe.PermissionError):
mark_bulk_attendance(data)
finally:
frappe.set_user("Administrator")

self.assertFalse(frappe.db.exists("Attendance", {"employee": other_company_employee}))

def tearDown(self):
frappe.db.rollback()
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from frappe.model.document import Document
from frappe.utils import getdate

from hrms.hr.doctype.attendance.attendance import validate_employee_access


class EmployeeAttendanceTool(Document):
# begin: auto-generated types
Expand Down Expand Up @@ -166,6 +168,14 @@ def _get_unmarked_attendance_with_shift(unmarked_attendance, shift, date):
return shiftwise_unmarked_attendance


def get_permission_check_fields(doctype: str) -> list[str]:
"""Columns needed to evaluate document permissions without loading the document."""
link_fields = [
df.fieldname for df in frappe.get_meta(doctype).get_link_fields() if not df.ignore_user_permissions
]
return ["name", "owner", "docstatus", *link_fields]


@frappe.whitelist(methods=["POST"])
def mark_employee_attendance(
employee_list: list | str,
Expand All @@ -183,6 +193,10 @@ def mark_employee_attendance(
if isinstance(employee_list, str):
employee_list = json.loads(employee_list)

if employee_list:
frappe.has_permission("Attendance", "create", throw=True)
validate_employee_access(employee_list, company)

for employee in employee_list:
leave_type = None
if status == "On Leave" and leave_type:
Expand All @@ -207,27 +221,29 @@ def mark_employee_attendance(
if isinstance(half_day_employee_list, str):
half_day_employee_list = json.loads(half_day_employee_list)

validate_employee_access(half_day_employee_list, company)

eligible_attendance = frappe.get_list(
"Attendance",
filters={
"employee": ["in", half_day_employee_list],
"attendance_date": date,
"docstatus": 1,
},
fields=["name", "employee"],
fields=get_permission_check_fields("Attendance"),
limit=0,
)
attendance_map = {d.employee: d.name for d in eligible_attendance}
if not eligible_attendance:
return

for row in eligible_attendance:
# in-memory document, no fetch: the engine needs meta, owner and link values
attendance = frappe.get_doc(doctype="Attendance", **row)
frappe.has_permission("Attendance", "write", doc=attendance, throw=True)

Attendance = frappe.qb.DocType("Attendance")
for employee in half_day_employee_list:
attendance_name = attendance_map.get(employee)
if attendance_name:
frappe.has_permission("Attendance", "write", attendance_name, throw=True)
frappe.qb.update(Attendance).where(
(Attendance.employee == employee)
& (Attendance.attendance_date == date)
& (Attendance.docstatus == 1)
).set(Attendance.half_day_status, half_day_status).set(Attendance.shift, shift).set(
Attendance.late_entry, late_entry or 0
).set(Attendance.early_exit, early_exit or 0).set(Attendance.modify_half_day_status, 0).run()
frappe.qb.update(Attendance).where(
Attendance.name.isin([row.name for row in eligible_attendance])
).set(Attendance.half_day_status, half_day_status).set(Attendance.shift, shift).set(
Attendance.late_entry, late_entry or 0
).set(Attendance.early_exit, early_exit or 0).set(Attendance.modify_half_day_status, 0).run()
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from hrms.hr.doctype.leave_type.test_leave_type import create_leave_type
from hrms.hr.doctype.shift_type.test_shift_type import setup_shift_type
from hrms.payroll.doctype.salary_slip.test_salary_slip import make_leave_application
from hrms.tests.utils import HRMSTestSuite
from hrms.tests.utils import HRMSTestSuite, make_company_restricted_user


class TestEmployeeAttendanceTool(HRMSTestSuite):
Expand Down Expand Up @@ -234,6 +234,107 @@ def test_get_unmarked_attendance_with_shift(self):
self.assertIn(self.employee2.name, filtered)
self.assertNotIn(self.employee3.name, filtered)

def test_mark_attendance_outside_company_scope(self):
user = make_company_restricted_user("test_scoped_hr_user@example.com", "_Test Company")

date = add_days(getdate(), -1)
while is_holiday(employee=self.employee4, date=date):
date = add_days(date, -1)

frappe.set_user(user)
try:
# employee4 belongs to _Test Company 1, outside the user's scope
with self.assertRaises(frappe.PermissionError):
mark_employee_attendance(employee_list=[self.employee4], status="Present", date=date)

with self.assertRaises(frappe.PermissionError):
mark_employee_attendance(
employee_list=[],
status="Present",
date=date,
mark_half_day=True,
half_day_status="Absent",
half_day_employee_list=[self.employee4],
)

# employee3 belongs to _Test Company but the caller claims a different company
with self.assertRaises(frappe.ValidationError):
mark_employee_attendance(
employee_list=[self.employee3], status="Present", date=date, company="_Test Company 1"
)
finally:
frappe.set_user("Administrator")

self.assertFalse(
frappe.db.exists("Attendance", {"employee": self.employee4, "attendance_date": date})
)
self.assertFalse(
frappe.db.exists("Attendance", {"employee": self.employee3, "attendance_date": date})
)

def test_mark_attendance_rejects_non_string_employees(self):
date = add_days(getdate(), -1)
for bad_list in ([None], [1], [{"name": self.employee1}], [self.employee1, ""]):
self.assertRaises(
frappe.ValidationError,
mark_employee_attendance,
employee_list=bad_list,
status="Present",
date=date,
)
self.assertFalse(frappe.db.exists("Attendance", {"attendance_date": date}))

def test_half_day_update_requires_write_access_on_each_record(self):
hr_user = make_company_restricted_user("test_half_day_writer@example.com", "_Test Company 1")

date = add_days(getdate(), -1)
while is_holiday(employee=self.employee1, date=date):
date = add_days(date, -1)

attendance = frappe.get_doc(
{
"doctype": "Attendance",
"employee": self.employee1,
"attendance_date": date,
"status": "Present",
}
).insert()
attendance.submit()

# employee1 sits outside the user's company scope; share the records read-only so
# they are visible to the user without being editable
frappe.share.add("Employee", self.employee1, hr_user, read=1)
frappe.share.add("Attendance", attendance.name, hr_user, read=1)

def mark_half_day():
mark_employee_attendance(
employee_list=[],
status="Present",
date=date,
mark_half_day=True,
half_day_status="Absent",
half_day_employee_list=[self.employee1],
)

frappe.set_user(hr_user)
try:
self.assertRaises(frappe.PermissionError, mark_half_day)
finally:
frappe.set_user("Administrator")

attendance.reload()
self.assertIsNone(attendance.half_day_status)

frappe.share.add("Attendance", attendance.name, hr_user, read=1, write=1)
frappe.set_user(hr_user)
try:
mark_half_day()
finally:
frappe.set_user("Administrator")

attendance.reload()
self.assertEqual(attendance.half_day_status, "Absent")

def test_mark_half_day_attendance_permissions(self):
user_no_role = "test_no_role@example.com"

Expand Down
Loading
Loading