code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import datetime
import frappe
from frappe import _
from frappe.query_builder.functions import Max, Min, Sum
from frappe.utils import (
add_days,
cint,
cstr,
date_diff,
flt,
formatdate,
get_fullname,
get_link_to_form,
getdate,
nowdate,
)
from erpnext.buying.doctype.supplier_scorecard.supplier_scorecard import daterange
from erpnext.setup.doctype.employee.employee import get_holiday_list_for_employee
import hrms
from hrms.hr.doctype.leave_block_list.leave_block_list import get_applicable_block_dates
from hrms.hr.doctype.leave_ledger_entry.leave_ledger_entry import create_leave_ledger_entry
from hrms.hr.utils import (
get_holiday_dates_for_employee,
get_leave_period,
set_employee_name,
share_doc_with_approver,
validate_active_employee,
)
from hrms.mixins.pwa_notifications import PWANotificationsMixin
from hrms.utils import get_employee_email
class LeaveDayBlockedError(frappe.ValidationError):
pass
class OverlapError(frappe.ValidationError):
pass
class AttendanceAlreadyMarkedError(frappe.ValidationError):
pass
class NotAnOptionalHoliday(frappe.ValidationError):
pass
class InsufficientLeaveBalanceError(frappe.ValidationError):
pass
class LeaveAcrossAllocationsError(frappe.ValidationError):
pass
from frappe.model.document import Document
class LeaveApplication(Document, PWANotificationsMixin):
def get_feed(self):
return _("{0}: From {0} of type {1}").format(self.employee_name, self.leave_type)
def after_insert(self):
self.notify_approver()
def validate(self):
validate_active_employee(self.employee)
set_employee_name(self)
self.validate_dates()
self.validate_balance_leaves()
self.validate_leave_overlap()
self.validate_max_days()
self.show_block_day_warning()
self.validate_block_days()
self.validate_salary_processed_days()
self.validate_attendance()
self.set_half_day_date()
if frappe.db.get_value("Leave Type", self.leave_type, "is_optional_leave"):
self.validate_optional_leave()
self.validate_applicable_after()
def on_update(self):
if self.status == "Open" and self.docstatus < 1:
# notify leave approver about creation
if frappe.db.get_single_value("HR Settings", "send_leave_notification"):
self.notify_leave_approver()
share_doc_with_approver(self, self.leave_approver)
self.publish_update()
self.notify_approval_status()
def on_submit(self):
if self.status in ["Open", "Cancelled"]:
frappe.throw(_("Only Leave Applications with status 'Approved' and 'Rejected' can be submitted"))
self.validate_back_dated_application()
self.update_attendance()
# notify leave applier about approval
if frappe.db.get_single_value("HR Settings", "send_leave_notification"):
self.notify_employee()
self.create_leave_ledger_entry()
self.reload()
def before_cancel(self):
self.status = "Cancelled"
def on_cancel(self):
self.create_leave_ledger_entry(submit=False)
# notify leave applier about cancellation
if frappe.db.get_single_value("HR Settings", "send_leave_notification"):
self.notify_employee()
self.cancel_attendance()
self.publish_update()
def after_delete(self):
self.publish_update()
def publish_update(self):
employee_user = frappe.db.get_value("Employee", self.employee, "user_id", cache=True)
hrms.refetch_resource("hrms:my_leaves", employee_user)
def validate_applicable_after(self):
if self.leave_type:
leave_type = frappe.get_doc("Leave Type", self.leave_type)
if leave_type.applicable_after > 0:
date_of_joining = frappe.db.get_value("Employee", self.employee, "date_of_joining")
leave_days = get_approved_leaves_for_period(
self.employee, False, date_of_joining, self.from_date
)
number_of_days = date_diff(getdate(self.from_date), date_of_joining)
if number_of_days >= 0:
holidays = 0
if not frappe.db.get_value("Leave Type", self.leave_type, "include_holiday"):
holidays = get_holidays(self.employee, date_of_joining, self.from_date)
number_of_days = number_of_days - leave_days - holidays
if number_of_days < leave_type.applicable_after:
frappe.throw(
_("{0} applicable after {1} working days").format(
self.leave_type, leave_type.applicable_after
)
)
def validate_dates(self):
if frappe.db.get_single_value("HR Settings", "restrict_backdated_leave_application"):
if self.from_date and getdate(self.from_date) < getdate():
allowed_role = frappe.db.get_single_value(
"HR Settings", "role_allowed_to_create_backdated_leave_application"
)
user = frappe.get_doc("User", frappe.session.user)
user_roles = [d.role for d in user.roles]
if not allowed_role:
frappe.throw(
_("Backdated Leave Application is restricted. Please set the {} in {}").format(
frappe.bold(_("Role Allowed to Create Backdated Leave Application")),
get_link_to_form("HR Settings", "HR Settings", _("HR Settings")),
)
)
if allowed_role and allowed_role not in user_roles:
frappe.throw(
_("Only users with the {0} role can create backdated leave applications").format(
_(allowed_role)
)
)
if self.from_date and self.to_date and (getdate(self.to_date) < getdate(self.from_date)):
frappe.throw(_("To date cannot be before from date"))
if (
self.half_day
and self.half_day_date
and (
getdate(self.half_day_date) < getdate(self.from_date)
or getdate(self.half_day_date) > getdate(self.to_date)
)
):
frappe.throw(_("Half Day Date should be between From Date and To Date"))
if not is_lwp(self.leave_type):
self.validate_dates_across_allocation()
self.validate_back_dated_application()
def validate_dates_across_allocation(self):
if frappe.db.get_value("Leave Type", self.leave_type, "allow_negative"):
return
alloc_on_from_date, alloc_on_to_date = self.get_allocation_based_on_application_dates()
if not (alloc_on_from_date or alloc_on_to_date):
frappe.throw(_("Application period cannot be outside leave allocation period"))
elif self.is_separate_ledger_entry_required(alloc_on_from_date, alloc_on_to_date):
frappe.throw(
_("Application period cannot be across two allocation records"),
exc=LeaveAcrossAllocationsError,
)
def get_allocation_based_on_application_dates(self) -> tuple[dict, dict]:
"""Returns allocation name, from and to dates for application dates"""
def _get_leave_allocation_record(date):
LeaveAllocation = frappe.qb.DocType("Leave Allocation")
allocation = (
frappe.qb.from_(LeaveAllocation)
.select(LeaveAllocation.name, LeaveAllocation.from_date, LeaveAllocation.to_date)
.where(
(LeaveAllocation.employee == self.employee)
& (LeaveAllocation.leave_type == self.leave_type)
& (LeaveAllocation.docstatus == 1)
& ((date >= LeaveAllocation.from_date) & (date <= LeaveAllocation.to_date))
)
).run(as_dict=True)
return allocation and allocation[0]
allocation_based_on_from_date = _get_leave_allocation_record(self.from_date)
allocation_based_on_to_date = _get_leave_allocation_record(self.to_date)
return allocation_based_on_from_date, allocation_based_on_to_date
def validate_back_dated_application(self):
future_allocation = frappe.db.sql(
"""select name, from_date from `tabLeave Allocation`
where employee=%s and leave_type=%s and docstatus=1 and from_date > %s
and carry_forward=1""",
(self.employee, self.leave_type, self.to_date),
as_dict=1,
)
if future_allocation:
frappe.throw(
_(
"Leave cannot be applied/cancelled before {0}, as leave balance has already been carry-forwarded in the future leave allocation record {1}"
).format(formatdate(future_allocation[0].from_date), future_allocation[0].name)
)
def update_attendance(self):
if self.status != "Approved":
return
holiday_dates = []
if not frappe.db.get_value("Leave Type", self.leave_type, "include_holiday"):
holiday_dates = get_holiday_dates_for_employee(self.employee, self.from_date, self.to_date)
for dt in daterange(getdate(self.from_date), getdate(self.to_date)):
date = dt.strftime("%Y-%m-%d")
attendance_name = frappe.db.exists(
"Attendance", dict(employee=self.employee, attendance_date=date, docstatus=("!=", 2))
)
# don't mark attendance for holidays
# if leave type does not include holidays within leaves as leaves
if date in holiday_dates:
if attendance_name:
# cancel and delete existing attendance for holidays
attendance = frappe.get_doc("Attendance", attendance_name)
attendance.flags.ignore_permissions = True
if attendance.docstatus == 1:
attendance.cancel()
frappe.delete_doc("Attendance", attendance_name, force=1)
continue
self.create_or_update_attendance(attendance_name, date)
def create_or_update_attendance(self, attendance_name, date):
status = (
"Half Day" if self.half_day_date and getdate(date) == getdate(self.half_day_date) else "On Leave"
)
if attendance_name:
# update existing attendance, change absent to on leave
doc = frappe.get_doc("Attendance", attendance_name)
doc.db_set({"status": status, "leave_type": self.leave_type, "leave_application": self.name})
else:
# make new attendance and submit it
doc = frappe.new_doc("Attendance")
doc.employee = self.employee
doc.employee_name = self.employee_name
doc.attendance_date = date
doc.company = self.company
doc.leave_type = self.leave_type
doc.leave_application = self.name
doc.status = status
doc.flags.ignore_validate = True
doc.insert(ignore_permissions=True)
doc.submit()
def cancel_attendance(self):
if self.docstatus == 2:
attendance = frappe.db.sql(
"""select name from `tabAttendance` where employee = %s\
and (attendance_date between %s and %s) and docstatus < 2 and status in ('On Leave', 'Half Day')""",
(self.employee, self.from_date, self.to_date),
as_dict=1,
)
for name in attendance:
frappe.db.set_value("Attendance", name, "docstatus", 2)
def validate_salary_processed_days(self):
if not frappe.db.get_value("Leave Type", self.leave_type, "is_lwp"):
return
last_processed_pay_slip = frappe.db.sql(
"""
select start_date, end_date from `tabSalary Slip`
where docstatus = 1 and employee = %s
and ((%s between start_date and end_date) or (%s between start_date and end_date))
order by creation desc limit 1
""",
(self.employee, self.to_date, self.from_date),
)
if last_processed_pay_slip:
frappe.throw(
_(
"Salary already processed for period between {0} and {1}, Leave application period cannot be between this date range."
).format(formatdate(last_processed_pay_slip[0][0]), formatdate(last_processed_pay_slip[0][1]))
)
def show_block_day_warning(self):
block_dates = get_applicable_block_dates(
self.from_date,
self.to_date,
self.employee,
self.company,
all_lists=True,
leave_type=self.leave_type,
)
if block_dates:
frappe.msgprint(_("Warning: Leave application contains following block dates") + ":")
for d in block_dates:
frappe.msgprint(formatdate(d.block_date) + ": " + d.reason)
def validate_block_days(self):
block_dates = get_applicable_block_dates(
self.from_date, self.to_date, self.employee, self.company, leave_type=self.leave_type
)
if block_dates and self.status == "Approved":
frappe.throw(_("You are not authorized to approve leaves on Block Dates"), LeaveDayBlockedError)
def validate_balance_leaves(self):
if self.from_date and self.to_date:
self.total_leave_days = get_number_of_leave_days(
self.employee,
self.leave_type,
self.from_date,
self.to_date,
self.half_day,
self.half_day_date,
)
if self.total_leave_days <= 0:
frappe.throw(
_(
"The day(s) on which you are applying for leave are holidays. You need not apply for leave."
)
)
if not is_lwp(self.leave_type):
leave_balance = get_leave_balance_on(
self.employee,
self.leave_type,
self.from_date,
self.to_date,
consider_all_leaves_in_the_allocation_period=True,
for_consumption=True,
)
self.leave_balance = leave_balance.get("leave_balance")
leave_balance_for_consumption = leave_balance.get("leave_balance_for_consumption")
if self.status != "Rejected" and (
leave_balance_for_consumption < self.total_leave_days or not leave_balance_for_consumption
):
self.show_insufficient_balance_message(leave_balance_for_consumption)
def show_insufficient_balance_message(self, leave_balance_for_consumption: float) -> None:
alloc_on_from_date, alloc_on_to_date = self.get_allocation_based_on_application_dates()
if frappe.db.get_value("Leave Type", self.leave_type, "allow_negative"):
if leave_balance_for_consumption != self.leave_balance:
msg = _("Warning: Insufficient leave balance for Leave Type {0} in this allocation.").format(
frappe.bold(self.leave_type)
)
msg += "<br><br>"
msg += _(
"Actual balances aren't available because the leave application spans over different leave allocations. You can still apply for leaves which would be compensated during the next allocation."
)
else:
msg = _("Warning: Insufficient leave balance for Leave Type {0}.").format(
frappe.bold(self.leave_type)
)
frappe.msgprint(msg, title=_("Warning"), indicator="orange")
else:
frappe.throw(
_("Insufficient leave balance for Leave Type {0}").format(frappe.bold(self.leave_type)),
exc=InsufficientLeaveBalanceError,
title=_("Insufficient Balance"),
)
def validate_leave_overlap(self):
if not self.name:
# hack! if name is null, it could cause problems with !=
self.name = "New Leave Application"
for d in frappe.db.sql(
"""
select
name, leave_type, posting_date, from_date, to_date, total_leave_days, half_day_date
from `tabLeave Application`
where employee = %(employee)s and docstatus < 2 and status in ('Open', 'Approved')
and to_date >= %(from_date)s and from_date <= %(to_date)s
and name != %(name)s""",
{
"employee": self.employee,
"from_date": self.from_date,
"to_date": self.to_date,
"name": self.name,
},
as_dict=1,
):
if (
cint(self.half_day) == 1
and getdate(self.half_day_date) == getdate(d.half_day_date)
and (
flt(self.total_leave_days) == 0.5
or getdate(self.from_date) == getdate(d.to_date)
or getdate(self.to_date) == getdate(d.from_date)
)
):
total_leaves_on_half_day = self.get_total_leaves_on_half_day()
if total_leaves_on_half_day >= 1:
self.throw_overlap_error(d)
else:
self.throw_overlap_error(d)
def throw_overlap_error(self, d):
form_link = get_link_to_form("Leave Application", d.name)
msg = _("Employee {0} has already applied for {1} between {2} and {3} : {4}").format(
self.employee, d["leave_type"], formatdate(d["from_date"]), formatdate(d["to_date"]), form_link
)
frappe.throw(msg, OverlapError)
def get_total_leaves_on_half_day(self):
leave_count_on_half_day_date = frappe.db.sql(
"""select count(name) from `tabLeave Application`
where employee = %(employee)s
and docstatus < 2
and status in ('Open', 'Approved')
and half_day = 1
and half_day_date = %(half_day_date)s
and name != %(name)s""",
{"employee": self.employee, "half_day_date": self.half_day_date, "name": self.name},
)[0][0]
return leave_count_on_half_day_date * 0.5
def validate_max_days(self):
max_days = frappe.db.get_value("Leave Type", self.leave_type, "max_continuous_days_allowed")
if not max_days:
return
details = self.get_consecutive_leave_details()
if details.total_consecutive_leaves > cint(max_days):
msg = _("Leave of type {0} cannot be longer than {1}.").format(
get_link_to_form("Leave Type", self.leave_type), max_days
)
if details.leave_applications:
msg += "<br><br>" + _("Reference: {0}").format(
", ".join(
get_link_to_form("Leave Application", name) for name in details.leave_applications
)
)
frappe.throw(msg, title=_("Maximum Consecutive Leaves Exceeded"))
def get_consecutive_leave_details(self) -> dict:
leave_applications = set()
def _get_first_from_date(reference_date):
"""gets `from_date` of first leave application from previous consecutive leave applications"""
prev_date = add_days(reference_date, -1)
application = frappe.db.get_value(
"Leave Application",
{
"employee": self.employee,
"leave_type": self.leave_type,
"to_date": prev_date,
"docstatus": ["!=", 2],
"status": ["in", ["Open", "Approved"]],
},
["name", "from_date"],
as_dict=True,
)
if application:
leave_applications.add(application.name)
return _get_first_from_date(application.from_date)
return reference_date
def _get_last_to_date(reference_date):
"""gets `to_date` of last leave application from following consecutive leave applications"""
next_date = add_days(reference_date, 1)
application = frappe.db.get_value(
"Leave Application",
{
"employee": self.employee,
"leave_type": self.leave_type,
"from_date": next_date,
"docstatus": ["!=", 2],
"status": ["in", ["Open", "Approved"]],
},
["name", "to_date"],
as_dict=True,
)
if application:
leave_applications.add(application.name)
return _get_last_to_date(application.to_date)
return reference_date
first_from_date = _get_first_from_date(self.from_date)
last_to_date = _get_last_to_date(self.to_date)
total_consecutive_leaves = get_number_of_leave_days(
self.employee, self.leave_type, first_from_date, last_to_date
)
return frappe._dict(
{
"total_consecutive_leaves": total_consecutive_leaves,
"leave_applications": leave_applications,
}
)
def validate_attendance(self):
attendance = frappe.db.sql(
"""select name from `tabAttendance` where employee = %s and (attendance_date between %s and %s)
and status = 'Present' and docstatus = 1""",
(self.employee, self.from_date, self.to_date),
)
if attendance:
frappe.throw(
_("Attendance for employee {0} is already marked for this day").format(self.employee),
AttendanceAlreadyMarkedError,
)
def validate_optional_leave(self):
leave_period = get_leave_period(self.from_date, self.to_date, self.company)
if not leave_period:
frappe.throw(_("Cannot find active Leave Period"))
optional_holiday_list = frappe.db.get_value(
"Leave Period", leave_period[0]["name"], "optional_holiday_list"
)
if not optional_holiday_list:
frappe.throw(
_("Optional Holiday List not set for leave period {0}").format(leave_period[0]["name"])
)
day = getdate(self.from_date)
while day <= getdate(self.to_date):
if not frappe.db.exists(
{"doctype": "Holiday", "parent": optional_holiday_list, "holiday_date": day}
):
frappe.throw(
_("{0} is not in Optional Holiday List").format(formatdate(day)), NotAnOptionalHoliday
)
day = add_days(day, 1)
def set_half_day_date(self):
if self.from_date == self.to_date and self.half_day == 1:
self.half_day_date = self.from_date
if self.half_day == 0:
self.half_day_date = None
def notify_employee(self):
employee_email = get_employee_email(self.employee)
if not employee_email:
return
parent_doc = frappe.get_doc("Leave Application", self.name)
args = parent_doc.as_dict()
template = frappe.db.get_single_value("HR Settings", "leave_status_notification_template")
if not template:
frappe.msgprint(_("Please set default template for Leave Status Notification in HR Settings."))
return
email_template = frappe.get_doc("Email Template", template)
subject = frappe.render_template(email_template.subject, args)
message = frappe.render_template(email_template.response_, args)
self.notify(
{
# for post in messages
"message": message,
"message_to": employee_email,
# for email
"subject": subject,
"notify": "employee",
}
)
def notify_leave_approver(self):
if self.leave_approver:
parent_doc = frappe.get_doc("Leave Application", self.name)
args = parent_doc.as_dict()
template = frappe.db.get_single_value("HR Settings", "leave_approval_notification_template")
if not template:
frappe.msgprint(
_("Please set default template for Leave Approval Notification in HR Settings.")
)
return
email_template = frappe.get_doc("Email Template", template)
subject = frappe.render_template(email_template.subject, args)
message = frappe.render_template(email_template.response_, args)
self.notify(
{
# for post in messages
"message": message,
"message_to": self.leave_approver,
# for email
"subject": subject,
}
)
def notify(self, args):
args = frappe._dict(args)
# args -> message, message_to, subject
if cint(self.follow_via_email):
contact = args.message_to
if not isinstance(contact, list):
if not args.notify == "employee":
contact = frappe.get_doc("User", contact).email or contact
sender = dict()
sender["email"] = frappe.get_doc("User", frappe.session.user).email
sender["full_name"] = get_fullname(sender["email"])
try:
frappe.sendmail(
recipients=contact,
sender=sender["email"],
subject=args.subject,
message=args.message,
)
frappe.msgprint(_("Email sent to {0}").format(contact))
except frappe.OutgoingEmailError:
pass
def create_leave_ledger_entry(self, submit=True):
if self.status != "Approved" and submit:
return
expiry_date = get_allocation_expiry_for_cf_leaves(
self.employee, self.leave_type, self.to_date, self.from_date
)
lwp = frappe.db.get_value("Leave Type", self.leave_type, "is_lwp")
if expiry_date:
self.create_ledger_entry_for_intermediate_allocation_expiry(expiry_date, submit, lwp)
else:
alloc_on_from_date, alloc_on_to_date = self.get_allocation_based_on_application_dates()
if self.is_separate_ledger_entry_required(alloc_on_from_date, alloc_on_to_date):
# required only if negative balance is allowed for leave type
# else will be stopped in validation itself
self.create_separate_ledger_entries(alloc_on_from_date, alloc_on_to_date, submit, lwp)
else:
raise_exception = False if frappe.flags.in_patch else True
args = dict(
leaves=self.total_leave_days * -1,
from_date=self.from_date,
to_date=self.to_date,
is_lwp=lwp,
holiday_list=get_holiday_list_for_employee(self.employee, raise_exception=raise_exception)
or "",
)
create_leave_ledger_entry(self, args, submit)
def is_separate_ledger_entry_required(
self, alloc_on_from_date: dict | None = None, alloc_on_to_date: dict | None = None
) -> bool:
"""Checks if application dates fall in separate allocations"""
if (
(alloc_on_from_date and not alloc_on_to_date)
or (not alloc_on_from_date and alloc_on_to_date)
or (alloc_on_from_date and alloc_on_to_date and alloc_on_from_date.name != alloc_on_to_date.name)
):
return True
return False
def create_separate_ledger_entries(self, alloc_on_from_date, alloc_on_to_date, submit, lwp):
"""Creates separate ledger entries for application period falling into separate allocations"""
# for creating separate ledger entries existing allocation periods should be consecutive
if (
submit
and alloc_on_from_date
and alloc_on_to_date
and add_days(alloc_on_from_date.to_date, 1) != alloc_on_to_date.from_date
):
frappe.throw(
_(
"Leave Application period cannot be across two non-consecutive leave allocations {0} and {1}."
).format(
get_link_to_form("Leave Allocation", alloc_on_from_date.name),
get_link_to_form("Leave Allocation", alloc_on_to_date),
)
)
raise_exception = False if frappe.flags.in_patch else True
if alloc_on_from_date:
first_alloc_end = alloc_on_from_date.to_date
second_alloc_start = add_days(alloc_on_from_date.to_date, 1)
else:
first_alloc_end = add_days(alloc_on_to_date.from_date, -1)
second_alloc_start = alloc_on_to_date.from_date
leaves_in_first_alloc = get_number_of_leave_days(
self.employee,
self.leave_type,
self.from_date,
first_alloc_end,
self.half_day,
self.half_day_date,
)
leaves_in_second_alloc = get_number_of_leave_days(
self.employee,
self.leave_type,
second_alloc_start,
self.to_date,
self.half_day,
self.half_day_date,
)
args = dict(
is_lwp=lwp,
holiday_list=get_holiday_list_for_employee(self.employee, raise_exception=raise_exception) or "",
)
if leaves_in_first_alloc:
args.update(
dict(from_date=self.from_date, to_date=first_alloc_end, leaves=leaves_in_first_alloc * -1)
)
create_leave_ledger_entry(self, args, submit)
if leaves_in_second_alloc:
args.update(
dict(from_date=second_alloc_start, to_date=self.to_date, leaves=leaves_in_second_alloc * -1)
)
create_leave_ledger_entry(self, args, submit)
def create_ledger_entry_for_intermediate_allocation_expiry(self, expiry_date, submit, lwp):
"""Splits leave application into two ledger entries to consider expiry of allocation"""
raise_exception = False if frappe.flags.in_patch else True
leaves = get_number_of_leave_days(
self.employee, self.leave_type, self.from_date, expiry_date, self.half_day, self.half_day_date
)
if leaves:
args = dict(
from_date=self.from_date,
to_date=expiry_date,
leaves=leaves * -1,
is_lwp=lwp,
holiday_list=get_holiday_list_for_employee(self.employee, raise_exception=raise_exception)
or "",
)
create_leave_ledger_entry(self, args, submit)
if getdate(expiry_date) != getdate(self.to_date):
start_date = add_days(expiry_date, 1)
leaves = get_number_of_leave_days(
self.employee, self.leave_type, start_date, self.to_date, self.half_day, self.half_day_date
)
if leaves:
args.update(dict(from_date=start_date, to_date=self.to_date, leaves=leaves * -1))
create_leave_ledger_entry(self, args, submit)
def get_allocation_expiry_for_cf_leaves(
employee: str, leave_type: str, to_date: datetime.date, from_date: datetime.date
) -> str:
"""Returns expiry of carry forward allocation in leave ledger entry"""
Ledger = frappe.qb.DocType("Leave Ledger Entry")
expiry = (
frappe.qb.from_(Ledger)
.select(Ledger.to_date)
.where(
(Ledger.employee == employee)
& (Ledger.leave_type == leave_type)
& (Ledger.is_carry_forward == 1)
& (Ledger.transaction_type == "Leave Allocation")
& (Ledger.to_date.between(from_date, to_date))
& (Ledger.docstatus == 1)
)
.limit(1)
).run()
return expiry[0][0] if expiry else ""
@frappe.whitelist()
def get_number_of_leave_days(
employee: str,
leave_type: str,
from_date: datetime.date,
to_date: datetime.date,
half_day: int | str | None = None,
half_day_date: datetime.date | str | None = None,
holiday_list: str | None = None,
) -> float:
"""Returns number of leave days between 2 dates after considering half day and holidays
(Based on the include_holiday setting in Leave Type)"""
number_of_days = 0
if cint(half_day) == 1:
if getdate(from_date) == getdate(to_date):
number_of_days = 0.5
elif half_day_date and getdate(from_date) <= getdate(half_day_date) <= getdate(to_date):
number_of_days = date_diff(to_date, from_date) + 0.5
else:
number_of_days = date_diff(to_date, from_date) + 1
else:
number_of_days = date_diff(to_date, from_date) + 1
if not frappe.db.get_value("Leave Type", leave_type, "include_holiday"):
number_of_days = flt(number_of_days) - flt(
get_holidays(employee, from_date, to_date, holiday_list=holiday_list)
)
return number_of_days
@frappe.whitelist()
def get_leave_details(employee, date):
allocation_records = get_leave_allocation_records(employee, date)
leave_allocation = {}
precision = cint(frappe.db.get_single_value("System Settings", "float_precision", cache=True))
for d in allocation_records:
allocation = allocation_records.get(d, frappe._dict())
remaining_leaves = get_leave_balance_on(
employee, d, date, to_date=allocation.to_date, consider_all_leaves_in_the_allocation_period=True
)
end_date = allocation.to_date
leaves_taken = get_leaves_for_period(employee, d, allocation.from_date, end_date) * -1
leaves_pending = get_leaves_pending_approval_for_period(employee, d, allocation.from_date, end_date)
expired_leaves = allocation.total_leaves_allocated - (remaining_leaves + leaves_taken)
leave_allocation[d] = {
"total_leaves": flt(allocation.total_leaves_allocated, precision),
"expired_leaves": flt(expired_leaves, precision) if expired_leaves > 0 else 0,
"leaves_taken": flt(leaves_taken, precision),
"leaves_pending_approval": flt(leaves_pending, precision),
"remaining_leaves": flt(remaining_leaves, precision),
}
# is used in set query
lwp = frappe.get_list("Leave Type", filters={"is_lwp": 1}, pluck="name")
return {
"leave_allocation": leave_allocation,
"leave_approver": get_leave_approver(employee),
"lwps": lwp,
}
@frappe.whitelist()
def get_leave_balance_on(
employee: str,
leave_type: str,
date: datetime.date,
to_date: datetime.date | None = None,
consider_all_leaves_in_the_allocation_period: bool = False,
for_consumption: bool = False,
):
"""
Returns leave balance till date
:param employee: employee name
:param leave_type: leave type
:param date: date to check balance on
:param to_date: future date to check for allocation expiry
:param consider_all_leaves_in_the_allocation_period: consider all leaves taken till the allocation end date
:param for_consumption: flag to check if leave balance is required for consumption or display
eg: employee has leave balance = 10 but allocation is expiring in 1 day so employee can only consume 1 leave
in this case leave_balance = 10 but leave_balance_for_consumption = 1
if True, returns a dict eg: {'leave_balance': 10, 'leave_balance_for_consumption': 1}
else, returns leave_balance (in this case 10)
"""
if not to_date:
to_date = nowdate()
allocation_records = get_leave_allocation_records(employee, date, leave_type)
allocation = allocation_records.get(leave_type, frappe._dict())
end_date = allocation.to_date if cint(consider_all_leaves_in_the_allocation_period) else date
cf_expiry = get_allocation_expiry_for_cf_leaves(employee, leave_type, to_date, allocation.from_date)
leaves_taken = get_leaves_for_period(employee, leave_type, allocation.from_date, end_date)
remaining_leaves = get_remaining_leaves(allocation, leaves_taken, date, cf_expiry)
if for_consumption:
return remaining_leaves
else:
return remaining_leaves.get("leave_balance")
def get_leave_allocation_records(employee, date, leave_type=None):
"""Returns the total allocated leaves and carry forwarded leaves based on ledger entries"""
Ledger = frappe.qb.DocType("Leave Ledger Entry")
LeaveAllocation = frappe.qb.DocType("Leave Allocation")
cf_leave_case = frappe.qb.terms.Case().when(Ledger.is_carry_forward == "1", Ledger.leaves).else_(0)
sum_cf_leaves = Sum(cf_leave_case).as_("cf_leaves")
new_leaves_case = frappe.qb.terms.Case().when(Ledger.is_carry_forward == "0", Ledger.leaves).else_(0)
sum_new_leaves = Sum(new_leaves_case).as_("new_leaves")
query = (
frappe.qb.from_(Ledger)
.inner_join(LeaveAllocation)
.on(Ledger.transaction_name == LeaveAllocation.name)
.select(
sum_cf_leaves,
sum_new_leaves,
Min(Ledger.from_date).as_("from_date"),
Max(Ledger.to_date).as_("to_date"),
Ledger.leave_type,
Ledger.employee,
)
.where(
(Ledger.from_date <= date)
& (Ledger.docstatus == 1)
& (Ledger.transaction_type == "Leave Allocation")
& (Ledger.employee == employee)
& (Ledger.is_expired == 0)
& (Ledger.is_lwp == 0)
& (
# newly allocated leave's end date is same as the leave allocation's to date
((Ledger.is_carry_forward == 0) & (Ledger.to_date >= date))
# carry forwarded leave's end date won't be same as the leave allocation's to date
# it's between the leave allocation's from and to date
| (
(Ledger.is_carry_forward == 1)
& (Ledger.to_date.between(LeaveAllocation.from_date, LeaveAllocation.to_date))
# only consider cf leaves from current allocation
& (LeaveAllocation.from_date <= date)
& (date <= LeaveAllocation.to_date)
)
)
)
)
if leave_type:
query = query.where(Ledger.leave_type == leave_type)
query = query.groupby(Ledger.employee, Ledger.leave_type)
allocation_details = query.run(as_dict=True)
allocated_leaves = frappe._dict()
for d in allocation_details:
allocated_leaves.setdefault(
d.leave_type,
frappe._dict(
{
"from_date": d.from_date,
"to_date": d.to_date,
"total_leaves_allocated": flt(d.cf_leaves) + flt(d.new_leaves),
"unused_leaves": d.cf_leaves,
"new_leaves_allocated": d.new_leaves,
"leave_type": d.leave_type,
"employee": d.employee,
}
),
)
return allocated_leaves
def get_leaves_pending_approval_for_period(
employee: str, leave_type: str, from_date: datetime.date, to_date: datetime.date
) -> float:
"""Returns leaves that are pending for approval"""
leaves = frappe.get_all(
"Leave Application",
filters={"employee": employee, "leave_type": leave_type, "status": "Open"},
or_filters={
"from_date": ["between", (from_date, to_date)],
"to_date": ["between", (from_date, to_date)],
},
fields=["SUM(total_leave_days) as leaves"],
)[0]
return leaves["leaves"] if leaves["leaves"] else 0.0
def get_remaining_leaves(
allocation: dict, leaves_taken: float, date: str, cf_expiry: str
) -> dict[str, float]:
"""Returns a dict of leave_balance and leave_balance_for_consumption
leave_balance returns the available leave balance
leave_balance_for_consumption returns the minimum leaves remaining after comparing with remaining days for allocation expiry
"""
def _get_remaining_leaves(remaining_leaves, end_date):
"""Returns minimum leaves remaining after comparing with remaining days for allocation expiry"""
if remaining_leaves > 0:
remaining_days = date_diff(end_date, date) + 1
remaining_leaves = min(remaining_days, remaining_leaves)
return remaining_leaves
if cf_expiry and allocation.unused_leaves:
# allocation contains both carry forwarded and new leaves
new_leaves_taken, cf_leaves_taken = get_new_and_cf_leaves_taken(allocation, cf_expiry)
if getdate(date) > getdate(cf_expiry):
# carry forwarded leaves have expired
cf_leaves = remaining_cf_leaves = 0
else:
cf_leaves = flt(allocation.unused_leaves) + flt(cf_leaves_taken)
remaining_cf_leaves = _get_remaining_leaves(cf_leaves, cf_expiry)
# new leaves allocated - new leaves taken + cf leave balance
# Note: `new_leaves_taken` is added here because its already a -ve number in the ledger
leave_balance = (flt(allocation.new_leaves_allocated) + flt(new_leaves_taken)) + flt(cf_leaves)
leave_balance_for_consumption = (flt(allocation.new_leaves_allocated) + flt(new_leaves_taken)) + flt(
remaining_cf_leaves
)
else:
# allocation only contains newly allocated leaves
leave_balance = leave_balance_for_consumption = flt(allocation.total_leaves_allocated) + flt(
leaves_taken
)
remaining_leaves = _get_remaining_leaves(leave_balance_for_consumption, allocation.to_date)
return frappe._dict(leave_balance=leave_balance, leave_balance_for_consumption=remaining_leaves)
def get_new_and_cf_leaves_taken(allocation: dict, cf_expiry: str) -> tuple[float, float]:
"""returns new leaves taken and carry forwarded leaves taken within an allocation period based on cf leave expiry"""
cf_leaves_taken = get_leaves_for_period(
allocation.employee, allocation.leave_type, allocation.from_date, cf_expiry
)
new_leaves_taken = get_leaves_for_period(
allocation.employee, allocation.leave_type, add_days(cf_expiry, 1), allocation.to_date
)
# using abs because leaves taken is a -ve number in the ledger
if abs(cf_leaves_taken) > allocation.unused_leaves:
# adjust the excess leaves in new_leaves_taken
new_leaves_taken += -(abs(cf_leaves_taken) - allocation.unused_leaves)
cf_leaves_taken = -allocation.unused_leaves
return new_leaves_taken, cf_leaves_taken
def get_leaves_for_period(
employee: str,
leave_type: str,
from_date: datetime.date,
to_date: datetime.date,
skip_expired_leaves: bool = True,
) -> float:
leave_entries = get_leave_entries(employee, leave_type, from_date, to_date)
leave_days = 0
for leave_entry in leave_entries:
inclusive_period = leave_entry.from_date >= getdate(from_date) and leave_entry.to_date <= getdate(
to_date
)
if inclusive_period and leave_entry.transaction_type == "Leave Encashment":
leave_days += leave_entry.leaves
elif (
inclusive_period
and leave_entry.transaction_type == "Leave Allocation"
and leave_entry.is_expired
and not skip_expired_leaves
):
leave_days += leave_entry.leaves
elif leave_entry.transaction_type == "Leave Application":
if leave_entry.from_date < getdate(from_date):
leave_entry.from_date = from_date
if leave_entry.to_date > getdate(to_date):
leave_entry.to_date = to_date
half_day = 0
half_day_date = None
# fetch half day date for leaves with half days
if leave_entry.leaves % 1:
half_day = 1
half_day_date = frappe.db.get_value(
"Leave Application", leave_entry.transaction_name, "half_day_date"
)
leave_days += (
get_number_of_leave_days(
employee,
leave_type,
leave_entry.from_date,
leave_entry.to_date,
half_day,
half_day_date,
holiday_list=leave_entry.holiday_list,
)
* -1
)
return leave_days
def get_leave_entries(employee, leave_type, from_date, to_date):
"""Returns leave entries between from_date and to_date."""
return frappe.db.sql(
"""
SELECT
employee, leave_type, from_date, to_date, leaves, transaction_name, transaction_type, holiday_list,
is_carry_forward, is_expired
FROM `tabLeave Ledger Entry`
WHERE employee=%(employee)s AND leave_type=%(leave_type)s
AND docstatus=1
AND (leaves<0
OR is_expired=1)
AND (from_date between %(from_date)s AND %(to_date)s
OR to_date between %(from_date)s AND %(to_date)s
OR (from_date < %(from_date)s AND to_date > %(to_date)s))
""",
{"from_date": from_date, "to_date": to_date, "employee": employee, "leave_type": leave_type},
as_dict=1,
)
@frappe.whitelist()
def get_holidays(employee, from_date, to_date, holiday_list=None):
"""get holidays between two dates for the given employee"""
if not holiday_list:
holiday_list = get_holiday_list_for_employee(employee)
holidays = frappe.db.sql(
"""select count(distinct holiday_date) from `tabHoliday` h1, `tabHoliday List` h2
where h1.parent = h2.name and h1.holiday_date between %s and %s
and h2.name = %s""",
(from_date, to_date, holiday_list),
)[0][0]
return holidays
def is_lwp(leave_type):
lwp = frappe.db.sql("select is_lwp from `tabLeave Type` where name = %s", leave_type)
return lwp and cint(lwp[0][0]) or 0
@frappe.whitelist()
def get_events(start, end, filters=None):
import json
filters = json.loads(filters)
for idx, filter in enumerate(filters):
# taking relevant fields from the list [doctype, fieldname, condition, value, hidden]
filters[idx] = filter[1:-1]
events = []
employee = frappe.db.get_value(
"Employee", filters={"user_id": frappe.session.user}, fieldname=["name", "company"], as_dict=True
)
if employee:
employee, company = employee.name, employee.company
else:
employee = ""
company = frappe.db.get_value("Global Defaults", None, "default_company")
# show department leaves for employee
if "Employee" in frappe.get_roles():
add_department_leaves(events, start, end, employee, company)
add_leaves(events, start, end, filters)
add_block_dates(events, start, end, employee, company)
add_holidays(events, start, end, employee, company)
return events
def add_department_leaves(events, start, end, employee, company):
if department := frappe.db.get_value("Employee", employee, "department"):
department_employees = frappe.get_list(
"Employee", filters={"department": department, "company": company}, pluck="name"
)
filters = [["employee", "in", department_employees]]
add_leaves(events, start, end, filters=filters)
def add_leaves(events, start, end, filters=None):
if not filters:
filters = []
filters.extend(
[
["from_date", "<=", getdate(end)],
["to_date", ">=", getdate(start)],
["status", "in", ["Approved", "Open"]],
["docstatus", "<", 2],
]
)
fields = [
"name",
"from_date",
"to_date",
"color",
"docstatus",
"employee_name",
"leave_type",
"(1) as allDay",
"'Leave Application' as doctype",
]
show_leaves_of_all_members = frappe.db.get_single_value(
"HR Settings", "show_leaves_of_all_department_members_in_calendar"
)
if cint(show_leaves_of_all_members):
leave_applications = frappe.get_all("Leave Application", filters=filters, fields=fields)
else:
leave_applications = frappe.get_list("Leave Application", filters=filters, fields=fields)
for d in leave_applications:
d["title"] = f"{d['employee_name']} ({d['leave_type']})"
del d["employee_name"]
del d["leave_type"]
if d not in events:
events.append(d)
def add_block_dates(events, start, end, employee, company):
cnt = 0
block_dates = get_applicable_block_dates(start, end, employee, company, all_lists=True)
for block_date in block_dates:
events.append(
{
"doctype": "Leave Block List Date",
"from_date": block_date.block_date,
"to_date": block_date.block_date,
"title": _("Leave Blocked") + ": " + block_date.reason,
"name": "_" + str(cnt),
"allDay": 1,
}
)
cnt += 1
def add_holidays(events, start, end, employee, company):
applicable_holiday_list = get_holiday_list_for_employee(employee, company)
if not applicable_holiday_list:
return
for holiday in frappe.db.sql(
"""select name, holiday_date, description
from `tabHoliday` where parent=%s and holiday_date between %s and %s""",
(applicable_holiday_list, start, end),
as_dict=True,
):
events.append(
{
"doctype": "Holiday",
"from_date": holiday.holiday_date,
"to_date": holiday.holiday_date,
"title": _("Holiday") + ": " + cstr(holiday.description),
"name": holiday.name,
"allDay": 1,
}
)
@frappe.whitelist()
def get_mandatory_approval(doctype):
mandatory = ""
if doctype == "Leave Application":
mandatory = frappe.db.get_single_value("HR Settings", "leave_approver_mandatory_in_leave_application")
else:
mandatory = frappe.db.get_single_value("HR Settings", "expense_approver_mandatory_in_expense_claim")
return mandatory
def get_approved_leaves_for_period(employee, leave_type, from_date, to_date):
LeaveApplication = frappe.qb.DocType("Leave Application")
query = (
frappe.qb.from_(LeaveApplication)
.select(
LeaveApplication.employee,
LeaveApplication.leave_type,
LeaveApplication.from_date,
LeaveApplication.to_date,
LeaveApplication.total_leave_days,
)
.where(
(LeaveApplication.employee == employee)
& (LeaveApplication.docstatus == 1)
& (LeaveApplication.status == "Approved")
& (
(LeaveApplication.from_date.between(from_date, to_date))
| (LeaveApplication.to_date.between(from_date, to_date))
| ((LeaveApplication.from_date < from_date) & (LeaveApplication.to_date > to_date))
)
)
)
if leave_type:
query = query.where(LeaveApplication.leave_type == leave_type)
leave_applications = query.run(as_dict=True)
leave_days = 0
for leave_app in leave_applications:
if leave_app.from_date >= getdate(from_date) and leave_app.to_date <= getdate(to_date):
leave_days += leave_app.total_leave_days
else:
if leave_app.from_date < getdate(from_date):
leave_app.from_date = from_date
if leave_app.to_date > getdate(to_date):
leave_app.to_date = to_date
leave_days += get_number_of_leave_days(
employee, leave_type, leave_app.from_date, leave_app.to_date
)
return leave_days
@frappe.whitelist()
def get_leave_approver(employee):
leave_approver, department = frappe.db.get_value("Employee", employee, ["leave_approver", "department"])
if not leave_approver and department:
leave_approver = frappe.db.get_value(
"Department Approver",
{"parent": department, "parentfield": "leave_approvers", "idx": 1},
"approver",
)
return leave_approver
def on_doctype_update():
frappe.db.add_index("Leave Application", ["employee", "from_date", "to_date"])
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_application/leave_application.py
|
Python
|
agpl-3.0
| 44,772
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.views.calendar["Leave Application"] = {
field_map: {
start: "from_date",
end: "to_date",
id: "name",
title: "title",
docstatus: 1,
color: "color",
},
options: {
header: {
left: "prev,next today",
center: "title",
right: "month",
},
},
get_events_method: "hrms.hr.doctype.leave_application.leave_application.get_events",
};
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_application/leave_application_calendar.js
|
JavaScript
|
agpl-3.0
| 490
|
{% if not jQuery.isEmptyObject(data) %}
<table class="table table-bordered small">
<thead>
<tr>
<th style="width: 16%">{{ __("Leave Type") }}</th>
<th style="width: 16%" class="text-right">{{ __("Total Allocated Leaves") }}</th>
<th style="width: 16%" class="text-right">{{ __("Expired Leaves") }}</th>
<th style="width: 16%" class="text-right">{{ __("Used Leaves") }}</th>
<th style="width: 16%" class="text-right">{{ __("Leaves Pending Approval") }}</th>
<th style="width: 16%" class="text-right">{{ __("Available Leaves") }}</th>
</tr>
</thead>
<tbody>
{% for(const [key, value] of Object.entries(data)) { %}
{% let color = cint(value["remaining_leaves"]) > 0 ? "green" : "red" %}
<tr>
<td> {%= key %} </td>
<td class="text-right"> {%= value["total_leaves"] %} </td>
<td class="text-right"> {%= value["expired_leaves"] %} </td>
<td class="text-right"> {%= value["leaves_taken"] %} </td>
<td class="text-right"> {%= value["leaves_pending_approval"] %} </td>
<td class="text-right" style="color: {{ color }}"> {%= value["remaining_leaves"] %} </td>
</tr>
{% } %}
</tbody>
</table>
{% else %}
<p style="margin-top: 30px;"> {{ __("No leaves have been allocated.") }} </p>
{% endif %}
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_application/leave_application_dashboard.html
|
HTML
|
agpl-3.0
| 1,247
|
from frappe import _
def get_data():
return {
"fieldname": "leave_application",
"transactions": [{"items": ["Attendance"]}],
"reports": [{"label": _("Reports"), "items": ["Employee Leave Balance"]}],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_application/leave_application_dashboard.py
|
Python
|
agpl-3.0
| 212
|
<h1>Leave Application Notification</h1>
<h3>Details:</h3>
<table class="table table-bordered small" style="max-width: 500px;">
<tr>
<td>Employee</td>
<td>{{employee_name}}</td>
</tr>
<tr>
<td>Leave Type</td>
<td>{{leave_type}}</td>
</tr>
<tr>
<td>From Date</td>
<td>{{from_date}}</td>
</tr>
<tr>
<td>To Date</td>
<td>{{to_date}}</td>
</tr>
<tr>
<td>Status</td>
<td>{{status}}</td>
</tr>
</table>
{% set doc_link = frappe.utils.get_url_to_form('Leave Application', name) %}
<br><br>
<a class="btn btn-primary" href="{{ doc_link }}" target="_blank">{{ _('Open Now') }}</a>
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_application/leave_application_email_template.html
|
HTML
|
agpl-3.0
| 628
|
frappe.listview_settings["Leave Application"] = {
add_fields: [
"leave_type",
"employee",
"employee_name",
"total_leave_days",
"from_date",
"to_date",
],
has_indicator_for_draft: 1,
get_indicator: function (doc) {
const status_color = {
Approved: "green",
Rejected: "red",
Open: "orange",
Draft: "red",
Cancelled: "red",
Submitted: "blue",
};
const status =
!doc.docstatus && ["Approved", "Rejected"].includes(doc.status) ? "Draft" : doc.status;
return [__(status), status_color[status], "status,=," + doc.status];
},
};
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_application/leave_application_list.js
|
JavaScript
|
agpl-3.0
| 567
|
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Leave Block List", {
add_day_wise_dates: function (frm) {
let d = new frappe.ui.Dialog({
title: "Add Leave Block Dates",
fields: [
{
label: "Start Date",
fieldname: "start_date",
fieldtype: "Date",
reqd: 1,
},
{
fieldname: "col_break_0",
fieldtype: "Column Break",
},
{
label: "End Date",
fieldname: "end_date",
fieldtype: "Date",
reqd: 1,
},
{
fieldname: "sec_break_0",
fieldtype: "Section Break",
},
{
fieldname: "days",
fieldtype: "MultiCheck",
select_all: true,
columns: 3,
reqd: 1,
options: [
{
label: __("Monday"),
value: "Monday",
checked: 0,
},
{
label: __("Tuesday"),
value: "Tuesday",
checked: 0,
},
{
label: __("Wednesday"),
value: "Wednesday",
checked: 0,
},
{
label: __("Thursday"),
value: "Thursday",
checked: 0,
},
{
label: __("Friday"),
value: "Friday",
checked: 0,
},
{
label: __("Saturday"),
value: "Saturday",
checked: 0,
},
{
label: __("Sunday"),
value: "Sunday",
checked: 0,
},
],
},
{
fieldname: "sec_break_0",
fieldtype: "Section Break",
},
{
label: "Reason",
fieldname: "reason",
fieldtype: "Small Text",
reqd: 1,
},
],
primary_action_label: "Add",
primary_action(values) {
frm.call("set_weekly_off_dates", {
start_date: d.get_value("start_date"),
end_date: d.get_value("end_date"),
reason: d.get_value("reason"),
days: d.get_value("days"),
});
frm.dirty();
d.hide();
},
});
d.show();
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_block_list/leave_block_list.js
|
JavaScript
|
agpl-3.0
| 1,932
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import getdate
class LeaveBlockList(Document):
def validate(self):
dates = []
for d in self.get("leave_block_list_dates"):
# date is not repeated
if d.block_date in dates:
frappe.msgprint(_("Date is repeated") + ":" + d.block_date, raise_exception=1)
dates.append(d.block_date)
@frappe.whitelist()
def set_weekly_off_dates(self, start_date, end_date, days, reason):
date_list = self.get_block_dates_from_date(start_date, end_date, days)
for date in date_list:
self.append("leave_block_list_dates", {"block_date": date, "reason": reason})
def get_block_dates_from_date(self, start_date, end_date, days):
start_date, end_date = getdate(start_date), getdate(end_date)
import calendar
from datetime import timedelta
date_list = []
existing_date_list = [getdate(d.block_date) for d in self.get("leave_block_list_dates")]
while start_date <= end_date:
if start_date not in existing_date_list and calendar.day_name[start_date.weekday()] in days:
date_list.append(start_date)
start_date += timedelta(days=1)
return date_list
def get_applicable_block_dates(
from_date, to_date, employee=None, company=None, all_lists=False, leave_type=None
):
return frappe.db.get_all(
"Leave Block List Date",
filters={
"parent": ["IN", get_applicable_block_lists(employee, company, all_lists, leave_type)],
"block_date": ["BETWEEN", [getdate(from_date), getdate(to_date)]],
},
fields=["block_date", "reason"],
)
def get_applicable_block_lists(employee=None, company=None, all_lists=False, leave_type=None):
block_lists = []
def add_block_list(block_list):
for d in block_list:
if all_lists or not is_user_in_allow_list(d):
block_lists.append(d)
if not employee:
employee = frappe.db.get_value("Employee", {"user_id": frappe.session.user})
if not company and employee:
company = frappe.db.get_value("Employee", employee, "company")
if company:
# global
conditions = {"applies_to_all_departments": 1, "company": company}
if leave_type:
conditions["leave_type"] = ["IN", (leave_type, "", None)]
add_block_list(frappe.db.get_all("Leave Block List", filters=conditions, pluck="name"))
if employee:
# per department
department = frappe.db.get_value("Employee", employee, "department")
if department:
block_list = frappe.db.get_value("Department", department, "leave_block_list")
block_list_leave_type = frappe.db.get_value("Leave Block List", block_list, "leave_type")
if not block_list_leave_type or not leave_type or block_list_leave_type == leave_type:
add_block_list([block_list])
return list(set(block_lists))
def is_user_in_allow_list(block_list):
return frappe.db.get_value(
"Leave Block List Allow",
{"parent": block_list, "allow_user": frappe.session.user},
"allow_user",
)
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_block_list/leave_block_list.py
|
Python
|
agpl-3.0
| 3,077
|
def get_data():
return {"fieldname": "leave_block_list", "transactions": [{"items": ["Department"]}]}
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_block_list/leave_block_list_dashboard.py
|
Python
|
agpl-3.0
| 103
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# For license information, please see license.txt
from frappe.model.document import Document
class LeaveBlockListAllow(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_block_list_allow/leave_block_list_allow.py
|
Python
|
agpl-3.0
| 268
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# For license information, please see license.txt
from frappe.model.document import Document
class LeaveBlockListDate(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_block_list_date/leave_block_list_date.py
|
Python
|
agpl-3.0
| 267
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.ui.form.on("Leave Control Panel", {
setup: function (frm) {
frm.trigger("set_query");
frm.trigger("set_leave_details");
hrms.setup_employee_filter_group(frm);
},
refresh: function (frm) {
frm.page.clear_indicator();
frm.disable_save();
frm.trigger("get_employees");
frm.trigger("set_primary_action");
hrms.handle_realtime_bulk_action_notification(
frm,
"completed_bulk_leave_policy_assignment",
"Leave Policy Assignment",
);
hrms.handle_realtime_bulk_action_notification(
frm,
"completed_bulk_leave_allocation",
"Leave Allocation",
);
},
company: function (frm) {
if (frm.doc.company) {
frm.set_query("department", function () {
return {
filters: {
company: frm.doc.company,
},
};
});
}
frm.trigger("get_employees");
},
employment_type(frm) {
frm.trigger("get_employees");
},
branch(frm) {
frm.trigger("get_employees");
},
department(frm) {
frm.trigger("get_employees");
},
designation(frm) {
frm.trigger("get_employees");
},
employee_grade(frm) {
frm.trigger("get_employees");
},
dates_based_on(frm) {
frm.trigger("reset_leave_details");
frm.trigger("get_employees");
},
from_date(frm) {
frm.trigger("get_employees");
},
to_date(frm) {
frm.trigger("get_employees");
},
leave_period(frm) {
frm.trigger("get_employees");
},
allocate_based_on_leave_policy(frm) {
frm.trigger("get_employees");
},
leave_type(frm) {
frm.trigger("get_employees");
},
leave_policy(frm) {
frm.trigger("get_employees");
},
reset_leave_details(frm) {
if (frm.doc.dates_based_on === "Leave Period") {
frm.add_fetch("leave_period", "from_date", "from_date");
frm.add_fetch("leave_period", "to_date", "to_date");
}
},
set_leave_details(frm) {
frm.call("get_latest_leave_period").then((r) => {
frm.set_value({
dates_based_on: "Leave Period",
from_date: frappe.datetime.get_today(),
to_date: null,
leave_period: r.message,
carry_forward: 1,
allocate_based_on_leave_policy: 1,
leave_type: null,
no_of_days: 0,
leave_policy: null,
company: frappe.defaults.get_default("company"),
});
});
},
get_employees(frm) {
frm.call({
method: "get_employees",
args: {
advanced_filters: frm.advanced_filters || [],
},
doc: frm.doc,
}).then((r) => {
const columns = frm.events.get_employees_datatable_columns();
hrms.render_employees_datatable(frm, columns, r.message);
});
},
get_employees_datatable_columns() {
return [
{
name: "employee",
id: "employee",
content: __("Employee"),
},
{
name: "employee_name",
id: "employee_name",
content: __("Name"),
},
{
name: "company",
id: "company",
content: __("Company"),
},
{
name: "department",
id: "department",
content: __("Department"),
},
].map((x) => ({
...x,
editable: false,
focusable: false,
dropdown: false,
align: "left",
}));
},
set_query(frm) {
frm.set_query("leave_policy", function () {
return {
filters: {
docstatus: 1,
},
};
});
frm.set_query("leave_period", function () {
return {
filters: {
is_active: 1,
},
};
});
},
set_primary_action(frm) {
frm.page.set_primary_action(__("Allocate Leave"), () => {
frm.trigger("allocate_leave");
});
},
allocate_leave(frm) {
const check_map = frm.employees_datatable.rowmanager.checkMap;
const selected_employees = [];
check_map.forEach((is_checked, idx) => {
if (is_checked)
selected_employees.push(frm.employees_datatable.datamanager.data[idx].employee);
});
hrms.validate_mandatory_fields(frm, selected_employees);
frappe.confirm(
__("Allocate leaves to {0} employee(s)?", [selected_employees.length]),
() => frm.events.bulk_allocate_leave(frm, selected_employees),
);
},
bulk_allocate_leave(frm, employees) {
frm.call({
method: "allocate_leave",
doc: frm.doc,
args: {
employees: employees,
},
freeze: true,
freeze_message: __("Allocating Leave"),
}).then((r) => {
// don't refresh on complete failure
if (r.message.failed && !r.message.success) return;
frm.refresh();
});
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_control_panel/leave_control_panel.js
|
JavaScript
|
agpl-3.0
| 4,342
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
from frappe.model.document import Document
from frappe.utils import cint, flt, get_link_to_form
from erpnext import get_default_company
from hrms.hr.utils import validate_bulk_tool_fields
class LeaveControlPanel(Document):
def validate_fields(self, employees: list):
mandatory_fields = []
if self.dates_based_on == "Leave Period":
mandatory_fields.append("leave_period")
elif self.dates_based_on == "Joining Date":
mandatory_fields.append("to_date")
else:
mandatory_fields.extend(["from_date", "to_date"])
if self.allocate_based_on_leave_policy:
mandatory_fields.append("leave_policy")
else:
mandatory_fields.extend(["leave_type", "no_of_days"])
validate_bulk_tool_fields(self, mandatory_fields, employees, "from_date", "to_date")
@frappe.whitelist()
def allocate_leave(self, employees: list):
self.validate_fields(employees)
if self.allocate_based_on_leave_policy:
return self.create_leave_policy_assignments(employees)
return self.create_leave_allocations(employees)
def create_leave_allocations(self, employees: list) -> dict:
from_date, to_date = self.get_from_to_date()
failure = []
success = []
savepoint = "before_allocation_submission"
for employee in employees:
try:
frappe.db.savepoint(savepoint)
allocation = frappe.new_doc("Leave Allocation")
allocation.employee = employee
allocation.leave_type = self.leave_type
allocation.from_date = from_date or frappe.db.get_value(
"Employee", employee, "date_of_joining"
)
allocation.to_date = to_date
allocation.carry_forward = cint(self.carry_forward)
allocation.new_leaves_allocated = flt(self.no_of_days)
allocation.insert()
allocation.submit()
success.append(
{"doc": get_link_to_form("Leave Allocation", allocation.name), "employee": employee}
)
except Exception:
frappe.db.rollback(save_point=savepoint)
allocation.log_error(f"Leave Allocation failed for employee {employee}")
failure.append(employee)
frappe.clear_messages()
frappe.publish_realtime(
"completed_bulk_leave_allocation",
message={"success": success, "failure": failure},
doctype="Bulk Salary Structure Assignment",
after_commit=True,
)
def create_leave_policy_assignments(self, employees: list) -> dict:
from_date, to_date = self.get_from_to_date()
assignment_based_on = None if self.dates_based_on == "Custom Range" else self.dates_based_on
failure = []
success = []
savepoint = "before_assignment_submission"
for employee in employees:
try:
frappe.db.savepoint(savepoint)
assignment = frappe.new_doc("Leave Policy Assignment")
assignment.employee = employee
assignment.assignment_based_on = assignment_based_on
assignment.leave_policy = self.leave_policy
assignment.effective_from = from_date or frappe.db.get_value(
"Employee", employee, "date_of_joining"
)
assignment.effective_to = to_date
assignment.leave_period = self.get("leave_period")
assignment.carry_forward = self.carry_forward
assignment.save()
assignment.submit()
success.append(
{
"doc": get_link_to_form("Leave Policy Assignment", assignment.name),
"employee": employee,
}
)
except Exception:
frappe.db.rollback(save_point=savepoint)
assignment.log_error(f"Leave Policy Assignment failed for employee {employee}")
failure.append(employee)
frappe.clear_messages()
frappe.publish_realtime(
"completed_bulk_leave_policy_assignment",
message={"success": success, "failure": failure},
doctype="Bulk Salary Structure Assignment",
after_commit=True,
)
def get_from_to_date(self):
if self.dates_based_on == "Joining Date":
return None, self.to_date
elif self.dates_based_on == "Leave Period" and self.leave_period:
return frappe.db.get_value("Leave Period", self.leave_period, ["from_date", "to_date"])
else:
return self.from_date, self.to_date
@frappe.whitelist()
def get_employees(self, advanced_filters: list) -> list:
from_date, to_date = self.get_from_to_date()
if to_date and (from_date or self.dates_based_on == "Joining Date"):
if all_employees := frappe.get_list(
"Employee",
filters=self.get_filters() + advanced_filters,
fields=["name", "employee", "employee_name", "company", "department", "date_of_joining"],
):
return self.get_employees_without_allocations(all_employees, from_date, to_date)
return []
def get_employees_without_allocations(self, all_employees: list, from_date: str, to_date: str) -> list:
Allocation = frappe.qb.DocType("Leave Allocation")
Employee = frappe.qb.DocType("Employee")
query = (
frappe.qb.from_(Allocation)
.join(Employee)
.on(Allocation.employee == Employee.name)
.select(Employee.name)
.distinct()
.where((Allocation.docstatus == 1) & (Allocation.employee.isin([d.name for d in all_employees])))
)
if self.dates_based_on == "Joining Date":
from_date = Employee.date_of_joining
query = query.where(
(Allocation.from_date[from_date:to_date] | Allocation.to_date[from_date:to_date])
| (
(Allocation.from_date <= from_date)
& (Allocation.from_date <= to_date)
& (Allocation.to_date >= from_date)
& (Allocation.to_date >= to_date)
)
)
if self.allocate_based_on_leave_policy and self.leave_policy:
leave_types = frappe.get_all(
"Leave Policy Detail", {"parent": self.leave_policy}, pluck="leave_type"
)
query = query.where(Allocation.leave_type.isin(leave_types))
elif not self.allocate_based_on_leave_policy and self.leave_type:
query = query.where(Allocation.leave_type == self.leave_type)
employees_with_allocations = query.run(pluck=True)
return [d for d in all_employees if d.name not in employees_with_allocations]
@frappe.whitelist()
def get_latest_leave_period(self):
return frappe.db.get_value(
"Leave Period",
{
"is_active": 1,
"company": self.company or get_default_company(),
},
"name",
order_by="from_date desc",
)
def get_filters(self):
filter_fields = [
"company",
"employment_type",
"branch",
"department",
"designation",
"employee_grade",
]
filters = [["status", "=", "Active"]]
for d in filter_fields:
if self.get(d):
if d == "employee_grade":
filters.append(["grade", "=", self.get(d)])
else:
filters.append([d, "=", self.get(d)])
return filters
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_control_panel/leave_control_panel.py
|
Python
|
agpl-3.0
| 6,549
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Leave Encashment", {
onload: function (frm) {
// Ignore cancellation of doctype on cancel all.
frm.ignore_doctypes_on_cancel_all = ["Leave Ledger Entry"];
},
setup: function (frm) {
frm.set_query("leave_type", function () {
return {
filters: {
allow_encashment: 1,
},
};
});
frm.set_query("leave_period", function () {
return {
filters: {
is_active: 1,
},
};
});
},
refresh: function (frm) {
cur_frm.set_intro("");
if (frm.doc.__islocal && !frappe.user_roles.includes("Employee")) {
frm.set_intro(__("Fill the form and save it"));
}
hrms.leave_utils.add_view_ledger_button(frm);
},
employee: function (frm) {
if (frm.doc.employee) {
frappe.run_serially([
() => frm.trigger("get_employee_currency"),
() => frm.trigger("get_leave_details_for_encashment"),
]);
}
},
leave_type: function (frm) {
frm.trigger("get_leave_details_for_encashment");
},
encashment_date: function (frm) {
frm.trigger("get_leave_details_for_encashment");
},
get_leave_details_for_encashment: function (frm) {
frm.set_value("actual_encashable_days", 0);
frm.set_value("encashment_days", 0);
if (frm.doc.docstatus === 0 && frm.doc.employee && frm.doc.leave_type) {
return frappe.call({
method: "get_leave_details_for_encashment",
doc: frm.doc,
callback: function (r) {
frm.refresh_fields();
},
});
}
},
get_employee_currency: function (frm) {
frappe.call({
method: "hrms.payroll.doctype.salary_structure_assignment.salary_structure_assignment.get_employee_currency",
args: {
employee: frm.doc.employee,
},
callback: function (r) {
if (r.message) {
frm.set_value("currency", r.message);
frm.refresh_fields();
}
},
});
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_encashment/leave_encashment.js
|
JavaScript
|
agpl-3.0
| 1,913
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _, bold
from frappe.model.document import Document
from frappe.utils import format_date, get_link_to_form, getdate
from hrms.hr.doctype.leave_application.leave_application import get_leaves_for_period
from hrms.hr.doctype.leave_ledger_entry.leave_ledger_entry import create_leave_ledger_entry
from hrms.hr.utils import set_employee_name, validate_active_employee
from hrms.payroll.doctype.salary_structure_assignment.salary_structure_assignment import (
get_assigned_salary_structure,
)
class LeaveEncashment(Document):
def validate(self):
set_employee_name(self)
validate_active_employee(self.employee)
self.encashment_date = self.encashment_date or getdate()
self.set_salary_structure()
self.get_leave_details_for_encashment()
def set_salary_structure(self):
self._salary_structure = get_assigned_salary_structure(self.employee, self.encashment_date)
if not self._salary_structure:
frappe.throw(
_("No Salary Structure assigned to Employee {0} on the given date {1}").format(
self.employee, frappe.bold(format_date(self.encashment_date))
)
)
def before_submit(self):
if self.encashment_amount <= 0:
frappe.throw(_("You can only submit Leave Encashment for a valid encashment amount"))
def on_submit(self):
if not self.leave_allocation:
self.db_set("leave_allocation", self.get_leave_allocation().get("name"))
additional_salary = frappe.new_doc("Additional Salary")
additional_salary.company = frappe.get_value("Employee", self.employee, "company")
additional_salary.employee = self.employee
additional_salary.currency = self.currency
earning_component = frappe.get_value("Leave Type", self.leave_type, "earning_component")
if not earning_component:
frappe.throw(_("Please set Earning Component for Leave type: {0}.").format(self.leave_type))
additional_salary.salary_component = earning_component
additional_salary.payroll_date = self.encashment_date
additional_salary.amount = self.encashment_amount
additional_salary.ref_doctype = self.doctype
additional_salary.ref_docname = self.name
additional_salary.submit()
# Set encashed leaves in Allocation
frappe.db.set_value(
"Leave Allocation",
self.leave_allocation,
"total_leaves_encashed",
frappe.db.get_value("Leave Allocation", self.leave_allocation, "total_leaves_encashed")
+ self.encashment_days,
)
self.create_leave_ledger_entry()
def on_cancel(self):
if self.additional_salary:
frappe.get_doc("Additional Salary", self.additional_salary).cancel()
self.db_set("additional_salary", "")
if self.leave_allocation:
frappe.db.set_value(
"Leave Allocation",
self.leave_allocation,
"total_leaves_encashed",
frappe.db.get_value("Leave Allocation", self.leave_allocation, "total_leaves_encashed")
- self.encashment_days,
)
self.create_leave_ledger_entry(submit=False)
@frappe.whitelist()
def get_leave_details_for_encashment(self):
self.set_leave_balance()
self.set_actual_encashable_days()
self.set_encashment_days()
self.set_encashment_amount()
def get_encashment_settings(self):
return frappe.get_cached_value(
"Leave Type",
self.leave_type,
["allow_encashment", "non_encashable_leaves", "max_encashable_leaves"],
as_dict=True,
)
def set_actual_encashable_days(self):
encashment_settings = self.get_encashment_settings()
if not encashment_settings.allow_encashment:
frappe.throw(_("Leave Type {0} is not encashable").format(self.leave_type))
self.actual_encashable_days = self.leave_balance
leave_form_link = get_link_to_form("Leave Type", self.leave_type)
# TODO: Remove this weird setting if possible. Retained for backward compatibility
if encashment_settings.non_encashable_leaves:
actual_encashable_days = self.leave_balance - encashment_settings.non_encashable_leaves
self.actual_encashable_days = actual_encashable_days if actual_encashable_days > 0 else 0
frappe.msgprint(
_("Excluded {0} Non-Encashable Leaves for {1}").format(
bold(encashment_settings.non_encashable_leaves),
leave_form_link,
),
)
if encashment_settings.max_encashable_leaves:
self.actual_encashable_days = min(
self.actual_encashable_days, encashment_settings.max_encashable_leaves
)
frappe.msgprint(
_("Maximum encashable leaves for {0} are {1}").format(
leave_form_link, bold(encashment_settings.max_encashable_leaves)
),
title=_("Encashment Limit Applied"),
)
def set_encashment_days(self):
# allow overwriting encashment days
if not self.encashment_days:
self.encashment_days = self.actual_encashable_days
if self.encashment_days > self.actual_encashable_days:
frappe.throw(
_("Encashment Days cannot exceed {0} {1} as per Leave Type settings").format(
bold(_("Actual Encashable Days")),
self.actual_encashable_days,
)
)
def set_leave_balance(self):
allocation = self.get_leave_allocation()
if not allocation:
frappe.throw(
_("No Leaves Allocated to Employee: {0} for Leave Type: {1}").format(
self.employee, self.leave_type
)
)
self.leave_balance = (
allocation.total_leaves_allocated
- allocation.carry_forwarded_leaves_count
# adding this because the function returns a -ve number
+ get_leaves_for_period(
self.employee, self.leave_type, allocation.from_date, self.encashment_date
)
)
self.leave_allocation = allocation.name
def set_encashment_amount(self):
if not hasattr(self, "_salary_structure"):
self.set_salary_structure()
per_day_encashment = frappe.db.get_value(
"Salary Structure", self._salary_structure, "leave_encashment_amount_per_day"
)
self.encashment_amount = self.encashment_days * per_day_encashment if per_day_encashment > 0 else 0
def get_leave_allocation(self):
date = self.encashment_date or getdate()
LeaveAllocation = frappe.qb.DocType("Leave Allocation")
leave_allocation = (
frappe.qb.from_(LeaveAllocation)
.select(
LeaveAllocation.name,
LeaveAllocation.from_date,
LeaveAllocation.to_date,
LeaveAllocation.total_leaves_allocated,
LeaveAllocation.carry_forwarded_leaves_count,
)
.where(
((LeaveAllocation.from_date <= date) & (date <= LeaveAllocation.to_date))
& (LeaveAllocation.docstatus == 1)
& (LeaveAllocation.leave_type == self.leave_type)
& (LeaveAllocation.employee == self.employee)
)
).run(as_dict=True)
return leave_allocation[0] if leave_allocation else None
def create_leave_ledger_entry(self, submit=True):
args = frappe._dict(
leaves=self.encashment_days * -1,
from_date=self.encashment_date,
to_date=self.encashment_date,
is_carry_forward=0,
)
create_leave_ledger_entry(self, args, submit)
# create reverse entry for expired leaves
leave_allocation = self.get_leave_allocation()
if not leave_allocation:
return
to_date = leave_allocation.get("to_date")
if to_date < getdate():
args = frappe._dict(
leaves=self.encashment_days, from_date=to_date, to_date=to_date, is_carry_forward=0
)
create_leave_ledger_entry(self, args, submit)
def create_leave_encashment(leave_allocation):
"""Creates leave encashment for the given allocations"""
for allocation in leave_allocation:
if not get_assigned_salary_structure(allocation.employee, allocation.to_date):
continue
leave_encashment = frappe.get_doc(
dict(
doctype="Leave Encashment",
leave_period=allocation.leave_period,
employee=allocation.employee,
leave_type=allocation.leave_type,
encashment_date=allocation.to_date,
)
)
leave_encashment.insert(ignore_permissions=True)
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_encashment/leave_encashment.py
|
Python
|
agpl-3.0
| 7,771
|
// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Leave Ledger Entry", {
// refresh: function(frm) {
// }
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_ledger_entry/leave_ledger_entry.js
|
JavaScript
|
agpl-3.0
| 203
|
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import DATE_FORMAT, flt, get_link_to_form, getdate, today
class LeaveLedgerEntry(Document):
def validate(self):
if getdate(self.from_date) > getdate(self.to_date):
frappe.throw(_("To date needs to be before from date"))
def on_cancel(self):
# allow cancellation of expiry leaves
if self.is_expired:
frappe.db.set_value("Leave Allocation", self.transaction_name, "expired", 0)
else:
frappe.throw(_("Only expired allocation can be cancelled"))
def validate_leave_allocation_against_leave_application(ledger):
"""Checks that leave allocation has no leave application against it"""
leave_application_records = frappe.db.sql_list(
"""
SELECT transaction_name
FROM `tabLeave Ledger Entry`
WHERE
employee=%s
AND leave_type=%s
AND transaction_type='Leave Application'
AND from_date>=%s
AND to_date<=%s
""",
(ledger.employee, ledger.leave_type, ledger.from_date, ledger.to_date),
)
if leave_application_records:
frappe.throw(
_("Leave allocation {0} is linked with the Leave Application {1}").format(
ledger.transaction_name,
", ".join(
get_link_to_form("Leave Application", application)
for application in leave_application_records
),
)
)
def create_leave_ledger_entry(ref_doc, args, submit=True):
ledger = frappe._dict(
doctype="Leave Ledger Entry",
employee=ref_doc.employee,
employee_name=ref_doc.employee_name,
leave_type=ref_doc.leave_type,
transaction_type=ref_doc.doctype,
transaction_name=ref_doc.name,
is_carry_forward=0,
is_expired=0,
is_lwp=0,
)
ledger.update(args)
if submit:
doc = frappe.get_doc(ledger)
doc.flags.ignore_permissions = 1
doc.submit()
else:
delete_ledger_entry(ledger)
def delete_ledger_entry(ledger):
"""Delete ledger entry on cancel of leave application/allocation/encashment"""
if ledger.transaction_type == "Leave Allocation":
validate_leave_allocation_against_leave_application(ledger)
expired_entry = get_previous_expiry_ledger_entry(ledger)
frappe.db.sql(
"""DELETE
FROM `tabLeave Ledger Entry`
WHERE
`transaction_name`=%s
OR `name`=%s""",
(ledger.transaction_name, expired_entry),
)
def get_previous_expiry_ledger_entry(ledger):
"""Returns the expiry ledger entry having same creation date as the ledger entry to be cancelled"""
creation_date = frappe.db.get_value(
"Leave Ledger Entry",
filters={
"transaction_name": ledger.transaction_name,
"is_expired": 0,
"transaction_type": "Leave Allocation",
},
fieldname=["creation"],
)
creation_date = creation_date.strftime(DATE_FORMAT) if creation_date else ""
return frappe.db.get_value(
"Leave Ledger Entry",
filters={
"creation": ("like", creation_date + "%"),
"employee": ledger.employee,
"leave_type": ledger.leave_type,
"is_expired": 1,
"docstatus": 1,
"is_carry_forward": 0,
},
fieldname=["name"],
)
def process_expired_allocation():
"""Check if a carry forwarded allocation has expired and create a expiry ledger entry
Case 1: carry forwarded expiry period is set for the leave type,
create a separate leave expiry entry against each entry of carry forwarded and non carry forwarded leaves
Case 2: leave type has no specific expiry period for carry forwarded leaves
and there is no carry forwarded leave allocation, create a single expiry against the remaining leaves.
"""
# fetch leave type records that has carry forwarded leaves expiry
leave_type_records = frappe.db.get_values(
"Leave Type", filters={"expire_carry_forwarded_leaves_after_days": (">", 0)}, fieldname=["name"]
)
leave_type = [record[0] for record in leave_type_records] or [""]
# fetch non expired leave ledger entry of transaction_type allocation
expire_allocation = frappe.db.sql(
"""
SELECT
leaves, to_date, from_date, employee, leave_type,
is_carry_forward, transaction_name as name, transaction_type
FROM `tabLeave Ledger Entry` l
WHERE (NOT EXISTS
(SELECT name
FROM `tabLeave Ledger Entry`
WHERE
transaction_name = l.transaction_name
AND transaction_type = 'Leave Allocation'
AND name<>l.name
AND docstatus = 1
AND (
is_carry_forward=l.is_carry_forward
OR (is_carry_forward = 0 AND leave_type not in %s)
)))
AND transaction_type = 'Leave Allocation'
AND to_date < %s""",
(leave_type, today()),
as_dict=1,
)
if expire_allocation:
create_expiry_ledger_entry(expire_allocation)
def create_expiry_ledger_entry(allocations):
"""Create ledger entry for expired allocation"""
for allocation in allocations:
if allocation.is_carry_forward:
expire_carried_forward_allocation(allocation)
else:
expire_allocation(allocation)
def get_remaining_leaves(allocation):
"""Returns remaining leaves from the given allocation"""
return frappe.db.get_value(
"Leave Ledger Entry",
filters={
"employee": allocation.employee,
"leave_type": allocation.leave_type,
"to_date": ("<=", allocation.to_date),
"docstatus": 1,
},
fieldname=["SUM(leaves)"],
)
@frappe.whitelist()
def expire_allocation(allocation, expiry_date=None):
"""expires non-carry forwarded allocation"""
import json
if isinstance(allocation, str):
allocation = json.loads(allocation)
allocation = frappe.get_doc("Leave Allocation", allocation["name"])
leaves = get_remaining_leaves(allocation)
expiry_date = expiry_date if expiry_date else allocation.to_date
# allows expired leaves entry to be created/reverted
if leaves:
args = dict(
leaves=flt(leaves) * -1,
transaction_name=allocation.name,
transaction_type="Leave Allocation",
from_date=expiry_date,
to_date=expiry_date,
is_carry_forward=0,
is_expired=1,
)
create_leave_ledger_entry(allocation, args)
frappe.db.set_value("Leave Allocation", allocation.name, "expired", 1)
def expire_carried_forward_allocation(allocation):
"""Expires remaining leaves in the on carried forward allocation"""
from hrms.hr.doctype.leave_application.leave_application import get_leaves_for_period
leaves_taken = get_leaves_for_period(
allocation.employee,
allocation.leave_type,
allocation.from_date,
allocation.to_date,
skip_expired_leaves=False,
)
leaves = flt(allocation.leaves) + flt(leaves_taken)
# allow expired leaves entry to be created
if leaves > 0:
args = frappe._dict(
transaction_name=allocation.name,
transaction_type="Leave Allocation",
leaves=leaves * -1,
is_carry_forward=allocation.is_carry_forward,
is_expired=1,
from_date=allocation.to_date,
to_date=allocation.to_date,
)
create_leave_ledger_entry(allocation, args)
def on_doctype_update():
frappe.db.add_index("Leave Ledger Entry", ["transaction_type", "transaction_name"])
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
|
Python
|
agpl-3.0
| 6,940
|
frappe.listview_settings["Leave Ledger Entry"] = {
onload: function (listview) {
if (listview.page.fields_dict.transaction_type) {
listview.page.fields_dict.transaction_type.get_query = function () {
return {
filters: {
name: [
"in",
["Leave Allocation", "Leave Application", "Leave Encashment"],
],
},
};
};
}
},
};
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_ledger_entry/leave_ledger_entry_list.js
|
JavaScript
|
agpl-3.0
| 373
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Leave Period", {
from_date: (frm) => {
if (frm.doc.from_date && !frm.doc.to_date) {
var a_year_from_start = frappe.datetime.add_months(frm.doc.from_date, 12);
frm.set_value("to_date", frappe.datetime.add_days(a_year_from_start, -1));
}
},
onload: (frm) => {
frm.set_query("department", function () {
return {
filters: {
company: frm.doc.company,
},
};
});
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_period/leave_period.js
|
JavaScript
|
agpl-3.0
| 541
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import getdate
from hrms.hr.utils import validate_overlap
class LeavePeriod(Document):
def validate(self):
self.validate_dates()
validate_overlap(self, self.from_date, self.to_date, self.company)
def validate_dates(self):
if getdate(self.from_date) >= getdate(self.to_date):
frappe.throw(_("To date can not be equal or less than from date"))
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_period/leave_period.py
|
Python
|
agpl-3.0
| 574
|
from frappe import _
def get_data():
return {
"fieldname": "leave_period",
"transactions": [{"label": _("Transactions"), "items": ["Leave Allocation"]}],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_period/leave_period_dashboard.py
|
Python
|
agpl-3.0
| 164
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Leave Policy", {});
frappe.ui.form.on("Leave Policy Detail", {
leave_type: function (frm, cdt, cdn) {
var child = locals[cdt][cdn];
if (child.leave_type) {
frappe.call({
method: "frappe.client.get_value",
args: {
doctype: "Leave Type",
fieldname: "max_leaves_allowed",
filters: { name: child.leave_type },
},
callback: function (r) {
if (r.message) {
child.annual_allocation = r.message.max_leaves_allowed;
refresh_field("leave_policy_details");
}
},
});
} else {
child.annual_allocation = "";
refresh_field("leave_policy_details");
}
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy/leave_policy.js
|
JavaScript
|
agpl-3.0
| 763
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
class LeavePolicy(Document):
def validate(self):
if self.leave_policy_details:
for lp_detail in self.leave_policy_details:
max_leaves_allowed = frappe.db.get_value(
"Leave Type", lp_detail.leave_type, "max_leaves_allowed"
)
if max_leaves_allowed > 0 and lp_detail.annual_allocation > max_leaves_allowed:
frappe.throw(
_("Maximum leave allowed in the leave type {0} is {1}").format(
lp_detail.leave_type, max_leaves_allowed
)
)
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy/leave_policy.py
|
Python
|
agpl-3.0
| 680
|
from frappe import _
def get_data():
return {
"fieldname": "leave_policy",
"transactions": [
{"label": _("Leaves"), "items": ["Leave Policy Assignment", "Leave Allocation"]},
],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy/leave_policy_dashboard.py
|
Python
|
agpl-3.0
| 193
|
// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Leave Policy Assignment", {
onload: function (frm) {
frm.ignore_doctypes_on_cancel_all = ["Leave Ledger Entry"];
frm.set_query("leave_policy", function () {
return {
filters: {
docstatus: 1,
},
};
});
frm.set_query("leave_period", function () {
return {
filters: {
is_active: 1,
company: frm.doc.company,
},
};
});
},
assignment_based_on: function (frm) {
if (frm.doc.assignment_based_on) {
frm.events.set_effective_date(frm);
} else {
frm.set_value("effective_from", "");
frm.set_value("effective_to", "");
}
},
leave_period: function (frm) {
if (frm.doc.leave_period) {
frm.events.set_effective_date(frm);
}
},
set_effective_date: function (frm) {
if (frm.doc.assignment_based_on == "Leave Period" && frm.doc.leave_period) {
frappe.model.with_doc("Leave Period", frm.doc.leave_period, function () {
let from_date = frappe.model.get_value(
"Leave Period",
frm.doc.leave_period,
"from_date",
);
let to_date = frappe.model.get_value(
"Leave Period",
frm.doc.leave_period,
"to_date",
);
frm.set_value("effective_from", from_date);
frm.set_value("effective_to", to_date);
});
} else if (frm.doc.assignment_based_on == "Joining Date" && frm.doc.employee) {
frappe.model.with_doc("Employee", frm.doc.employee, function () {
let from_date = frappe.model.get_value(
"Employee",
frm.doc.employee,
"date_of_joining",
);
frm.set_value("effective_from", from_date);
frm.set_value(
"effective_to",
frappe.datetime.add_months(frm.doc.effective_from, 12),
);
});
}
frm.refresh();
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy_assignment/leave_policy_assignment.js
|
JavaScript
|
agpl-3.0
| 1,820
|
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import json
import frappe
from frappe import _, bold
from frappe.model.document import Document
from frappe.utils import (
add_months,
cint,
comma_and,
date_diff,
flt,
formatdate,
get_first_day,
get_last_day,
get_link_to_form,
getdate,
rounded,
)
class LeavePolicyAssignment(Document):
def validate(self):
self.set_dates()
self.validate_policy_assignment_overlap()
self.warn_about_carry_forwarding()
def on_submit(self):
self.grant_leave_alloc_for_employee()
def set_dates(self):
if self.assignment_based_on == "Leave Period":
self.effective_from, self.effective_to = frappe.db.get_value(
"Leave Period", self.leave_period, ["from_date", "to_date"]
)
elif self.assignment_based_on == "Joining Date":
self.effective_from = frappe.db.get_value("Employee", self.employee, "date_of_joining")
def validate_policy_assignment_overlap(self):
leave_policy_assignment = frappe.db.get_value(
"Leave Policy Assignment",
{
"employee": self.employee,
"name": ("!=", self.name),
"docstatus": 1,
"effective_to": (">=", self.effective_from),
"effective_from": ("<=", self.effective_to),
},
"leave_policy",
)
if leave_policy_assignment:
frappe.throw(
_("Leave Policy: {0} already assigned for Employee {1} for period {2} to {3}").format(
bold(leave_policy_assignment),
bold(self.employee),
bold(formatdate(self.effective_from)),
bold(formatdate(self.effective_to)),
),
title=_("Leave Policy Assignment Overlap"),
)
def warn_about_carry_forwarding(self):
if not self.carry_forward:
return
leave_types = get_leave_type_details()
leave_policy = frappe.get_doc("Leave Policy", self.leave_policy)
for policy in leave_policy.leave_policy_details:
leave_type = leave_types.get(policy.leave_type)
if not leave_type.is_carry_forward:
msg = _(
"Leaves for the Leave Type {0} won't be carry-forwarded since carry-forwarding is disabled."
).format(frappe.bold(get_link_to_form("Leave Type", leave_type.name)))
frappe.msgprint(msg, indicator="orange", alert=True)
def grant_leave_alloc_for_employee(self):
if self.leaves_allocated:
frappe.throw(_("Leave already have been assigned for this Leave Policy Assignment"))
else:
leave_allocations = {}
leave_type_details = get_leave_type_details()
leave_policy = frappe.get_doc("Leave Policy", self.leave_policy)
date_of_joining = frappe.db.get_value("Employee", self.employee, "date_of_joining")
for leave_policy_detail in leave_policy.leave_policy_details:
leave_details = leave_type_details.get(leave_policy_detail.leave_type)
if not leave_details.is_lwp:
leave_allocation, new_leaves_allocated = self.create_leave_allocation(
leave_policy_detail.annual_allocation,
leave_details,
date_of_joining,
)
leave_allocations[leave_details.name] = {
"name": leave_allocation,
"leaves": new_leaves_allocated,
}
self.db_set("leaves_allocated", 1)
return leave_allocations
def create_leave_allocation(self, annual_allocation, leave_details, date_of_joining):
# Creates leave allocation for the given employee in the provided leave period
carry_forward = self.carry_forward
if self.carry_forward and not leave_details.is_carry_forward:
carry_forward = 0
new_leaves_allocated = self.get_new_leaves(annual_allocation, leave_details, date_of_joining)
allocation = frappe.get_doc(
dict(
doctype="Leave Allocation",
employee=self.employee,
leave_type=leave_details.name,
from_date=self.effective_from,
to_date=self.effective_to,
new_leaves_allocated=new_leaves_allocated,
leave_period=self.leave_period if self.assignment_based_on == "Leave Policy" else "",
leave_policy_assignment=self.name,
leave_policy=self.leave_policy,
carry_forward=carry_forward,
)
)
allocation.save(ignore_permissions=True)
allocation.submit()
return allocation.name, new_leaves_allocated
def get_new_leaves(self, annual_allocation, leave_details, date_of_joining):
from frappe.model.meta import get_field_precision
precision = get_field_precision(frappe.get_meta("Leave Allocation").get_field("new_leaves_allocated"))
# Earned Leaves and Compensatory Leaves are allocated by scheduler, initially allocate 0
if leave_details.is_compensatory:
new_leaves_allocated = 0
elif leave_details.is_earned_leave:
new_leaves_allocated = self.get_leaves_for_passed_months(
annual_allocation, leave_details, date_of_joining
)
else:
# calculate pro-rated leaves for other leave types
new_leaves_allocated = calculate_pro_rated_leaves(
annual_allocation,
date_of_joining,
self.effective_from,
self.effective_to,
is_earned_leave=False,
)
# leave allocation should not exceed annual allocation as per policy assignment
if new_leaves_allocated > annual_allocation:
new_leaves_allocated = annual_allocation
return flt(new_leaves_allocated, precision)
def get_leaves_for_passed_months(self, annual_allocation, leave_details, date_of_joining):
from hrms.hr.utils import get_monthly_earned_leave
def _get_current_and_from_date():
current_date = frappe.flags.current_date or getdate()
if current_date > getdate(self.effective_to):
current_date = getdate(self.effective_to)
from_date = getdate(self.effective_from)
if getdate(date_of_joining) > from_date:
from_date = getdate(date_of_joining)
return current_date, from_date
def _get_months_passed(current_date, from_date, consider_current_month):
months_passed = 0
if current_date.year == from_date.year and current_date.month >= from_date.month:
months_passed = current_date.month - from_date.month
if consider_current_month:
months_passed += 1
elif current_date.year > from_date.year:
months_passed = (12 - from_date.month) + current_date.month
if consider_current_month:
months_passed += 1
return months_passed
def _get_pro_rata_period_end_date(consider_current_month):
# for earned leave, pro-rata period ends on the last day of the month
date = getdate(frappe.flags.current_date) or getdate()
if consider_current_month:
period_end_date = get_last_day(date)
else:
period_end_date = get_last_day(add_months(date, -1))
return period_end_date
def _calculate_leaves_for_passed_months(consider_current_month):
monthly_earned_leave = get_monthly_earned_leave(
date_of_joining,
annual_allocation,
leave_details.earned_leave_frequency,
leave_details.rounding,
pro_rated=False,
)
period_end_date = _get_pro_rata_period_end_date(consider_current_month)
if getdate(self.effective_from) <= date_of_joining <= period_end_date:
# if the employee joined within the allocation period in some previous month,
# calculate pro-rated leave for that month
# and normal monthly earned leave for remaining passed months
leaves = get_monthly_earned_leave(
date_of_joining,
annual_allocation,
leave_details.earned_leave_frequency,
leave_details.rounding,
get_first_day(date_of_joining),
get_last_day(date_of_joining),
)
leaves += monthly_earned_leave * (months_passed - 1)
else:
leaves = monthly_earned_leave * months_passed
return leaves
consider_current_month = is_earned_leave_applicable_for_current_month(
date_of_joining, leave_details.allocate_on_day
)
current_date, from_date = _get_current_and_from_date()
months_passed = _get_months_passed(current_date, from_date, consider_current_month)
if months_passed > 0:
new_leaves_allocated = _calculate_leaves_for_passed_months(consider_current_month)
else:
new_leaves_allocated = 0
return new_leaves_allocated
def calculate_pro_rated_leaves(
leaves, date_of_joining, period_start_date, period_end_date, is_earned_leave=False
):
if not leaves or getdate(date_of_joining) <= getdate(period_start_date):
return leaves
precision = cint(frappe.db.get_single_value("System Settings", "float_precision", cache=True))
actual_period = date_diff(period_end_date, date_of_joining) + 1
complete_period = date_diff(period_end_date, period_start_date) + 1
leaves *= actual_period / complete_period
if is_earned_leave:
return flt(leaves, precision)
return rounded(leaves)
def is_earned_leave_applicable_for_current_month(date_of_joining, allocate_on_day):
date = getdate(frappe.flags.current_date) or getdate()
# If the date of assignment creation is >= the leave type's "Allocate On" date,
# then the current month should be considered
# because the employee is already entitled for the leave of that month
if (
(allocate_on_day == "Date of Joining" and date.day >= date_of_joining.day)
or (allocate_on_day == "First Day" and date >= get_first_day(date))
or (allocate_on_day == "Last Day" and date == get_last_day(date))
):
return True
return False
@frappe.whitelist()
def create_assignment_for_multiple_employees(employees, data):
if isinstance(employees, str):
employees = json.loads(employees)
if isinstance(data, str):
data = frappe._dict(json.loads(data))
docs_name = []
failed = []
for employee in employees:
assignment = frappe.new_doc("Leave Policy Assignment")
assignment.employee = employee
assignment.assignment_based_on = data.assignment_based_on or None
assignment.leave_policy = data.leave_policy
assignment.effective_from = getdate(data.effective_from) or None
assignment.effective_to = getdate(data.effective_to) or None
assignment.leave_period = data.leave_period or None
assignment.carry_forward = data.carry_forward
assignment.save()
savepoint = "before_assignment_submission"
try:
frappe.db.savepoint(savepoint)
assignment.submit()
except Exception:
frappe.db.rollback(save_point=savepoint)
assignment.log_error("Leave Policy Assignment submission failed")
failed.append(assignment.name)
docs_name.append(assignment.name)
if failed:
show_assignment_submission_status(failed)
return docs_name
def show_assignment_submission_status(failed):
frappe.clear_messages()
assignment_list = [get_link_to_form("Leave Policy Assignment", entry) for entry in failed]
msg = _("Failed to submit some leave policy assignments:")
msg += " " + comma_and(assignment_list, False) + "<hr>"
msg += (
_("Check {0} for more details")
.format("<a href='/app/List/Error Log?reference_doctype=Leave Policy Assignment'>{0}</a>")
.format(_("Error Log"))
)
frappe.msgprint(
msg,
indicator="red",
title=_("Submission Failed"),
is_minimizable=True,
)
def get_leave_type_details():
leave_type_details = frappe._dict()
leave_types = frappe.get_all(
"Leave Type",
fields=[
"name",
"is_lwp",
"is_earned_leave",
"is_compensatory",
"allocate_on_day",
"is_carry_forward",
"expire_carry_forwarded_leaves_after_days",
"earned_leave_frequency",
"rounding",
],
)
for d in leave_types:
leave_type_details.setdefault(d.name, d)
return leave_type_details
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy_assignment/leave_policy_assignment.py
|
Python
|
agpl-3.0
| 11,158
|
from frappe import _
def get_data():
return {
"fieldname": "leave_policy_assignment",
"transactions": [
{"label": _("Leaves"), "items": ["Leave Allocation"]},
],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy_assignment/leave_policy_assignment_dashboard.py
|
Python
|
agpl-3.0
| 177
|
frappe.listview_settings["Leave Policy Assignment"] = {
onload: function (list_view) {
list_view.page.add_inner_button(__("Bulk Leave Policy Assignment"), function () {
frappe.set_route("Form", "Leave Control Panel");
});
},
};
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy_assignment/leave_policy_assignment_list.js
|
JavaScript
|
agpl-3.0
| 237
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Leave Policy Detail", {
refresh: function (frm) {},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy_detail/leave_policy_detail.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class LeavePolicyDetail(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_policy_detail/leave_policy_detail.py
|
Python
|
agpl-3.0
| 207
|
frappe.ui.form.on("Leave Type", {
refresh: function (frm) {},
});
frappe.tour["Leave Type"] = [
{
fieldname: "max_leaves_allowed",
title: "Maximum Leave Allocation Allowed",
description: __(
"This field allows you to set the maximum number of leaves that can be allocated annually for this Leave Type while creating the Leave Policy",
),
},
{
fieldname: "max_continuous_days_allowed",
title: "Maximum Consecutive Leaves Allowed",
description: __(
"This field allows you to set the maximum number of consecutive leaves an Employee can apply for.",
),
},
{
fieldname: "is_optional_leave",
title: "Is Optional Leave",
description: __(
"Optional Leaves are holidays that Employees can choose to avail from a list of holidays published by the company.",
),
},
{
fieldname: "is_compensatory",
title: "Is Compensatory Leave",
description: __(
"Leaves you can avail against a holiday you worked on. You can claim Compensatory Off Leave using Compensatory Leave Request. Click {0} to know more",
[
`<a href='https://frappehr.com/docs/v14/en/compensatory-leave-request' target='_blank'>${__(
"here",
)}</a>`,
],
),
},
{
fieldname: "allow_encashment",
title: "Allow Encashment",
description: __("From here, you can enable encashment for the balance leaves."),
},
{
fieldname: "is_earned_leave",
title: "Is Earned Leaves",
description: __(
"Earned Leaves are leaves earned by an Employee after working with the company for a certain amount of time. Enabling this will allocate leaves on pro-rata basis by automatically updating Leave Allocation for leaves of this type at intervals set by 'Earned Leave Frequency.",
),
},
];
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_type/leave_type.js
|
JavaScript
|
agpl-3.0
| 1,707
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
from frappe import _, bold
from frappe.model.document import Document
from frappe.utils import today
class LeaveType(Document):
def validate(self):
self.validate_lwp()
self.validate_leave_types()
def validate_lwp(self):
if self.is_lwp:
leave_allocation = frappe.get_all(
"Leave Allocation",
filters={"leave_type": self.name, "from_date": ("<=", today()), "to_date": (">=", today())},
fields=["name"],
)
leave_allocation = [l["name"] for l in leave_allocation]
if leave_allocation:
frappe.throw(
_(
"Leave application is linked with leave allocations {0}. Leave application cannot be set as leave without pay"
).format(", ".join(leave_allocation))
) # nosec
def validate_leave_types(self):
if self.is_compensatory and self.is_earned_leave:
msg = _("Leave Type can either be compensatory or earned leave.") + "<br><br>"
msg += _("Earned Leaves are allocated as per the configured frequency via scheduler.") + "<br>"
msg += _(
"Whereas allocation for Compensatory Leaves is automatically created or updated on submission of Compensatory Leave Request."
)
msg += "<br><br>"
msg += _("Disable {0} or {1} to proceed.").format(
bold(_("Is Compensatory Leave")), bold(_("Is Earned Leave"))
)
frappe.throw(msg, title=_("Not Allowed"))
if self.is_lwp and self.is_ppl:
frappe.throw(_("Leave Type can either be without pay or partial pay"), title=_("Not Allowed"))
if self.is_ppl and (
self.fraction_of_daily_salary_per_leave < 0 or self.fraction_of_daily_salary_per_leave > 1
):
frappe.throw(_("The fraction of Daily Salary per Leave should be between 0 and 1"))
def clear_cache(self):
from hrms.payroll.doctype.salary_slip.salary_slip import LEAVE_TYPE_MAP
frappe.cache().delete_value(LEAVE_TYPE_MAP)
return super().clear_cache()
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_type/leave_type.py
|
Python
|
agpl-3.0
| 1,985
|
def get_data():
return {
"fieldname": "leave_type",
"transactions": [
{
"items": ["Leave Allocation", "Leave Application"],
},
{"items": ["Attendance", "Leave Encashment"]},
],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/leave_type/leave_type_dashboard.py
|
Python
|
agpl-3.0
| 200
|
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Offer Term", {
refresh: function (frm) {},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/offer_term/offer_term.js
|
JavaScript
|
agpl-3.0
| 189
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class OfferTerm(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/offer_term/offer_term.py
|
Python
|
agpl-3.0
| 216
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Purpose of Travel", {
refresh: function (frm) {},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/purpose_of_travel/purpose_of_travel.js
|
JavaScript
|
agpl-3.0
| 196
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class PurposeofTravel(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/purpose_of_travel/purpose_of_travel.py
|
Python
|
agpl-3.0
| 205
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("PWA Notification", {
// refresh(frm) {
// },
// });
|
2302_79757062/hrms
|
hrms/hr/doctype/pwa_notification/pwa_notification.js
|
JavaScript
|
agpl-3.0
| 199
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
import hrms
class PWANotification(Document):
def on_update(self):
hrms.refetch_resource("hrms:notifications", self.to_user)
def after_insert(self):
self.send_push_notification()
def send_push_notification(self):
try:
from frappe.push_notification import PushNotification
push_notification = PushNotification("hrms")
if push_notification.is_enabled():
push_notification.send_notification_to_user(
self.to_user,
self.reference_document_type,
self.message,
link=self.get_notification_link(),
icon=f"{frappe.utils.get_url()}/assets/hrms/manifest/favicon-196.png",
)
except ImportError:
# push notifications are not supported in the current framework version
pass
except Exception:
self.log_error(f"Error sending push notification: {self.name}")
def get_notification_link(self):
base_url = f"{frappe.utils.get_url()}/hrms"
if self.reference_document_type == "Leave Application":
return f"{base_url}/leave-applications/{self.reference_document_name}"
elif self.reference_document_type == "Expense Claim":
return f"{base_url}/expense-claims/{self.reference_document_name}"
return base_url
|
2302_79757062/hrms
|
hrms/hr/doctype/pwa_notification/pwa_notification.py
|
Python
|
agpl-3.0
| 1,346
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Shift Assignment", {
refresh: function (frm) {},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment/shift_assignment.js
|
JavaScript
|
agpl-3.0
| 195
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from datetime import datetime, timedelta
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.query_builder import Criterion
from frappe.utils import add_days, cint, cstr, get_link_to_form, get_time, getdate, now_datetime
from hrms.hr.utils import validate_active_employee
from hrms.utils import generate_date_range
class OverlappingShiftError(frappe.ValidationError):
pass
class MultipleShiftError(frappe.ValidationError):
pass
class ShiftAssignment(Document):
def validate(self):
validate_active_employee(self.employee)
if self.end_date:
self.validate_from_to_dates("start_date", "end_date")
self.validate_overlapping_shifts()
def on_update_after_submit(self):
if self.end_date:
self.validate_from_to_dates("start_date", "end_date")
self.validate_overlapping_shifts()
def on_cancel(self):
self.validate_employee_checkin()
self.validate_attendance()
def validate_employee_checkin(self):
checkins = frappe.get_all(
"Employee Checkin",
filters={
"employee": self.employee,
"shift": self.shift_type,
"time": ["between", [self.start_date, self.end_date]],
},
pluck="name",
)
if checkins:
frappe.throw(
_("Cannot cancel Shift Assignment: {0} as it is linked to Employee Checkin: {1}").format(
self.name, get_link_to_form("Employee Checkin", checkins[0])
)
)
def validate_attendance(self):
attendances = frappe.get_all(
"Attendance",
filters={
"employee": self.employee,
"shift": self.shift_type,
"attendance_date": ["between", [self.start_date, self.end_date]],
},
pluck="name",
)
if attendances:
frappe.throw(
_("Cannot cancel Shift Assignment: {0} as it is linked to Attendance: {1}").format(
self.name, get_link_to_form("Attendance", attendances[0])
)
)
def validate_overlapping_shifts(self):
if self.status == "Inactive":
return
overlapping_dates = self.get_overlapping_dates()
if len(overlapping_dates):
self.validate_same_date_multiple_shifts(overlapping_dates)
# if dates are overlapping, check if timings are overlapping, else allow
for d in overlapping_dates:
if has_overlapping_timings(self.shift_type, d.shift_type):
self.throw_overlap_error(d)
def validate_same_date_multiple_shifts(self, overlapping_dates):
if cint(frappe.db.get_single_value("HR Settings", "allow_multiple_shift_assignments")):
if not self.docstatus:
frappe.msgprint(
_(
"Warning: {0} already has an active Shift Assignment {1} for some/all of these dates."
).format(
frappe.bold(self.employee),
get_link_to_form("Shift Assignment", overlapping_dates[0].name),
)
)
else:
msg = _("{0} already has an active Shift Assignment {1} for some/all of these dates.").format(
frappe.bold(self.employee),
get_link_to_form("Shift Assignment", overlapping_dates[0].name),
)
msg += "<br><br>"
msg += _("To allow this, enable {0} under {1}.").format(
frappe.bold(_("Allow Multiple Shift Assignments for Same Date")),
get_link_to_form("HR Settings", "HR Settings"),
)
frappe.throw(
title=_("Multiple Shift Assignments"),
msg=msg,
exc=MultipleShiftError,
)
def get_overlapping_dates(self):
if not self.name:
self.name = "New Shift Assignment"
shift = frappe.qb.DocType("Shift Assignment")
query = (
frappe.qb.from_(shift)
.select(shift.name, shift.shift_type, shift.docstatus, shift.status)
.where(
(shift.employee == self.employee)
& (shift.docstatus == 1)
& (shift.name != self.name)
& (shift.status == "Active")
& ((shift.end_date >= self.start_date) | (shift.end_date.isnull()))
)
)
if self.end_date:
query = query.where(shift.start_date <= self.end_date)
return query.run(as_dict=True)
def throw_overlap_error(self, shift_details):
shift_details = frappe._dict(shift_details)
if shift_details.docstatus == 1 and shift_details.status == "Active":
msg = _(
"Employee {0} already has an active Shift {1}: {2} that overlaps within this period."
).format(
frappe.bold(self.employee),
frappe.bold(shift_details.shift_type),
get_link_to_form("Shift Assignment", shift_details.name),
)
frappe.throw(msg, title=_("Overlapping Shifts"), exc=OverlappingShiftError)
def has_overlapping_timings(shift_1: str, shift_2: str) -> bool:
"""
Accepts two shift types and checks whether their timings are overlapping
"""
s1 = frappe.db.get_value("Shift Type", shift_1, ["start_time", "end_time"], as_dict=True)
s2 = frappe.db.get_value("Shift Type", shift_2, ["start_time", "end_time"], as_dict=True)
for d in [s1, s2]:
if d.end_time <= d.start_time:
d.end_time += timedelta(days=1)
return s1.end_time > s2.start_time and s1.start_time < s2.end_time
@frappe.whitelist()
def get_events(start, end, filters=None):
employee = frappe.db.get_value(
"Employee", {"user_id": frappe.session.user}, ["name", "company"], as_dict=True
)
if employee:
employee = employee.name
else:
employee = ""
assignments = get_shift_assignments(start, end, filters)
return get_shift_events(assignments)
def get_shift_assignments(start: str, end: str, filters: str | list | None = None) -> list[dict]:
import json
if isinstance(filters, str):
filters = json.loads(filters)
if not filters:
filters = []
filters.extend([["start_date", "<=", end], ["docstatus", "=", 1]])
or_filters = [["end_date", ">=", start], ["end_date", "is", "not set"]]
return frappe.get_list(
"Shift Assignment",
filters=filters,
or_filters=or_filters,
fields=[
"name",
"start_date",
"end_date",
"employee_name",
"employee",
"docstatus",
"shift_type",
],
)
def get_shift_events(assignments: list[dict]) -> list[dict]:
events = []
shift_timing_map = get_shift_type_timing([d.shift_type for d in assignments])
for d in assignments:
daily_event_start = d.start_date
daily_event_end = d.end_date or getdate()
shift_start = shift_timing_map[d.shift_type]["start_time"]
shift_end = shift_timing_map[d.shift_type]["end_time"]
delta = timedelta(days=1)
while daily_event_start <= daily_event_end:
start_timing = frappe.utils.get_datetime(daily_event_start) + shift_start
if shift_start > shift_end:
# shift spans across 2 days
end_timing = frappe.utils.get_datetime(daily_event_start) + shift_end + delta
else:
end_timing = frappe.utils.get_datetime(daily_event_start) + shift_end
event = {
"name": d.name,
"doctype": "Shift Assignment",
"start_date": start_timing,
"end_date": end_timing,
"title": cstr(d.employee_name) + ": " + cstr(d.shift_type),
"docstatus": d.docstatus,
"allDay": 0,
"convertToUserTz": 0,
}
if event not in events:
events.append(event)
daily_event_start += delta
return events
def get_shift_type_timing(shift_types):
shift_timing_map = {}
data = frappe.get_all(
"Shift Type",
filters={"name": ("IN", shift_types)},
fields=["name", "start_time", "end_time"],
)
for d in data:
shift_timing_map[d.name] = d
return shift_timing_map
def get_shift_for_time(shifts: list[dict], for_timestamp: datetime) -> dict:
"""Returns shift with details for given timestamp"""
valid_shifts = []
for assignment in shifts:
shift_details = get_shift_details(assignment.shift_type, for_timestamp=for_timestamp)
if _is_shift_outside_assignment_period(shift_details, assignment):
continue
if _is_timestamp_within_shift(shift_details, for_timestamp):
valid_shifts.append(shift_details)
valid_shifts.sort(key=lambda x: x["actual_start"])
_adjust_overlapping_shifts(valid_shifts)
return get_exact_shift(valid_shifts, for_timestamp)
def _is_shift_outside_assignment_period(shift_details: dict, assignment: dict) -> bool:
"""
Compares shift's actual start and end dates with assignment dates
and returns True is shift is outside assignment period
"""
# start time > end time, means its a midnight shift
is_midnight_shift = shift_details.actual_start.time() > shift_details.actual_end.time()
if _is_shift_start_before_assignment(shift_details, assignment, is_midnight_shift):
return True
if assignment.end_date and _is_shift_end_after_assignment(shift_details, assignment, is_midnight_shift):
return True
return False
def _is_shift_start_before_assignment(shift_details: dict, assignment: dict, is_midnight_shift: bool) -> bool:
if shift_details.actual_start.date() < assignment.start_date:
# log's start date can only precede assignment's start date if its a midnight shift
if not is_midnight_shift:
return True
# if actual start and start dates are same but it precedes assignment start date
# then its actually a shift that starts on the previous day, making it invalid
if shift_details.actual_start.date() == shift_details.start_datetime.date():
return True
# actual start is not the prev assignment day
# then its a shift that starts even before the prev day, making it invalid
prev_assignment_day = add_days(assignment.start_date, -1)
if shift_details.actual_start.date() != prev_assignment_day:
return True
return False
def _is_shift_end_after_assignment(shift_details: dict, assignment: dict, is_midnight_shift: bool) -> bool:
if shift_details.actual_start.date() > assignment.end_date:
return True
# log's end date can only exceed assignment's end date if its a midnight shift
if shift_details.actual_end.date() > assignment.end_date:
if not is_midnight_shift:
return True
# if shift starts & ends on the same day along with shift margin
# then actual end cannot exceed assignment's end date, making it invalid
if (
shift_details.actual_end.date() == shift_details.end_datetime.date()
and shift_details.start_datetime.date() == shift_details.end_datetime.date()
):
return True
# actual end is not the immediate next assignment day
# then its a shift that ends even after the next day, making it invalid
next_assignment_day = add_days(assignment.end_date, 1)
if shift_details.actual_end.date() != next_assignment_day:
return True
return False
def _is_timestamp_within_shift(shift_details: dict, for_timestamp: datetime) -> bool:
"""Checks whether the timestamp is within shift's actual start and end datetime"""
return shift_details.actual_start <= for_timestamp <= shift_details.actual_end
def _adjust_overlapping_shifts(shifts: dict):
"""
Compares 2 consecutive shifts and adjusts start and end times
if they are overlapping within grace period
"""
for i in range(len(shifts) - 1):
curr_shift = shifts[i]
next_shift = shifts[i + 1]
if curr_shift and next_shift:
next_shift.actual_start = max(curr_shift.end_datetime, next_shift.actual_start)
curr_shift.actual_end = min(next_shift.actual_start, curr_shift.actual_end)
shifts[i] = curr_shift
shifts[i + 1] = next_shift
def get_shifts_for_date(employee: str, for_timestamp: datetime) -> list[dict[str, str]]:
"""Returns list of shifts with details for given date"""
for_date = for_timestamp.date()
prev_day = add_days(for_date, -1)
next_day = add_days(for_date, 1)
assignment = frappe.qb.DocType("Shift Assignment")
return (
frappe.qb.from_(assignment)
.select(assignment.name, assignment.shift_type, assignment.start_date, assignment.end_date)
.where(
(assignment.employee == employee)
& (assignment.docstatus == 1)
& (assignment.status == "Active")
# for shifts that exceed a day in duration or margins
# eg: shift = 00:30:00 - 10:00:00, including margins (1 hr) = 23:30:00 - 11:00:00
# if for_timestamp = 23:30:00 (falls in before shift margin), also fetch next days shift to find the correct shift
& (assignment.start_date <= next_day)
& (
Criterion.any(
[
assignment.end_date.isnull(),
(
assignment.end_date.isnotnull()
# for shifts that exceed a day in duration or margins
# eg: shift = 15:00 - 23:30, including margins (1 hr) = 14:00 - 00:30
# if for_timestamp = 00:30:00 (falls in after shift margin), also fetch prev days shift to find the correct shift
& (prev_day <= assignment.end_date)
),
]
)
)
)
).run(as_dict=True)
def get_shift_for_timestamp(employee: str, for_timestamp: datetime) -> dict:
shifts = get_shifts_for_date(employee, for_timestamp)
if shifts:
return get_shift_for_time(shifts, for_timestamp)
return {}
def get_employee_shift(
employee: str,
for_timestamp: datetime | None = None,
consider_default_shift: bool = False,
next_shift_direction: str | None = None,
) -> dict:
"""Returns a Shift Type for the given employee on the given date
:param employee: Employee for which shift is required.
:param for_timestamp: DateTime on which shift is required
:param consider_default_shift: If set to true, default shift is taken when no shift assignment is found.
:param next_shift_direction: One of: None, 'forward', 'reverse'. Direction to look for next shift if shift not found on given date.
"""
if for_timestamp is None:
for_timestamp = now_datetime()
shift_details = get_shift_for_timestamp(employee, for_timestamp)
# if shift assignment is not found, consider default shift
default_shift = frappe.db.get_value("Employee", employee, "default_shift", cache=True)
if not shift_details and consider_default_shift:
shift_details = get_shift_details(default_shift, for_timestamp)
# if no shift is found, find next or prev shift assignment based on direction
if not shift_details and next_shift_direction:
shift_details = get_prev_or_next_shift(
employee, for_timestamp, consider_default_shift, default_shift, next_shift_direction
)
return shift_details or {}
def get_prev_or_next_shift(
employee: str,
for_timestamp: datetime,
consider_default_shift: bool,
default_shift: str,
next_shift_direction: str,
) -> dict:
"""Returns a dict of shift details for the next or prev shift based on the next_shift_direction"""
MAX_DAYS = 366
shift_details = {}
if consider_default_shift and default_shift:
direction = -1 if next_shift_direction == "reverse" else 1
for i in range(MAX_DAYS):
date = for_timestamp + timedelta(days=direction * (i + 1))
shift_details = get_employee_shift(employee, date, consider_default_shift, None)
if shift_details:
return shift_details
else:
direction = "<" if next_shift_direction == "reverse" else ">"
sort_order = "desc" if next_shift_direction == "reverse" else "asc"
shift_dates = frappe.get_all(
"Shift Assignment",
["start_date", "end_date"],
{
"employee": employee,
"start_date": (direction, for_timestamp.date()),
"docstatus": 1,
"status": "Active",
},
as_list=True,
limit=MAX_DAYS,
order_by="start_date " + sort_order,
)
for date_range in shift_dates:
# midnight shifts will span more than a day
start_date, end_date = getdate(date_range[0]), getdate(add_days(date_range[1], 1))
if reverse := (next_shift_direction == "reverse"):
end_date = min(end_date, for_timestamp.date())
elif next_shift_direction == "forward":
start_date = max(start_date, for_timestamp.date())
for dt in generate_date_range(start_date, end_date, reverse=reverse):
shift_details = get_employee_shift(
employee, datetime.combine(dt, for_timestamp.time()), consider_default_shift, None
)
if shift_details:
return shift_details
return shift_details or {}
def get_employee_shift_timings(
employee: str, for_timestamp: datetime | None = None, consider_default_shift: bool = False
) -> list[dict]:
"""Returns previous shift, current/upcoming shift, next_shift for the given timestamp and employee"""
if for_timestamp is None:
for_timestamp = now_datetime()
# write and verify a test case for midnight shift.
prev_shift = curr_shift = next_shift = None
curr_shift = get_employee_shift(employee, for_timestamp, consider_default_shift, "forward")
if curr_shift:
next_shift = get_employee_shift(
employee,
curr_shift.start_datetime + timedelta(days=1),
consider_default_shift,
"forward",
)
prev_shift = get_employee_shift(
employee,
(curr_shift.end_datetime if curr_shift else for_timestamp) + timedelta(days=-1),
consider_default_shift,
"reverse",
)
if curr_shift:
# adjust actual start and end times if they are overlapping with grace period (before start and after end)
if prev_shift:
curr_shift.actual_start = (
prev_shift.end_datetime
if curr_shift.actual_start < prev_shift.end_datetime
else curr_shift.actual_start
)
prev_shift.actual_end = (
curr_shift.actual_start
if prev_shift.actual_end > curr_shift.actual_start
else prev_shift.actual_end
)
if next_shift:
next_shift.actual_start = (
curr_shift.end_datetime
if next_shift.actual_start < curr_shift.end_datetime
else next_shift.actual_start
)
curr_shift.actual_end = (
next_shift.actual_start
if curr_shift.actual_end > next_shift.actual_start
else curr_shift.actual_end
)
return prev_shift, curr_shift, next_shift
def get_actual_start_end_datetime_of_shift(
employee: str, for_timestamp: datetime, consider_default_shift: bool = False
) -> dict:
"""Returns a Dict containing shift details with actual_start and actual_end datetime values
Here 'actual' means taking into account the "begin_check_in_before_shift_start_time" and "allow_check_out_after_shift_end_time".
Empty Dict is returned if the timestamp is outside any actual shift timings.
:param employee (str): Employee name
:param for_timestamp (datetime, optional): Datetime value of checkin, if not provided considers current datetime
:param consider_default_shift (bool, optional): Flag (defaults to False) to specify whether to consider
default shift in employee master if no shift assignment is found
"""
shift_timings_as_per_timestamp = get_employee_shift_timings(
employee, for_timestamp, consider_default_shift
)
return get_exact_shift(shift_timings_as_per_timestamp, for_timestamp)
def get_exact_shift(shifts: list, for_timestamp: datetime) -> dict:
"""Returns the shift details (dict) for the exact shift in which the 'for_timestamp' value falls among multiple shifts"""
return next(
(
shift
for shift in shifts
if shift and for_timestamp >= shift.actual_start and for_timestamp <= shift.actual_end
),
{},
)
def get_shift_details(shift_type_name: str, for_timestamp: datetime | None = None) -> dict:
"""Returns a Dict containing shift details with the following data:
'shift_type' - Object of DocType Shift Type,
'start_datetime' - datetime of shift start on given timestamp,
'end_datetime' - datetime of shift end on given timestamp,
'actual_start' - datetime of shift start after adding 'begin_check_in_before_shift_start_time',
'actual_end' - datetime of shift end after adding 'allow_check_out_after_shift_end_time' (None is returned if this is zero)
:param shift_type_name (str): shift type name for which shift_details are required.
:param for_timestamp (datetime, optional): Datetime value of checkin, if not provided considers current datetime
"""
if not shift_type_name:
return frappe._dict()
if for_timestamp is None:
for_timestamp = now_datetime()
shift_type = get_shift_type(shift_type_name)
start_datetime, end_datetime = get_shift_timings(shift_type, for_timestamp)
actual_start = start_datetime - timedelta(minutes=shift_type.begin_check_in_before_shift_start_time)
actual_end = end_datetime + timedelta(minutes=shift_type.allow_check_out_after_shift_end_time)
return frappe._dict(
{
"shift_type": shift_type,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"actual_start": actual_start,
"actual_end": actual_end,
}
)
def get_shift_type(shift_type_name: str) -> dict:
return frappe.get_cached_value(
"Shift Type",
shift_type_name,
[
"name",
"start_time",
"end_time",
"begin_check_in_before_shift_start_time",
"allow_check_out_after_shift_end_time",
],
as_dict=1,
)
def get_shift_timings(shift_type: dict, for_timestamp: datetime) -> tuple:
start_time = shift_type.start_time
end_time = shift_type.end_time
shift_actual_start = get_time(
datetime.combine(for_timestamp, datetime.min.time())
+ start_time
- timedelta(minutes=shift_type.begin_check_in_before_shift_start_time)
)
shift_actual_end = get_time(
datetime.combine(for_timestamp, datetime.min.time())
+ end_time
+ timedelta(minutes=shift_type.allow_check_out_after_shift_end_time)
)
for_time = get_time(for_timestamp.time())
start_datetime = end_datetime = None
if start_time > end_time:
# shift spans across 2 different days
if for_time >= shift_actual_start:
# if for_timestamp is greater than start time, it's within the first day
start_datetime = datetime.combine(for_timestamp, datetime.min.time()) + start_time
for_timestamp += timedelta(days=1)
end_datetime = datetime.combine(for_timestamp, datetime.min.time()) + end_time
elif for_time < shift_actual_start:
# if for_timestamp is less than start time, it's within the second day
end_datetime = datetime.combine(for_timestamp, datetime.min.time()) + end_time
for_timestamp += timedelta(days=-1)
start_datetime = datetime.combine(for_timestamp, datetime.min.time()) + start_time
elif (
shift_actual_start > shift_actual_end
and for_time < shift_actual_start
and get_time(end_time) > shift_actual_end
):
# for_timestamp falls within the margin period in the second day (after midnight)
# so shift started and ended on the previous day
for_timestamp += timedelta(days=-1)
end_datetime = datetime.combine(for_timestamp, datetime.min.time()) + end_time
start_datetime = datetime.combine(for_timestamp, datetime.min.time()) + start_time
elif (
shift_actual_start > shift_actual_end
and for_time > shift_actual_end
and get_time(start_time) < shift_actual_start
):
# for_timestamp falls within the margin period in the first day (before midnight)
# so shift started and ended on the next day
for_timestamp += timedelta(days=1)
start_datetime = datetime.combine(for_timestamp, datetime.min.time()) + start_time
end_datetime = datetime.combine(for_timestamp, datetime.min.time()) + end_time
else:
# start and end timings fall on the same day
start_datetime = datetime.combine(for_timestamp, datetime.min.time()) + start_time
end_datetime = datetime.combine(for_timestamp, datetime.min.time()) + end_time
return start_datetime, end_datetime
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment/shift_assignment.py
|
Python
|
agpl-3.0
| 22,626
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.views.calendar["Shift Assignment"] = {
field_map: {
start: "start_date",
end: "end_date",
id: "name",
docstatus: 1,
allDay: "allDay",
convertToUserTz: "convertToUserTz",
},
get_events_method: "hrms.hr.doctype.shift_assignment.shift_assignment.get_events",
};
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment/shift_assignment_calendar.js
|
JavaScript
|
agpl-3.0
| 403
|
frappe.listview_settings["Shift Assignment"] = {
onload: function (list_view) {
list_view.page.add_inner_button(
__("Shift Assignment Tool"),
function () {
frappe.set_route("Form", "Shift Assignment Tool");
},
__("View"),
);
list_view.page.add_inner_button(
__("Roster"),
function () {
window.location.href = "/hr/roster";
},
__("View"),
);
},
};
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment/shift_assignment_list.js
|
JavaScript
|
agpl-3.0
| 390
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Shift Assignment Schedule", {
// refresh(frm) {
// },
// });
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment_schedule/shift_assignment_schedule.js
|
JavaScript
|
agpl-3.0
| 208
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from frappe.utils import add_days, get_weekday, nowdate
from hrms.hr.doctype.shift_assignment_tool.shift_assignment_tool import create_shift_assignment
class ShiftAssignmentSchedule(Document):
def create_shifts(self, start_date: str, end_date: str | None = None) -> None:
gap = {
"Every Week": 0,
"Every 2 Weeks": 1,
"Every 3 Weeks": 2,
"Every 4 Weeks": 3,
}[self.frequency]
date = start_date
individual_assignment_start = None
week_end_day = get_weekday(add_days(start_date, -1))
repeat_on_days = [day.day for day in self.repeat_on_days]
if not end_date:
end_date = add_days(start_date, 90)
while date <= end_date:
weekday = get_weekday(date)
if weekday in repeat_on_days:
if not individual_assignment_start:
individual_assignment_start = date
if date == end_date:
self.create_individual_assignment(individual_assignment_start, date)
elif individual_assignment_start:
self.create_individual_assignment(individual_assignment_start, add_days(date, -1))
individual_assignment_start = None
if weekday == week_end_day and gap:
if individual_assignment_start:
self.create_individual_assignment(individual_assignment_start, date)
individual_assignment_start = None
date = add_days(date, 7 * gap)
date = add_days(date, 1)
def create_individual_assignment(self, start_date, end_date):
create_shift_assignment(
self.employee, self.company, self.shift_type, start_date, end_date, self.shift_status, self.name
)
self.create_shifts_after = end_date
self.save()
def process_auto_shift_creation():
schedules = frappe.get_all(
"Shift Assignment Schedule",
filters={"enabled": 1, "create_shifts_after": ["<=", nowdate()]},
pluck="name",
)
for d in schedules:
doc = frappe.get_doc("Shift Assignment Schedule", d)
doc.create_shifts(add_days(doc.create_shifts_after, 1))
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment_schedule/shift_assignment_schedule.py
|
Python
|
agpl-3.0
| 2,057
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Shift Assignment Tool", {
setup(frm) {
hrms.setup_employee_filter_group(frm);
},
refresh(frm) {
frm.page.clear_indicator();
frm.disable_save();
frm.trigger("set_primary_action");
frm.trigger("get_employees");
hrms.handle_realtime_bulk_action_notification(
frm,
"completed_bulk_shift_assignment",
"Shift Assignment",
);
hrms.handle_realtime_bulk_action_notification(
frm,
"completed_bulk_shift_request_processing",
"Shift Request",
);
},
action(frm) {
frm.trigger("set_primary_action");
frm.trigger("get_employees");
},
company(frm) {
frm.trigger("get_employees");
},
shift_type(frm) {
frm.trigger("get_employees");
},
status(frm) {
frm.trigger("get_employees");
},
start_date(frm) {
if (frm.doc.start_date > frm.doc.end_date) frm.set_value("end_date", null);
frm.trigger("get_employees");
},
end_date(frm) {
if (frm.doc.end_date < frm.doc.start_date) frm.set_value("start_date", null);
frm.trigger("get_employees");
},
shift_type_filter(frm) {
frm.trigger("get_employees");
},
approver(frm) {
frm.trigger("get_employees");
},
from_date(frm) {
if (frm.doc.from_date > frm.doc.to_date) frm.set_value("to_date", null);
frm.trigger("get_employees");
},
to_date(frm) {
if (frm.doc.to_date < frm.doc.from_date) frm.set_value("from_date", null);
frm.trigger("get_employees");
},
branch(frm) {
frm.trigger("get_employees");
},
department(frm) {
frm.trigger("get_employees");
},
designation(frm) {
frm.trigger("get_employees");
},
grade(frm) {
frm.trigger("get_employees");
},
employment_type(frm) {
frm.trigger("get_employees");
},
set_primary_action(frm) {
const select_rows_section_head = document
.querySelector('[data-fieldname="select_rows_section"]')
.querySelector(".section-head");
if (frm.doc.action === "Assign Shift") {
frm.clear_custom_buttons();
frm.page.set_primary_action(__("Assign Shift"), () => {
frm.trigger("assign_shift");
});
select_rows_section_head.textContent = __("Select Employees");
return;
}
frm.page.clear_primary_action();
frm.page.add_inner_button(
__("Approve"),
() => {
frm.events.process_shift_requests(frm, "Approved");
},
__("Process Requests"),
);
frm.page.add_inner_button(
__("Reject"),
() => {
frm.events.process_shift_requests(frm, "Rejected");
},
__("Process Requests"),
);
frm.page.set_inner_btn_group_as_primary(__("Process Requests"));
frm.page.clear_menu();
select_rows_section_head.textContent = __("Select Shift Requests");
},
get_employees(frm) {
if (frm.doc.action === "Assign Shift" && !(frm.doc.shift_type && frm.doc.start_date))
return frm.events.render_employees_datatable(frm, []);
frm.call({
method: "get_employees",
args: {
advanced_filters: frm.advanced_filters || [],
},
doc: frm.doc,
}).then((r) => frm.events.render_employees_datatable(frm, r.message));
},
render_employees_datatable(frm, employees) {
let columns = undefined;
let no_data_message = undefined;
if (frm.doc.action === "Assign Shift") {
columns = frm.events.get_assign_shift_datatable_columns();
no_data_message = __(
frm.doc.shift_type && frm.doc.start_date
? "There are no employees without Shift Assignments for these dates based on the given filters."
: "Please select Shift Type and assignment date(s).",
);
} else {
columns = frm.events.get_process_shift_requests_datatable_columns();
no_data_message = "There are no open Shift Requests based on the given filters.";
}
hrms.render_employees_datatable(frm, columns, employees, no_data_message);
},
get_assign_shift_datatable_columns() {
return [
{
name: "employee",
id: "employee",
content: __("Employee"),
},
{
name: "employee_name",
id: "employee_name",
content: __("Employee Name"),
},
{
name: "branch",
id: "branch",
content: __("Branch"),
},
{
name: "department",
id: "department",
content: __("Department"),
},
{
name: "default_shift",
id: "default_shift",
content: __("Default Shift"),
},
].map((x) => ({
...x,
editable: false,
focusable: false,
dropdown: false,
align: "left",
}));
},
get_process_shift_requests_datatable_columns() {
return [
{
name: "shift_request",
id: "shift_request",
content: __("Shift Request"),
},
{
name: "employee",
id: "employee_name",
content: __("Employee"),
},
{
name: "shift_type",
id: "shift_type",
content: __("Shift Type"),
},
{
name: "from_date",
id: "from_date",
content: __("From Date"),
},
{
name: "to_date",
id: "to_date",
content: __("To Date"),
},
].map((x) => ({
...x,
editable: false,
focusable: false,
dropdown: false,
align: "left",
}));
},
assign_shift(frm) {
const rows = frm.employees_datatable.datamanager.data;
const selected_employees = [];
const checked_row_indexes = frm.employees_datatable.rowmanager.getCheckedRows();
checked_row_indexes.forEach((idx) => {
selected_employees.push(rows[idx].employee);
});
hrms.validate_mandatory_fields(frm, selected_employees);
frappe.confirm(__("Assign Shift to {0} employee(s)?", [selected_employees.length]), () => {
frm.events.bulk_assign_shift(frm, selected_employees);
});
},
bulk_assign_shift(frm, employees) {
frm.call({
method: "bulk_assign_shift",
doc: frm.doc,
args: {
employees: employees,
},
freeze: true,
freeze_message: __("Assigning Shift"),
});
},
process_shift_requests(frm, status) {
const rows = frm.employees_datatable.datamanager.data;
const selected_requests = [];
const checked_row_indexes = frm.employees_datatable.rowmanager.getCheckedRows();
checked_row_indexes.forEach((idx) => {
selected_requests.push({
shift_request: rows[idx].name,
employee: rows[idx].employee,
});
});
hrms.validate_mandatory_fields(frm, selected_requests, "Shift Requests");
frappe.confirm(
__("Process {0} Shift Request(s) as <b>{1}</b>?", [selected_requests.length, status]),
() => {
frm.events.bulk_process_shift_requests(frm, selected_requests, status);
},
);
},
bulk_process_shift_requests(frm, shift_requests, status) {
frm.call({
method: "bulk_process_shift_requests",
doc: frm.doc,
args: {
shift_requests: shift_requests,
status: status,
},
freeze: true,
freeze_message: __("Processing Requests"),
});
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment_tool/shift_assignment_tool.js
|
JavaScript
|
agpl-3.0
| 6,676
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from datetime import timedelta
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.query_builder import Case, Interval
from frappe.query_builder.terms import SubQuery
from frappe.utils import get_link_to_form
from hrms.hr.utils import validate_bulk_tool_fields
class ShiftAssignmentTool(Document):
@frappe.whitelist()
def get_employees(self, advanced_filters: list | None = None) -> list:
if not advanced_filters:
advanced_filters = []
quick_filter_fields = [
"company",
"branch",
"department",
"designation",
"grade",
"employment_type",
]
filters = [[d, "=", self.get(d)] for d in quick_filter_fields if self.get(d)]
filters += advanced_filters
if self.action == "Assign Shift":
return self.get_employees_for_assigning_shift(filters)
return self.get_shift_requests(filters)
def get_employees_for_assigning_shift(self, filters):
Employee = frappe.qb.DocType("Employee")
query = frappe.qb.get_query(
Employee,
fields=[
Employee.employee,
Employee.employee_name,
Employee.branch,
Employee.department,
Employee.default_shift,
],
filters=filters,
).where(
(Employee.status == "Active")
& (Employee.date_of_joining <= self.start_date)
& ((Employee.relieving_date >= self.start_date) | (Employee.relieving_date.isnull()))
)
if self.end_date:
query = query.where(
(Employee.relieving_date >= self.end_date) | (Employee.relieving_date.isnull())
)
if self.status == "Active":
query = query.where(Employee.employee.notin(SubQuery(self.get_query_for_employees_with_shifts())))
return query.run(as_dict=True)
def get_shift_requests(self, filters):
Employee = frappe.qb.DocType("Employee")
ShiftRequest = frappe.qb.DocType("Shift Request")
query = (
frappe.qb.get_query(
Employee,
fields=[Employee.employee, Employee.employee_name],
filters=filters,
)
.inner_join(ShiftRequest)
.on(ShiftRequest.employee == Employee.name)
.select(
ShiftRequest.name,
ShiftRequest.shift_type,
ShiftRequest.from_date,
ShiftRequest.to_date,
)
.where(ShiftRequest.status == "Draft")
)
if self.shift_type_filter:
query = query.where(ShiftRequest.shift_type == self.shift_type_filter)
if self.approver:
query = query.where(ShiftRequest.approver == self.approver)
if self.from_date:
query = query.where((ShiftRequest.to_date >= self.from_date) | (ShiftRequest.to_date.isnull()))
if self.to_date:
query = query.where(ShiftRequest.from_date <= self.to_date)
data = query.run(as_dict=True)
for d in data:
d.employee_name = d.employee + ": " + d.employee_name
d.shift_request = get_link_to_form("Shift Request", d.name)
return data
def get_query_for_employees_with_shifts(self):
ShiftAssignment = frappe.qb.DocType("Shift Assignment")
query = frappe.qb.from_(ShiftAssignment)
allow_multiple_shifts = frappe.db.get_single_value("HR Settings", "allow_multiple_shift_assignments")
# join Shift Type if multiple shifts are allowed as we need to know shift timings only in this case
if allow_multiple_shifts:
ShiftType = frappe.qb.DocType("Shift Type")
query = query.left_join(ShiftType).on(ShiftAssignment.shift_type == ShiftType.name)
query = (
query.select(ShiftAssignment.employee)
.distinct()
.where(
(ShiftAssignment.status == "Active")
& (ShiftAssignment.docstatus == 1)
# check for overlapping dates
& ((ShiftAssignment.end_date >= self.start_date) | (ShiftAssignment.end_date.isnull()))
)
)
if self.end_date:
query = query.where(ShiftAssignment.start_date <= self.end_date)
# check for overlapping timings if multiple shifts are allowed
if allow_multiple_shifts:
shift_start, shift_end = frappe.db.get_value(
"Shift Type", self.shift_type, ["start_time", "end_time"]
)
# turn it into a 48 hour clock for easier conditioning while considering overnight shifts
if shift_end < shift_start:
shift_end += timedelta(hours=24)
end_time_case = (
Case()
.when(ShiftType.end_time < ShiftType.start_time, ShiftType.end_time + Interval(hours=24))
.else_(ShiftType.end_time)
)
query = query.where((end_time_case >= shift_start) & (ShiftType.start_time <= shift_end))
return query
@frappe.whitelist()
def bulk_assign_shift(self, employees: list):
mandatory_fields = ["company", "shift_type", "start_date"]
validate_bulk_tool_fields(self, mandatory_fields, employees, "start_date", "end_date")
if len(employees) <= 30:
return self._bulk_assign_shift(employees)
frappe.enqueue(self._bulk_assign_shift, timeout=3000, employees=employees)
frappe.msgprint(
_("Creation of Shift Assignments has been queued. It may take a few minutes."),
alert=True,
indicator="blue",
)
def _bulk_assign_shift(self, employees: list):
success, failure = [], []
count = 0
savepoint = "before_shift_assignment"
for d in employees:
try:
frappe.db.savepoint(savepoint)
assignment = create_shift_assignment(
d, self.company, self.shift_type, self.start_date, self.end_date, self.status
)
except Exception:
frappe.db.rollback(save_point=savepoint)
frappe.log_error(
f"Bulk Assignment - Shift Assignment failed for employee {d}.",
reference_doctype="Shift Assignment",
)
failure.append(d)
else:
success.append({"doc": get_link_to_form("Shift Assignment", assignment), "employee": d})
count += 1
frappe.publish_progress(count * 100 / len(employees), title=_("Assigning Shift..."))
frappe.clear_messages()
frappe.publish_realtime(
"completed_bulk_shift_assignment",
message={"success": success, "failure": failure},
doctype="Shift Assignment Tool",
after_commit=True,
)
@frappe.whitelist()
def bulk_process_shift_requests(self, shift_requests: list, status: str):
if not shift_requests:
frappe.throw(
_("Please select at least one Shift Request to perform this action."),
title=_("No Shift Requests Selected"),
)
if len(shift_requests) <= 30:
return self._bulk_process_shift_requests(shift_requests, status)
frappe.enqueue(
self._bulk_process_shift_requests, timeout=3000, shift_requests=shift_requests, status=status
)
frappe.msgprint(
_("Processing of Shift Requests has been queued. It may take a few minutes."),
alert=True,
indicator="blue",
)
def _bulk_process_shift_requests(self, shift_requests: list, status: str):
success, failure = [], []
count = 0
for d in shift_requests:
try:
shift_request = frappe.get_doc("Shift Request", d["shift_request"])
shift_request.status = status
shift_request.save()
shift_request.submit()
except Exception:
frappe.log_error(
f"Bulk Processing - Processing failed for Shift Request {d['shift_request']}.",
reference_doctype="Shift Request",
)
failure.append(d["employee"])
else:
success.append(
{"doc": get_link_to_form("Shift Request", shift_request.name), "employee": d["employee"]}
)
count += 1
frappe.publish_progress(count * 100 / len(shift_requests), title=_("Processing Requests..."))
frappe.clear_messages()
frappe.publish_realtime(
"completed_bulk_shift_request_processing",
message={"success": success, "failure": failure, "for_processing": True},
doctype="Shift Assignment Tool",
after_commit=True,
)
def create_shift_assignment(
employee: str,
company: str,
shift_type: str,
start_date: str,
end_date: str,
status: str,
schedule: str | None = None,
) -> str:
assignment = frappe.new_doc("Shift Assignment")
assignment.employee = employee
assignment.company = company
assignment.shift_type = shift_type
assignment.start_date = start_date
assignment.end_date = end_date
assignment.status = status
assignment.schedule = schedule
assignment.save()
assignment.submit()
return assignment.name
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_assignment_tool/shift_assignment_tool.py
|
Python
|
agpl-3.0
| 8,014
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Shift Request", {
setup: function (frm) {
frm.set_query("approver", function () {
return {
query: "hrms.hr.doctype.department_approver.department_approver.get_approvers",
filters: {
employee: frm.doc.employee,
doctype: frm.doc.doctype,
},
};
});
frm.set_query("employee", erpnext.queries.employee);
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_request/shift_request.js
|
JavaScript
|
agpl-3.0
| 483
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.query_builder import Criterion
from frappe.utils import get_link_to_form
from hrms.hr.doctype.shift_assignment.shift_assignment import has_overlapping_timings
from hrms.hr.utils import share_doc_with_approver, validate_active_employee
class OverlappingShiftRequestError(frappe.ValidationError):
pass
class ShiftRequest(Document):
def validate(self):
validate_active_employee(self.employee)
self.validate_from_to_dates("from_date", "to_date")
self.validate_overlapping_shift_requests()
self.validate_approver()
self.validate_default_shift()
def on_update(self):
share_doc_with_approver(self, self.approver)
def on_submit(self):
if self.status not in ["Approved", "Rejected"]:
frappe.throw(_("Only Shift Request with status 'Approved' and 'Rejected' can be submitted"))
if self.status == "Approved":
assignment_doc = frappe.new_doc("Shift Assignment")
assignment_doc.company = self.company
assignment_doc.shift_type = self.shift_type
assignment_doc.employee = self.employee
assignment_doc.start_date = self.from_date
if self.to_date:
assignment_doc.end_date = self.to_date
assignment_doc.shift_request = self.name
assignment_doc.flags.ignore_permissions = 1
assignment_doc.insert()
assignment_doc.submit()
frappe.msgprint(
_("Shift Assignment: {0} created for Employee: {1}").format(
frappe.bold(assignment_doc.name), frappe.bold(self.employee)
)
)
def on_cancel(self):
shift_assignment_list = frappe.db.get_all(
"Shift Assignment", {"employee": self.employee, "shift_request": self.name, "docstatus": 1}
)
if shift_assignment_list:
for shift in shift_assignment_list:
shift_assignment_doc = frappe.get_doc("Shift Assignment", shift["name"])
shift_assignment_doc.cancel()
def validate_default_shift(self):
default_shift = frappe.get_value("Employee", self.employee, "default_shift")
if self.shift_type == default_shift:
frappe.throw(
_("You can not request for your Default Shift: {0}").format(frappe.bold(self.shift_type))
)
def validate_approver(self):
department = frappe.get_value("Employee", self.employee, "department")
shift_approver = frappe.get_value("Employee", self.employee, "shift_request_approver")
approvers = frappe.db.sql(
"""select approver from `tabDepartment Approver` where parent= %s and parentfield = 'shift_request_approver'""",
(department),
)
approvers = [approver[0] for approver in approvers]
approvers.append(shift_approver)
if self.approver not in approvers:
frappe.throw(_("Only Approvers can Approve this Request."))
def validate_overlapping_shift_requests(self):
overlapping_dates = self.get_overlapping_dates()
if len(overlapping_dates):
# if dates are overlapping, check if timings are overlapping, else allow
for d in overlapping_dates:
if has_overlapping_timings(self.shift_type, d.shift_type):
self.throw_overlap_error(d)
def get_overlapping_dates(self):
if not self.name:
self.name = "New Shift Request"
shift = frappe.qb.DocType("Shift Request")
query = (
frappe.qb.from_(shift)
.select(shift.name, shift.shift_type)
.where(
(shift.employee == self.employee)
& (shift.docstatus < 2)
& (shift.name != self.name)
& ((shift.to_date >= self.from_date) | (shift.to_date.isnull()))
)
)
if self.to_date:
query = query.where(shift.from_date <= self.to_date)
return query.run(as_dict=True)
def throw_overlap_error(self, shift_details):
shift_details = frappe._dict(shift_details)
msg = _(
"Employee {0} has already applied for Shift {1}: {2} that overlaps within this period"
).format(
frappe.bold(self.employee),
frappe.bold(shift_details.shift_type),
get_link_to_form("Shift Request", shift_details.name),
)
frappe.throw(msg, title=_("Overlapping Shift Requests"), exc=OverlappingShiftRequestError)
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_request/shift_request.py
|
Python
|
agpl-3.0
| 4,085
|
def get_data():
return {
"fieldname": "shift_request",
"transactions": [
{"items": ["Shift Assignment"]},
],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_request/shift_request_dashboard.py
|
Python
|
agpl-3.0
| 122
|
frappe.listview_settings["Shift Request"] = {
onload: function (list_view) {
list_view.page.add_inner_button(__("Shift Assignment Tool"), function () {
const doc = frappe.model.get_new_doc("Shift Assignment Tool");
doc.action = "Process Shift Requests";
frappe.set_route("Form", "Shift Assignment Tool", doc.name);
});
},
};
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_request/shift_request_list.js
|
JavaScript
|
agpl-3.0
| 340
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Shift Type", {
refresh: function (frm) {
if (frm.doc.__islocal) return;
frm.add_custom_button(
__("Bulk Assign Shift"),
() => {
const doc = frappe.model.get_new_doc("Shift Assignment Tool");
doc.action = "Assign Shift";
doc.company = frappe.defaults.get_default("company");
doc.shift_type = frm.doc.name;
doc.status = "Active";
frappe.set_route("Form", "Shift Assignment Tool", doc.name);
},
__("Actions"),
);
frm.add_custom_button(
__("Mark Attendance"),
() => {
if (!frm.doc.enable_auto_attendance) {
frm.scroll_to_field("enable_auto_attendance");
frappe.throw(
__("Please Enable Auto Attendance and complete the setup first."),
);
}
if (!frm.doc.process_attendance_after) {
frm.scroll_to_field("process_attendance_after");
frappe.throw(__("Please set {0}.", [__("Process Attendance After").bold()]));
}
if (!frm.doc.last_sync_of_checkin) {
frm.scroll_to_field("last_sync_of_checkin");
frappe.throw(__("Please set {0}.", [__("Last Sync of Checkin").bold()]));
}
frm.call({
doc: frm.doc,
method: "process_auto_attendance",
freeze: true,
callback: () => {
frappe.msgprint(
__("Attendance has been marked as per employee check-ins"),
);
},
});
},
__("Actions"),
);
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_type/shift_type.js
|
JavaScript
|
agpl-3.0
| 1,494
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from datetime import datetime, timedelta
from itertools import groupby
import frappe
from frappe.model.document import Document
from frappe.utils import cint, create_batch, get_datetime, get_time, getdate
from erpnext.setup.doctype.employee.employee import get_holiday_list_for_employee
from erpnext.setup.doctype.holiday_list.holiday_list import is_holiday
from hrms.hr.doctype.attendance.attendance import mark_attendance
from hrms.hr.doctype.employee_checkin.employee_checkin import (
calculate_working_hours,
mark_attendance_and_link_log,
)
from hrms.hr.doctype.shift_assignment.shift_assignment import get_employee_shift, get_shift_details
from hrms.utils import get_date_range
from hrms.utils.holiday_list import get_holiday_dates_between
EMPLOYEE_CHUNK_SIZE = 50
class ShiftType(Document):
@frappe.whitelist()
def process_auto_attendance(self):
if (
not cint(self.enable_auto_attendance)
or not self.process_attendance_after
or not self.last_sync_of_checkin
):
return
logs = self.get_employee_checkins()
group_key = lambda x: (x["employee"], x["shift_start"]) # noqa
for key, group in groupby(sorted(logs, key=group_key), key=group_key):
single_shift_logs = list(group)
attendance_date = key[1].date()
employee = key[0]
if not self.should_mark_attendance(employee, attendance_date):
continue
(
attendance_status,
working_hours,
late_entry,
early_exit,
in_time,
out_time,
) = self.get_attendance(single_shift_logs)
mark_attendance_and_link_log(
single_shift_logs,
attendance_status,
attendance_date,
working_hours,
late_entry,
early_exit,
in_time,
out_time,
self.name,
)
# commit after processing checkin logs to avoid losing progress
frappe.db.commit() # nosemgrep
assigned_employees = self.get_assigned_employees(self.process_attendance_after, True)
# mark absent in batches & commit to avoid losing progress since this tries to process remaining attendance
# right from "Process Attendance After" to "Last Sync of Checkin"
for batch in create_batch(assigned_employees, EMPLOYEE_CHUNK_SIZE):
for employee in batch:
self.mark_absent_for_dates_with_no_attendance(employee)
frappe.db.commit() # nosemgrep
def get_employee_checkins(self) -> list[dict]:
return frappe.get_all(
"Employee Checkin",
fields=[
"name",
"employee",
"log_type",
"time",
"shift",
"shift_start",
"shift_end",
"shift_actual_start",
"shift_actual_end",
"device_id",
],
filters={
"skip_auto_attendance": 0,
"attendance": ("is", "not set"),
"time": (">=", self.process_attendance_after),
"shift_actual_end": ("<", self.last_sync_of_checkin),
"shift": self.name,
},
order_by="employee,time",
)
def get_attendance(self, logs):
"""Return attendance_status, working_hours, late_entry, early_exit, in_time, out_time
for a set of logs belonging to a single shift.
Assumptions:
1. These logs belongs to a single shift, single employee and it's not in a holiday date.
2. Logs are in chronological order
"""
late_entry = early_exit = False
total_working_hours, in_time, out_time = calculate_working_hours(
logs, self.determine_check_in_and_check_out, self.working_hours_calculation_based_on
)
if (
cint(self.enable_late_entry_marking)
and in_time
and in_time > logs[0].shift_start + timedelta(minutes=cint(self.late_entry_grace_period))
):
late_entry = True
if (
cint(self.enable_early_exit_marking)
and out_time
and out_time < logs[0].shift_end - timedelta(minutes=cint(self.early_exit_grace_period))
):
early_exit = True
if (
self.working_hours_threshold_for_absent
and total_working_hours < self.working_hours_threshold_for_absent
):
return "Absent", total_working_hours, late_entry, early_exit, in_time, out_time
if (
self.working_hours_threshold_for_half_day
and total_working_hours < self.working_hours_threshold_for_half_day
):
return "Half Day", total_working_hours, late_entry, early_exit, in_time, out_time
return "Present", total_working_hours, late_entry, early_exit, in_time, out_time
def mark_absent_for_dates_with_no_attendance(self, employee: str):
"""Marks Absents for the given employee on working days in this shift that have no attendance marked.
The Absent status is marked starting from 'process_attendance_after' or employee creation date.
"""
start_time = get_time(self.start_time)
dates = self.get_dates_for_attendance(employee)
for date in dates:
timestamp = datetime.combine(date, start_time)
shift_details = get_employee_shift(employee, timestamp, True)
if shift_details and shift_details.shift_type.name == self.name:
attendance = mark_attendance(employee, date, "Absent", self.name)
if not attendance:
continue
frappe.get_doc(
{
"doctype": "Comment",
"comment_type": "Comment",
"reference_doctype": "Attendance",
"reference_name": attendance,
"content": frappe._("Employee was marked Absent due to missing Employee Checkins."),
}
).insert(ignore_permissions=True)
def get_dates_for_attendance(self, employee: str) -> list[str]:
start_date, end_date = self.get_start_and_end_dates(employee)
# no shift assignment found, no need to process absent attendance records
if start_date is None:
return []
date_range = get_date_range(start_date, end_date)
# skip marking absent on holidays
holiday_list = self.get_holiday_list(employee)
holiday_dates = get_holiday_dates_between(holiday_list, start_date, end_date)
# skip dates with attendance
marked_attendance_dates = self.get_marked_attendance_dates_between(employee, start_date, end_date)
return sorted(set(date_range) - set(holiday_dates) - set(marked_attendance_dates))
def get_start_and_end_dates(self, employee):
"""Returns start and end dates for checking attendance and marking absent
return: start date = max of `process_attendance_after` and DOJ
return: end date = min of shift before `last_sync_of_checkin` and Relieving Date
"""
date_of_joining, relieving_date, employee_creation = frappe.get_cached_value(
"Employee", employee, ["date_of_joining", "relieving_date", "creation"]
)
if not date_of_joining:
date_of_joining = employee_creation.date()
start_date = max(getdate(self.process_attendance_after), date_of_joining)
end_date = None
shift_details = get_shift_details(self.name, get_datetime(self.last_sync_of_checkin))
last_shift_time = (
shift_details.actual_end if shift_details else get_datetime(self.last_sync_of_checkin)
)
# check if shift is found for 1 day before the last sync of checkin
# absentees are auto-marked 1 day after the shift to wait for any manual attendance records
prev_shift = get_employee_shift(employee, last_shift_time - timedelta(days=1), True, "reverse")
if prev_shift and prev_shift.shift_type.name == self.name:
end_date = (
min(prev_shift.start_datetime.date(), relieving_date)
if relieving_date
else prev_shift.start_datetime.date()
)
else:
# no shift found
return None, None
return start_date, end_date
def get_marked_attendance_dates_between(self, employee: str, start_date: str, end_date: str) -> list[str]:
Attendance = frappe.qb.DocType("Attendance")
return (
frappe.qb.from_(Attendance)
.select(Attendance.attendance_date)
.where(
(Attendance.employee == employee)
& (Attendance.docstatus < 2)
& (Attendance.attendance_date.between(start_date, end_date))
& ((Attendance.shift.isnull()) | (Attendance.shift == self.name))
)
).run(pluck=True)
def get_assigned_employees(self, from_date=None, consider_default_shift=False) -> list[str]:
filters = {"shift_type": self.name, "docstatus": "1", "status": "Active"}
if from_date:
filters["start_date"] = (">=", from_date)
assigned_employees = frappe.get_all("Shift Assignment", filters=filters, pluck="employee")
if consider_default_shift:
default_shift_employees = self.get_employees_with_default_shift(filters)
assigned_employees = set(assigned_employees + default_shift_employees)
# exclude inactive employees
inactive_employees = frappe.db.get_all("Employee", {"status": "Inactive"}, pluck="name")
return list(set(assigned_employees) - set(inactive_employees))
def get_employees_with_default_shift(self, filters: dict) -> list:
default_shift_employees = frappe.get_all(
"Employee", filters={"default_shift": self.name, "status": "Active"}, pluck="name"
)
if not default_shift_employees:
return []
# exclude employees from default shift list if any other valid shift assignment exists
del filters["shift_type"]
filters["employee"] = ("in", default_shift_employees)
active_shift_assignments = frappe.get_all(
"Shift Assignment",
filters=filters,
pluck="employee",
)
return list(set(default_shift_employees) - set(active_shift_assignments))
def get_holiday_list(self, employee: str) -> str:
holiday_list_name = self.holiday_list or get_holiday_list_for_employee(employee, False)
return holiday_list_name
def should_mark_attendance(self, employee: str, attendance_date: str) -> bool:
"""Determines whether attendance should be marked on holidays or not"""
if self.mark_auto_attendance_on_holidays:
# no need to check if date is a holiday or not
# since attendance should be marked on all days
return True
holiday_list = self.get_holiday_list(employee)
if is_holiday(holiday_list, attendance_date):
return False
return True
def process_auto_attendance_for_all_shifts():
shift_list = frappe.get_all("Shift Type", filters={"enable_auto_attendance": "1"}, pluck="name")
for shift in shift_list:
doc = frappe.get_cached_doc("Shift Type", shift)
doc.process_auto_attendance()
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_type/shift_type.py
|
Python
|
agpl-3.0
| 9,986
|
def get_data():
return {
"fieldname": "shift",
"non_standard_fieldnames": {"Shift Request": "shift_type", "Shift Assignment": "shift_type"},
"transactions": [{"items": ["Attendance", "Employee Checkin", "Shift Request", "Shift Assignment"]}],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_type/shift_type_dashboard.py
|
Python
|
agpl-3.0
| 253
|
frappe.listview_settings["Shift Type"] = {
onload: function (list_view) {
list_view.page.add_inner_button(__("Shift Assignment Tool"), function () {
frappe.set_route("Form", "Shift Assignment Tool");
});
},
};
|
2302_79757062/hrms
|
hrms/hr/doctype/shift_type/shift_type_list.js
|
JavaScript
|
agpl-3.0
| 219
|
// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Skill", {
// refresh: function(frm) {
// }
});
|
2302_79757062/hrms
|
hrms/hr/doctype/skill/skill.js
|
JavaScript
|
agpl-3.0
| 190
|
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class Skill(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/skill/skill.py
|
Python
|
agpl-3.0
| 211
|
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class SkillAssessment(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/skill_assessment/skill_assessment.py
|
Python
|
agpl-3.0
| 221
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Staffing Plan", {
setup: function (frm) {
frm.set_query("designation", "staffing_details", function () {
let designations = [];
(frm.doc.staffing_details || []).forEach(function (staff_detail) {
if (staff_detail.designation) {
designations.push(staff_detail.designation);
}
});
// Filter out designations already selected in Staffing Plan Detail
return {
filters: [["Designation", "name", "not in", designations]],
};
});
frm.set_query("department", function () {
return {
filters: {
company: frm.doc.company,
},
};
});
},
get_job_requisitions: function (frm) {
new frappe.ui.form.MultiSelectDialog({
doctype: "Job Requisition",
target: frm,
date_field: "posting_date",
add_filters_group: 1,
setters: {
designation: null,
requested_by: null,
},
get_query() {
let filters = {
company: frm.doc.company,
status: ["in", ["Pending", "Open & Approved"]],
};
if (frm.doc.department) filters.department = frm.doc.department;
return {
filters: filters,
};
},
action(selections) {
const plan_name = frm.doc.__newname;
frappe
.call({
method: "set_job_requisitions",
doc: frm.doc,
args: selections,
})
.then(() => {
// hack to retain prompt name that gets lost on frappe.call
frm.doc.__newname = plan_name;
refresh_field("staffing_details");
});
cur_dialog.hide();
},
});
},
});
frappe.ui.form.on("Staffing Plan Detail", {
designation: function (frm, cdt, cdn) {
let child = locals[cdt][cdn];
if (frm.doc.company && child.designation) {
set_number_of_positions(frm, cdt, cdn);
}
},
vacancies: function (frm, cdt, cdn) {
let child = locals[cdt][cdn];
if (child.vacancies < child.current_openings) {
frappe.throw(__("Vacancies cannot be lower than the current openings"));
}
set_number_of_positions(frm, cdt, cdn);
},
current_count: function (frm, cdt, cdn) {
set_number_of_positions(frm, cdt, cdn);
},
estimated_cost_per_position: function (frm, cdt, cdn) {
set_total_estimated_cost(frm, cdt, cdn);
},
});
var set_number_of_positions = function (frm, cdt, cdn) {
let child = locals[cdt][cdn];
if (!child.designation) frappe.throw(__("Please enter the designation"));
frappe.call({
method: "hrms.hr.doctype.staffing_plan.staffing_plan.get_designation_counts",
args: {
designation: child.designation,
company: frm.doc.company,
},
callback: function (data) {
if (data.message) {
frappe.model.set_value(cdt, cdn, "current_count", data.message.employee_count);
frappe.model.set_value(cdt, cdn, "current_openings", data.message.job_openings);
let total_positions = cint(data.message.employee_count) + cint(child.vacancies);
if (cint(child.number_of_positions) < total_positions) {
frappe.model.set_value(cdt, cdn, "number_of_positions", total_positions);
}
} else {
// No employees for this designation
frappe.model.set_value(cdt, cdn, "current_count", 0);
frappe.model.set_value(cdt, cdn, "current_openings", 0);
}
},
});
refresh_field("staffing_details");
set_total_estimated_cost(frm, cdt, cdn);
};
// Note: Estimated Cost is calculated on number of Vacancies
var set_total_estimated_cost = function (frm, cdt, cdn) {
let child = locals[cdt][cdn];
if (child.vacancies > 0 && child.estimated_cost_per_position) {
frappe.model.set_value(
cdt,
cdn,
"total_estimated_cost",
child.vacancies * child.estimated_cost_per_position,
);
} else {
frappe.model.set_value(cdt, cdn, "total_estimated_cost", 0);
}
set_total_estimated_budget(frm);
};
var set_total_estimated_budget = function (frm) {
let estimated_budget = 0.0;
if (frm.doc.staffing_details) {
(frm.doc.staffing_details || []).forEach(function (staff_detail) {
if (staff_detail.total_estimated_cost) {
estimated_budget += staff_detail.total_estimated_cost;
}
});
frm.set_value("total_estimated_budget", estimated_budget);
}
};
|
2302_79757062/hrms
|
hrms/hr/doctype/staffing_plan/staffing_plan.js
|
JavaScript
|
agpl-3.0
| 4,167
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import cint, flt, getdate, nowdate
from frappe.utils.nestedset import get_descendants_of
class SubsidiaryCompanyError(frappe.ValidationError):
pass
class ParentCompanyError(frappe.ValidationError):
pass
class StaffingPlan(Document):
def validate(self):
self.validate_period()
self.validate_details()
self.set_total_estimated_budget()
def validate_period(self):
# Validate Dates
if self.from_date and self.to_date and self.from_date > self.to_date:
frappe.throw(_("From Date cannot be greater than To Date"))
def validate_details(self):
for detail in self.get("staffing_details"):
self.validate_overlap(detail)
self.validate_with_subsidiary_plans(detail)
self.validate_with_parent_plan(detail)
def set_total_estimated_budget(self):
self.total_estimated_budget = 0
for detail in self.get("staffing_details"):
# Set readonly fields
self.set_number_of_positions(detail)
designation_counts = get_designation_counts(detail.designation, self.company)
detail.current_count = designation_counts["employee_count"]
detail.current_openings = designation_counts["job_openings"]
detail.total_estimated_cost = 0
if detail.number_of_positions > 0:
if detail.vacancies and detail.estimated_cost_per_position:
detail.total_estimated_cost = cint(detail.vacancies) * flt(
detail.estimated_cost_per_position
)
self.total_estimated_budget += detail.total_estimated_cost
def set_number_of_positions(self, detail):
detail.number_of_positions = cint(detail.vacancies) + cint(detail.current_count)
def validate_overlap(self, staffing_plan_detail):
# Validate if any submitted Staffing Plan exist for any Designations in this plan
# and spd.vacancies>0 ?
overlap = frappe.db.sql(
"""select spd.parent
from `tabStaffing Plan Detail` spd join `tabStaffing Plan` sp on spd.parent=sp.name
where spd.designation=%s and sp.docstatus=1
and sp.to_date >= %s and sp.from_date <= %s and sp.company = %s
""",
(staffing_plan_detail.designation, self.from_date, self.to_date, self.company),
)
if overlap and overlap[0][0]:
frappe.throw(
_("Staffing Plan {0} already exist for designation {1}").format(
overlap[0][0], staffing_plan_detail.designation
)
)
def validate_with_parent_plan(self, staffing_plan_detail):
if not frappe.get_cached_value("Company", self.company, "parent_company"):
return # No parent, nothing to validate
# Get staffing plan applicable for the company (Parent Company)
parent_plan_details = get_active_staffing_plan_details(
self.company, staffing_plan_detail.designation, self.from_date, self.to_date
)
if not parent_plan_details:
return # no staffing plan for any parent Company in hierarchy
# Fetch parent company which owns the staffing plan. NOTE: Parent could be higher up in the hierarchy
parent_company = frappe.db.get_value("Staffing Plan", parent_plan_details[0].name, "company")
# Parent plan available, validate with parent, siblings as well as children of staffing plan Company
if cint(staffing_plan_detail.vacancies) > cint(parent_plan_details[0].vacancies) or flt(
staffing_plan_detail.total_estimated_cost
) > flt(parent_plan_details[0].total_estimated_cost):
frappe.throw(
_(
"You can only plan for upto {0} vacancies and budget {1} for {2} as per staffing plan {3} for parent company {4}."
).format(
cint(parent_plan_details[0].vacancies),
parent_plan_details[0].total_estimated_cost,
frappe.bold(staffing_plan_detail.designation),
parent_plan_details[0].name,
parent_company,
),
ParentCompanyError,
)
# Get vacanices already planned for all companies down the hierarchy of Parent Company
lft, rgt = frappe.get_cached_value("Company", parent_company, ["lft", "rgt"])
all_sibling_details = frappe.db.sql(
"""select sum(spd.vacancies) as vacancies,
sum(spd.total_estimated_cost) as total_estimated_cost
from `tabStaffing Plan Detail` spd join `tabStaffing Plan` sp on spd.parent=sp.name
where spd.designation=%s and sp.docstatus=1
and sp.to_date >= %s and sp.from_date <=%s
and sp.company in (select name from tabCompany where lft > %s and rgt < %s)
""",
(staffing_plan_detail.designation, self.from_date, self.to_date, lft, rgt),
as_dict=1,
)[0]
if (
cint(parent_plan_details[0].vacancies)
< (cint(staffing_plan_detail.vacancies) + cint(all_sibling_details.vacancies))
) or (
flt(parent_plan_details[0].total_estimated_cost)
< (flt(staffing_plan_detail.total_estimated_cost) + flt(all_sibling_details.total_estimated_cost))
):
frappe.throw(
_(
"{0} vacancies and {1} budget for {2} already planned for subsidiary companies of {3}. You can only plan for upto {4} vacancies and and budget {5} as per staffing plan {6} for parent company {3}."
).format(
cint(all_sibling_details.vacancies),
all_sibling_details.total_estimated_cost,
frappe.bold(staffing_plan_detail.designation),
parent_company,
cint(parent_plan_details[0].vacancies),
parent_plan_details[0].total_estimated_cost,
parent_plan_details[0].name,
)
)
def validate_with_subsidiary_plans(self, staffing_plan_detail):
# Valdate this plan with all child company plan
children_details = frappe.db.sql(
"""select sum(spd.vacancies) as vacancies,
sum(spd.total_estimated_cost) as total_estimated_cost
from `tabStaffing Plan Detail` spd join `tabStaffing Plan` sp on spd.parent=sp.name
where spd.designation=%s and sp.docstatus=1
and sp.to_date >= %s and sp.from_date <=%s
and sp.company in (select name from tabCompany where parent_company = %s)
""",
(staffing_plan_detail.designation, self.from_date, self.to_date, self.company),
as_dict=1,
)[0]
if (
children_details
and cint(staffing_plan_detail.vacancies) < cint(children_details.vacancies)
or flt(staffing_plan_detail.total_estimated_cost) < flt(children_details.total_estimated_cost)
):
frappe.throw(
_(
"Subsidiary companies have already planned for {1} vacancies at a budget of {2}. Staffing Plan for {0} should allocate more vacancies and budget for {3} than planned for its subsidiary companies"
).format(
self.company,
cint(children_details.vacancies),
children_details.total_estimated_cost,
frappe.bold(staffing_plan_detail.designation),
),
SubsidiaryCompanyError,
)
@frappe.whitelist()
def set_job_requisitions(self, job_reqs):
if job_reqs:
requisitions = frappe.db.get_list(
"Job Requisition",
filters={"name": ["in", job_reqs]},
fields=["designation", "no_of_positions", "expected_compensation"],
)
self.staffing_details = []
for req in requisitions:
self.append(
"staffing_details",
{
"designation": req.designation,
"vacancies": req.no_of_positions,
"estimated_cost_per_position": req.expected_compensation,
},
)
return self
@frappe.whitelist()
def get_designation_counts(designation, company, job_opening=None):
if not designation:
return False
company_set = get_descendants_of("Company", company)
company_set.append(company)
employee_count = frappe.db.count(
"Employee", {"designation": designation, "status": "Active", "company": ("in", company_set)}
)
filters = {"designation": designation, "status": "Open", "company": ("in", company_set)}
if job_opening:
filters["name"] = ("!=", job_opening)
job_openings = frappe.db.count("Job Opening", filters)
return {"employee_count": employee_count, "job_openings": job_openings}
@frappe.whitelist()
def get_active_staffing_plan_details(company, designation, from_date=None, to_date=None):
if from_date is None:
from_date = getdate(nowdate())
if to_date is None:
to_date = getdate(nowdate())
if not company or not designation:
frappe.throw(_("Please select Company and Designation"))
staffing_plan = frappe.db.sql(
"""
select sp.name, spd.vacancies, spd.total_estimated_cost
from `tabStaffing Plan Detail` spd join `tabStaffing Plan` sp on spd.parent=sp.name
where company=%s and spd.designation=%s and sp.docstatus=1
and to_date >= %s and from_date <= %s """,
(company, designation, from_date, to_date),
as_dict=1,
)
if not staffing_plan:
parent_company = frappe.get_cached_value("Company", company, "parent_company")
if parent_company:
staffing_plan = get_active_staffing_plan_details(parent_company, designation, from_date, to_date)
# Only a single staffing plan can be active for a designation on given date
return staffing_plan if staffing_plan else None
|
2302_79757062/hrms
|
hrms/hr/doctype/staffing_plan/staffing_plan.py
|
Python
|
agpl-3.0
| 8,818
|
def get_data():
return {
"fieldname": "staffing_plan",
"transactions": [{"items": ["Job Opening"]}],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/staffing_plan/staffing_plan_dashboard.py
|
Python
|
agpl-3.0
| 109
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class StaffingPlanDetail(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/staffing_plan_detail/staffing_plan_detail.py
|
Python
|
agpl-3.0
| 208
|
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Training Event", {
onload_post_render: function (frm) {
frm.get_field("employees").grid.set_multiple_add("employee");
},
refresh: function (frm) {
if (!frm.doc.__islocal) {
frm.add_custom_button(__("Training Result"), function () {
frappe.route_options = {
training_event: frm.doc.name,
};
frappe.set_route("List", "Training Result");
});
frm.add_custom_button(__("Training Feedback"), function () {
frappe.route_options = {
training_event: frm.doc.name,
};
frappe.set_route("List", "Training Feedback");
});
}
frm.events.set_employee_query(frm);
},
set_employee_query: function (frm) {
let emp = [];
for (let d in frm.doc.employees) {
if (frm.doc.employees[d].employee) {
emp.push(frm.doc.employees[d].employee);
}
}
frm.set_query("employee", "employees", function () {
return {
filters: {
name: ["NOT IN", emp],
status: "Active",
},
};
});
},
});
frappe.ui.form.on("Training Event Employee", {
employee: function (frm) {
frm.events.set_employee_query(frm);
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/training_event/training_event.js
|
JavaScript
|
agpl-3.0
| 1,217
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import time_diff_in_seconds
from erpnext.setup.doctype.employee.employee import get_employee_emails
class TrainingEvent(Document):
def validate(self):
self.set_employee_emails()
self.validate_period()
def on_update_after_submit(self):
self.set_status_for_attendees()
def set_employee_emails(self):
self.employee_emails = ", ".join(get_employee_emails([d.employee for d in self.employees]))
def validate_period(self):
if time_diff_in_seconds(self.end_time, self.start_time) <= 0:
frappe.throw(_("End time cannot be before start time"))
def set_status_for_attendees(self):
if self.event_status == "Completed":
for employee in self.employees:
if employee.attendance == "Present" and employee.status != "Feedback Submitted":
employee.status = "Completed"
elif self.event_status == "Scheduled":
for employee in self.employees:
employee.status = "Open"
self.db_update_all()
|
2302_79757062/hrms
|
hrms/hr/doctype/training_event/training_event.py
|
Python
|
agpl-3.0
| 1,137
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.views.calendar["Training Event"] = {
field_map: {
start: "start_time",
end: "end_time",
id: "name",
title: "event_name",
allDay: "allDay",
},
gantt: true,
get_events_method: "frappe.desk.calendar.get_events",
};
|
2302_79757062/hrms
|
hrms/hr/doctype/training_event/training_event_calendar.js
|
JavaScript
|
agpl-3.0
| 363
|
def get_data():
return {
"fieldname": "training_event",
"transactions": [
{"items": ["Training Result", "Training Feedback"]},
],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/training_event/training_event_dashboard.py
|
Python
|
agpl-3.0
| 143
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class TrainingEventEmployee(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/training_event_employee/training_event_employee.py
|
Python
|
agpl-3.0
| 211
|
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Training Feedback", {
onload: function (frm) {
frm.add_fetch("training_event", "course", "course");
frm.add_fetch("training_event", "event_name", "event_name");
frm.add_fetch("training_event", "trainer_name", "trainer_name");
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/training_feedback/training_feedback.js
|
JavaScript
|
agpl-3.0
| 382
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_("{0} must be submitted").format(_("Training Event")))
emp_event_details = frappe.db.get_value(
"Training Event Employee",
{"parent": self.training_event, "employee": self.employee},
["name", "attendance"],
as_dict=True,
)
if not emp_event_details:
frappe.throw(
_("Employee {0} not found in Training Event Participants.").format(
frappe.bold(self.employee_name)
)
)
if emp_event_details.attendance == "Absent":
frappe.throw(_("Feedback cannot be recorded for an absent Employee."))
def on_submit(self):
employee = frappe.db.get_value(
"Training Event Employee", {"parent": self.training_event, "employee": self.employee}
)
if employee:
frappe.db.set_value("Training Event Employee", employee, "status", "Feedback Submitted")
def on_cancel(self):
employee = frappe.db.get_value(
"Training Event Employee", {"parent": self.training_event, "employee": self.employee}
)
if employee:
frappe.db.set_value("Training Event Employee", employee, "status", "Completed")
|
2302_79757062/hrms
|
hrms/hr/doctype/training_feedback/training_feedback.py
|
Python
|
agpl-3.0
| 1,417
|
// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Training Program", {});
|
2302_79757062/hrms
|
hrms/hr/doctype/training_program/training_program.js
|
JavaScript
|
agpl-3.0
| 165
|
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class TrainingProgram(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/training_program/training_program.py
|
Python
|
agpl-3.0
| 205
|
from frappe import _
def get_data():
return {
"fieldname": "training_program",
"transactions": [
{"label": _("Training Events"), "items": ["Training Event"]},
],
}
|
2302_79757062/hrms
|
hrms/hr/doctype/training_program/training_program_dashboard.py
|
Python
|
agpl-3.0
| 177
|
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Training Result", {
onload: function (frm) {
frm.trigger("training_event");
},
training_event: function (frm) {
frm.trigger("training_event");
},
training_event: function (frm) {
if (frm.doc.training_event && !frm.doc.docstatus && !frm.doc.employees) {
frappe.call({
method: "hrms.hr.doctype.training_result.training_result.get_employees",
args: {
training_event: frm.doc.training_event,
},
callback: function (r) {
frm.set_value("employees", "");
if (r.message) {
$.each(r.message, function (i, d) {
var row = frappe.model.add_child(
frm.doc,
"Training Result Employee",
"employees",
);
row.employee = d.employee;
row.employee_name = d.employee_name;
});
}
refresh_field("employees");
},
});
}
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/training_result/training_result.js
|
JavaScript
|
agpl-3.0
| 974
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from erpnext.setup.doctype.employee.employee import get_employee_emails
class TrainingResult(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_("{0} must be submitted").format(_("Training Event")))
self.employee_emails = ", ".join(get_employee_emails([d.employee for d in self.employees]))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
training_event.status = "Completed"
for e in self.employees:
for e1 in training_event.employees:
if e1.employee == e.employee:
e1.status = "Completed"
break
training_event.save()
@frappe.whitelist()
def get_employees(training_event):
return frappe.get_doc("Training Event", training_event).employees
|
2302_79757062/hrms
|
hrms/hr/doctype/training_result/training_result.py
|
Python
|
agpl-3.0
| 1,026
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class TrainingResultEmployee(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/training_result_employee/training_result_employee.py
|
Python
|
agpl-3.0
| 212
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class TravelItinerary(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/travel_itinerary/travel_itinerary.py
|
Python
|
agpl-3.0
| 205
|
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Travel Request", {
refresh: function (frm) {},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/travel_request/travel_request.js
|
JavaScript
|
agpl-3.0
| 193
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
from hrms.hr.utils import validate_active_employee
class TravelRequest(Document):
def validate(self):
validate_active_employee(self.employee)
|
2302_79757062/hrms
|
hrms/hr/doctype/travel_request/travel_request.py
|
Python
|
agpl-3.0
| 312
|
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class TravelRequestCosting(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/travel_request_costing/travel_request_costing.py
|
Python
|
agpl-3.0
| 210
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.provide("hrms.hr");
hrms.hr.AttendanceControlPanel = class AttendanceControlPanel extends frappe.ui.form.Controller {
onload() {
this.frm.set_value("att_fr_date", frappe.datetime.get_today());
this.frm.set_value("att_to_date", frappe.datetime.get_today());
}
refresh() {
this.frm.disable_save();
this.show_upload();
this.setup_import_progress();
}
get_template() {
if (!this.frm.doc.att_fr_date || !this.frm.doc.att_to_date) {
frappe.msgprint(__("Attendance From Date and Attendance To Date is mandatory"));
return;
}
window.location.href = repl(
frappe.request.url + "?cmd=%(cmd)s&from_date=%(from_date)s&to_date=%(to_date)s",
{
cmd: "hrms.hr.doctype.upload_attendance.upload_attendance.get_template",
from_date: this.frm.doc.att_fr_date,
to_date: this.frm.doc.att_to_date,
},
);
}
show_upload() {
let $wrapper = $(this.frm.fields_dict.upload_html.wrapper).empty();
new frappe.ui.FileUploader({
wrapper: $wrapper,
method: "hrms.hr.doctype.upload_attendance.upload_attendance.upload",
});
$wrapper.addClass("pb-5");
}
setup_import_progress() {
var $log_wrapper = $(this.frm.fields_dict.import_log.wrapper).empty();
frappe.realtime.on("import_attendance", (data) => {
if (data.progress) {
this.frm.dashboard.show_progress(
"Import Attendance",
(data.progress / data.total) * 100,
__("Importing {0} of {1}", [data.progress, data.total]),
);
if (data.progress === data.total) {
this.frm.dashboard.hide_progress("Import Attendance");
}
} else if (data.error) {
this.frm.dashboard.hide();
let messages = [`<th>${__("Error in some rows")}</th>`]
.concat(
data.messages
.filter((message) => message.includes("Error"))
.map((message) => `<tr><td>${message}</td></tr>`),
)
.join("");
$log_wrapper.append('<table class="table table-bordered">' + messages);
} else if (data.messages) {
this.frm.dashboard.hide();
let messages = [`<th>${__("Import Successful")}</th>`]
.concat(data.messages.map((message) => `<tr><td>${message}</td></tr>`))
.join("");
$log_wrapper.append('<table class="table table-bordered">' + messages);
}
});
}
};
// nosemgrep: frappe-semgrep-rules.rules.frappe-cur-frm-usage
cur_frm.cscript = new hrms.hr.AttendanceControlPanel({ frm: cur_frm });
|
2302_79757062/hrms
|
hrms/hr/doctype/upload_attendance/upload_attendance.js
|
JavaScript
|
agpl-3.0
| 2,493
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import add_days, cstr, date_diff, getdate
from frappe.utils.csvutils import UnicodeWriter
from erpnext.setup.doctype.employee.employee import get_holiday_list_for_employee
from hrms.hr.utils import get_holiday_dates_for_employee
class UploadAttendance(Document):
pass
@frappe.whitelist()
def get_template():
if not frappe.has_permission("Attendance", "create"):
raise frappe.PermissionError
args = frappe.local.form_dict
if getdate(args.from_date) > getdate(args.to_date):
frappe.throw(_("To Date should be greater than From Date"))
w = UnicodeWriter()
w = add_header(w)
try:
w = add_data(w, args)
except Exception as e:
frappe.clear_messages()
frappe.respond_as_web_page("Holiday List Missing", html=e)
return
# write out response as a type csv
frappe.response["result"] = cstr(w.getvalue())
frappe.response["type"] = "csv"
frappe.response["doctype"] = "Attendance"
def add_header(w):
status = ", ".join((frappe.get_meta("Attendance").get_field("status").options or "").strip().split("\n"))
w.writerow(["Notes:"])
w.writerow(["Please do not change the template headings"])
w.writerow(["Status should be one of these values: " + status])
w.writerow(["If you are overwriting existing attendance records, 'ID' column mandatory"])
w.writerow(
["ID", "Employee", "Employee Name", "Date", "Status", "Leave Type", "Company", "Naming Series"]
)
return w
def add_data(w, args):
data = get_data(args)
writedata(w, data)
return w
def get_data(args):
dates = get_dates(args)
employees = get_active_employees()
holidays = get_holidays_for_employees(
[employee.name for employee in employees], args["from_date"], args["to_date"]
)
existing_attendance_records = get_existing_attendance_records(args)
data = []
for date in dates:
for employee in employees:
if getdate(date) < getdate(employee.date_of_joining):
continue
if employee.relieving_date:
if getdate(date) > getdate(employee.relieving_date):
continue
existing_attendance = {}
if (
existing_attendance_records
and tuple([getdate(date), employee.name]) in existing_attendance_records
and getdate(employee.date_of_joining) <= getdate(date)
and getdate(employee.relieving_date) >= getdate(date)
):
existing_attendance = existing_attendance_records[tuple([getdate(date), employee.name])]
employee_holiday_list = get_holiday_list_for_employee(employee.name)
row = [
existing_attendance and existing_attendance.name or "",
employee.name,
employee.employee_name,
date,
existing_attendance and existing_attendance.status or "",
existing_attendance and existing_attendance.leave_type or "",
employee.company,
existing_attendance and existing_attendance.naming_series or get_naming_series(),
]
if date in holidays[employee_holiday_list]:
row[4] = "Holiday"
data.append(row)
return data
def get_holidays_for_employees(employees, from_date, to_date):
holidays = {}
for employee in employees:
holiday_list = get_holiday_list_for_employee(employee)
holiday = get_holiday_dates_for_employee(employee, getdate(from_date), getdate(to_date))
if holiday_list not in holidays:
holidays[holiday_list] = holiday
return holidays
def writedata(w, data):
for row in data:
w.writerow(row)
def get_dates(args):
"""get list of dates in between from date and to date"""
no_of_days = date_diff(add_days(args["to_date"], 1), args["from_date"])
dates = [add_days(args["from_date"], i) for i in range(0, no_of_days)]
return dates
def get_active_employees():
employees = frappe.db.get_all(
"Employee",
fields=["name", "employee_name", "date_of_joining", "company", "relieving_date"],
filters={"docstatus": ["<", 2], "status": "Active"},
)
return employees
def get_existing_attendance_records(args):
attendance = frappe.db.sql(
"""select name, attendance_date, employee, status, leave_type, naming_series
from `tabAttendance` where attendance_date between %s and %s and docstatus < 2""",
(args["from_date"], args["to_date"]),
as_dict=1,
)
existing_attendance = {}
for att in attendance:
existing_attendance[tuple([att.attendance_date, att.employee])] = att
return existing_attendance
def get_naming_series():
series = frappe.get_meta("Attendance").get_field("naming_series").options.strip().split("\n")
if not series:
frappe.throw(_("Please setup numbering series for Attendance via Setup > Numbering Series"))
return series[0]
@frappe.whitelist()
def upload():
if not frappe.has_permission("Attendance", "create"):
raise frappe.PermissionError
from frappe.utils.csvutils import read_csv_content
rows = read_csv_content(frappe.local.uploaded_file)
if not rows:
frappe.throw(_("Please select a csv file"))
frappe.enqueue(import_attendances, rows=rows, now=True if len(rows) < 200 else False)
def import_attendances(rows):
def remove_holidays(rows):
rows = [row for row in rows if row[4] != "Holiday"]
return rows
from frappe.modules import scrub
rows = list(filter(lambda x: x and any(x), rows))
columns = [scrub(f) for f in rows[4]]
columns[0] = "name"
columns[3] = "attendance_date"
rows = rows[5:]
ret = []
error = False
rows = remove_holidays(rows)
from frappe.utils.csvutils import check_record, import_doc
for i, row in enumerate(rows):
if not row:
continue
row_idx = i + 5
d = frappe._dict(zip(columns, row, strict=False))
d["doctype"] = "Attendance"
if d.name:
d["docstatus"] = frappe.db.get_value("Attendance", d.name, "docstatus")
try:
check_record(d)
ret.append(import_doc(d, "Attendance", 1, row_idx, submit=True))
frappe.publish_realtime("import_attendance", dict(progress=i, total=len(rows)))
except AttributeError:
pass
except Exception as e:
error = True
ret.append("Error for row (#%d) %s : %s" % (row_idx, len(row) > 1 and row[1] or "", cstr(e)))
frappe.errprint(frappe.get_traceback())
if error:
frappe.db.rollback()
else:
frappe.db.commit()
frappe.publish_realtime("import_attendance", dict(messages=ret, error=error))
|
2302_79757062/hrms
|
hrms/hr/doctype/upload_attendance/upload_attendance.py
|
Python
|
agpl-3.0
| 6,343
|
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Vehicle Log", {
setup: function (frm) {
frm.set_query("employee", function () {
return {
filters: {
status: "Active",
},
};
});
},
refresh: function (frm) {
if (frm.doc.docstatus == 1) {
frm.add_custom_button(
__("Expense Claim"),
function () {
frm.events.expense_claim(frm);
},
__("Create"),
);
frm.page.set_inner_btn_group_as_primary(__("Create"));
}
},
expense_claim: function (frm) {
frappe.call({
method: "hrms.hr.doctype.vehicle_log.vehicle_log.make_expense_claim",
args: {
docname: frm.doc.name,
},
callback: function (r) {
var doc = frappe.model.sync(r.message);
frappe.set_route("Form", "Expense Claim", r.message.name);
},
});
},
});
|
2302_79757062/hrms
|
hrms/hr/doctype/vehicle_log/vehicle_log.js
|
JavaScript
|
agpl-3.0
| 880
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import flt
class VehicleLog(Document):
def validate(self):
if flt(self.odometer) < flt(self.last_odometer):
frappe.throw(
_("Current Odometer Value should be greater than Last Odometer Value {0}").format(
self.last_odometer
)
)
def on_submit(self):
frappe.db.set_value("Vehicle", self.license_plate, "last_odometer", self.odometer)
def on_cancel(self):
distance_travelled = self.odometer - self.last_odometer
if distance_travelled > 0:
updated_odometer_value = (
int(frappe.db.get_value("Vehicle", self.license_plate, "last_odometer")) - distance_travelled
)
frappe.db.set_value("Vehicle", self.license_plate, "last_odometer", updated_odometer_value)
@frappe.whitelist()
def make_expense_claim(docname):
expense_claim = frappe.db.exists("Expense Claim", {"vehicle_log": docname})
if expense_claim:
frappe.throw(_("Expense Claim {0} already exists for the Vehicle Log").format(expense_claim))
vehicle_log = frappe.get_doc("Vehicle Log", docname)
service_expense = sum([flt(d.expense_amount) for d in vehicle_log.service_detail])
claim_amount = service_expense + (flt(vehicle_log.price) * flt(vehicle_log.fuel_qty) or 1)
if not claim_amount:
frappe.throw(_("No additional expenses has been added"))
exp_claim = frappe.new_doc("Expense Claim")
exp_claim.employee = vehicle_log.employee
exp_claim.vehicle_log = vehicle_log.name
exp_claim.remark = _("Expense Claim for Vehicle Log {0}").format(vehicle_log.name)
exp_claim.append(
"expenses",
{"expense_date": vehicle_log.date, "description": _("Vehicle Expenses"), "amount": claim_amount},
)
return exp_claim.as_dict()
|
2302_79757062/hrms
|
hrms/hr/doctype/vehicle_log/vehicle_log.py
|
Python
|
agpl-3.0
| 1,854
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class VehicleService(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/vehicle_service/vehicle_service.py
|
Python
|
agpl-3.0
| 204
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Vehicle Service Item", {
// refresh: function(frm) {
// }
});
|
2302_79757062/hrms
|
hrms/hr/doctype/vehicle_service_item/vehicle_service_item.js
|
JavaScript
|
agpl-3.0
| 205
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class VehicleServiceItem(Document):
pass
|
2302_79757062/hrms
|
hrms/hr/doctype/vehicle_service_item/vehicle_service_item.py
|
Python
|
agpl-3.0
| 223
|
frappe.ui.form.on(cur_frm.doctype, {
setup: function (frm) {
frm.set_query("employee", function () {
return {
filters: {
status: "Active",
},
};
});
},
onload: function (frm) {
if (frm.doc.__islocal && !frm.doc.amended_from) frm.trigger("clear_property_table");
},
employee: function (frm) {
frm.trigger("clear_property_table");
},
clear_property_table: function (frm) {
let table = frm.doctype == "Employee Promotion" ? "promotion_details" : "transfer_details";
frm.clear_table(table);
frm.refresh_field(table);
frm.fields_dict[table].grid.wrapper.find(".grid-add-row").hide();
},
refresh: function (frm) {
let table;
if (frm.doctype == "Employee Promotion") {
table = "promotion_details";
} else if (frm.doctype == "Employee Transfer") {
table = "transfer_details";
}
if (!table) return;
frm.fields_dict[table].grid.wrapper.find(".grid-add-row").hide();
frm.events.setup_employee_property_button(frm, table);
},
setup_employee_property_button: function (frm, table) {
frm.fields_dict[table].grid.add_custom_button(__("Add Employee Property"), () => {
if (!frm.doc.employee) {
frappe.msgprint(__("Please select Employee first."));
return;
}
const allowed_fields = [];
const exclude_fields = [
"naming_series",
"employee",
"first_name",
"middle_name",
"last_name",
"marital_status",
"ctc",
"employee_name",
"status",
"image",
"gender",
"date_of_birth",
"date_of_joining",
"lft",
"rgt",
"old_parent",
];
const exclude_field_types = [
"HTML",
"Section Break",
"Column Break",
"Button",
"Read Only",
"Tab Break",
"Table",
];
frappe.model.with_doctype("Employee", () => {
const field_label_map = {};
frappe.get_meta("Employee").fields.forEach((d) => {
field_label_map[d.fieldname] =
__(d.label, null, d.parent) + ` (${d.fieldname})`;
if (
!exclude_field_types.includes(d.fieldtype) &&
!exclude_fields.includes(d.fieldname) &&
!d.hidden &&
!d.read_only
) {
allowed_fields.push({
label: field_label_map[d.fieldname],
value: d.fieldname,
});
}
});
show_dialog(frm, table, allowed_fields);
});
});
},
});
var show_dialog = function (frm, table, field_labels) {
var d = new frappe.ui.Dialog({
title: "Update Property",
fields: [
{
fieldname: "property",
label: __("Select Property"),
fieldtype: "Autocomplete",
options: field_labels,
},
{ fieldname: "current", fieldtype: "Data", label: __("Current"), read_only: true },
{ fieldname: "new_value", fieldtype: "Data", label: __("New") },
],
primary_action_label: __("Add to Details"),
primary_action: () => {
d.get_primary_btn().attr("disabled", true);
if (d.data) {
d.data.new = d.get_values().new_value;
add_to_details(frm, d, table);
}
},
});
d.fields_dict["property"].df.onchange = () => {
let property = d.get_values().property;
d.data.fieldname = property;
if (!property) {
return;
}
frappe.call({
method: "hrms.hr.utils.get_employee_field_property",
args: { employee: frm.doc.employee, fieldname: property },
callback: function (r) {
if (r.message) {
d.data.current = r.message.value;
d.data.property = r.message.label;
d.set_value("current", r.message.value);
render_dynamic_field(d, r.message.datatype, r.message.options, property);
d.get_primary_btn().attr("disabled", false);
}
},
});
};
d.get_primary_btn().attr("disabled", true);
d.data = {};
d.show();
};
var render_dynamic_field = function (d, fieldtype, options, fieldname) {
d.data.new = null;
var dynamic_field = frappe.ui.form.make_control({
df: {
fieldtype: fieldtype,
fieldname: fieldname,
options: options || "",
label: __("New"),
},
parent: d.fields_dict.new_value.wrapper,
only_input: false,
});
dynamic_field.make_input();
d.replace_field("new_value", dynamic_field.df);
};
var add_to_details = function (frm, d, table) {
let data = d.data;
if (data.fieldname) {
if (validate_duplicate(frm, table, data.fieldname)) {
frappe.show_alert({ message: __("Property already added"), indicator: "orange" });
return false;
}
if (data.current == data.new) {
frappe.show_alert({ message: __("Nothing to change"), indicator: "orange" });
d.get_primary_btn().attr("disabled", false);
return false;
}
frm.add_child(table, {
fieldname: data.fieldname,
property: data.property,
current: data.current,
new: data.new,
});
frm.refresh_field(table);
frm.fields_dict[table].grid.wrapper.find(".grid-add-row").hide();
d.fields_dict.new_value.$wrapper.html("");
d.set_value("property", "");
d.set_value("current", "");
frappe.show_alert({ message: __("Added to details"), indicator: "green" });
d.data = {};
} else {
frappe.show_alert({ message: __("Value missing"), indicator: "red" });
}
};
var validate_duplicate = function (frm, table, fieldname) {
let duplicate = false;
$.each(frm.doc[table], function (i, detail) {
if (detail.fieldname === fieldname) {
duplicate = true;
return;
}
});
return duplicate;
};
|
2302_79757062/hrms
|
hrms/hr/employee_property_update.js
|
JavaScript
|
agpl-3.0
| 5,236
|
# import frappe
def get_context(context):
# do your magic here
pass
|
2302_79757062/hrms
|
hrms/hr/notification/exit_interview_scheduled/exit_interview_scheduled.py
|
Python
|
agpl-3.0
| 72
|
<p>{{ _("Hello") }},</p>
<p>You attended training {{ frappe.utils.get_link_to_form(
"Training Event", doc.training_event) }}</p>
<p>{{ _("Please share your feedback to the training by clicking on 'Training Feedback' and then 'New'") }}</p>
|
2302_79757062/hrms
|
hrms/hr/notification/training_feedback/training_feedback.html
|
HTML
|
agpl-3.0
| 243
|
def get_context(context):
# do your magic here
pass
|
2302_79757062/hrms
|
hrms/hr/notification/training_feedback/training_feedback.py
|
Python
|
agpl-3.0
| 54
|
<table class="panel-header" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr height="10"></tr>
<tr>
<td width="15"></td>
<td>
<div class="text-medium text-muted">
<span>{{_("Training Event:")}} {{ doc.event_name }}</span>
</div>
</td>
<td width="15"></td>
</tr>
<tr height="10"></tr>
</table>
<table class="panel-body" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr height="10"></tr>
<tr>
<td width="15"></td>
<td>
<div>
{{ doc.introduction }}
<ul class="list-unstyled" style="line-height: 1.7">
<li>{{_("Event Location")}}: <b>{{ doc.location }}</b></li>
{% set start = frappe.utils.get_datetime(doc.start_time) %}
{% set end = frappe.utils.get_datetime(doc.end_time) %}
{% if start.date() == end.date() %}
<li>{{_("Date")}}: <b>{{ start.strftime("%A, %d %b %Y") }}</b></li>
<li>
{{_("Timing")}}: <b>{{ start.strftime("%I:%M %p") + ' to ' + end.strftime("%I:%M %p") }}</b>
</li>
{% else %}
<li>{{_("Start Time")}}: <b>{{ start.strftime("%A, %d %b %Y at %I:%M %p") }}</b>
</li>
<li>{{_("End Time")}}: <b>{{ end.strftime("%A, %d %b %Y at %I:%M %p") }}</b>
</li>
{% endif %}
<li>{{ _('Event Link') }}: {{ frappe.utils.get_link_to_form(doc.doctype, doc.name) }}</li>
</ul>
</div>
</td>
<td width="15"></td>
</tr>
<tr height="10"></tr>
</table>
|
2302_79757062/hrms
|
hrms/hr/notification/training_scheduled/training_scheduled.html
|
HTML
|
agpl-3.0
| 1,780
|
def get_context(context):
# do your magic here
pass
|
2302_79757062/hrms
|
hrms/hr/notification/training_scheduled/training_scheduled.py
|
Python
|
agpl-3.0
| 54
|
frappe.pages["organizational-chart"].on_page_load = function (wrapper) {
frappe.ui.make_app_page({
parent: wrapper,
title: __("Organizational Chart"),
single_column: true,
});
$(wrapper).bind("show", () => {
frappe.require("hierarchy-chart.bundle.js", () => {
let organizational_chart;
let method = "hrms.hr.page.organizational_chart.organizational_chart.get_children";
if (frappe.is_mobile()) {
organizational_chart = new hrms.HierarchyChartMobile("Employee", wrapper, method);
} else {
organizational_chart = new hrms.HierarchyChart("Employee", wrapper, method);
}
frappe.breadcrumbs.add("HR");
organizational_chart.show();
});
});
};
|
2302_79757062/hrms
|
hrms/hr/page/organizational_chart/organizational_chart.js
|
JavaScript
|
agpl-3.0
| 683
|
import frappe
from frappe.query_builder.functions import Count
@frappe.whitelist()
def get_children(parent=None, company=None, exclude_node=None):
filters = [["status", "=", "Active"]]
if company and company != "All Companies":
filters.append(["company", "=", company])
if parent and company and parent != company:
filters.append(["reports_to", "=", parent])
else:
filters.append(["reports_to", "=", ""])
if exclude_node:
filters.append(["name", "!=", exclude_node])
employees = frappe.get_all(
"Employee",
fields=[
"employee_name as name",
"name as id",
"lft",
"rgt",
"reports_to",
"image",
"designation as title",
],
filters=filters,
order_by="name",
)
for employee in employees:
employee.connections = get_connections(employee.id, employee.lft, employee.rgt)
employee.expandable = bool(employee.connections)
return employees
def get_connections(employee: str, lft: int, rgt: int) -> int:
Employee = frappe.qb.DocType("Employee")
query = (
frappe.qb.from_(Employee)
.select(Count(Employee.name))
.where((Employee.lft > lft) & (Employee.rgt < rgt) & (Employee.status == "Active"))
).run()
return query[0][0]
|
2302_79757062/hrms
|
hrms/hr/page/organizational_chart/organizational_chart.py
|
Python
|
agpl-3.0
| 1,181
|
<div class="row activity-row" data-creation="{%= creation.split(" ")[0] + " 00:00:00" %}">
<div class="col-xs-3 text-right activity-date"><span class="{%= date_class %}">
{%= date_sep || "" %}</span></div>
<div class="col-xs-9 activity-message"
title="{%= by %} / {%= frappe.datetime.str_to_user(creation) %}">
<div class="row">
<div class="col-xs-2 col-sm-1">
{{ avatar }}
</div>
<div class="col-xs-10 col-sm-11 small content">
{{ content }}
</div>
</div>
</div>
</div>
|
2302_79757062/hrms
|
hrms/hr/page/team_updates/team_update_row.html
|
HTML
|
agpl-3.0
| 502
|
.date-indicator {
background: none;
font-size: 12px;
vertical-align: middle;
font-weight: bold;
color: #6c7680;
}
.date-indicator::after {
margin: 0 -4px 0 12px;
content: "";
display: inline-block;
height: 8px;
width: 8px;
border-radius: 8px;
background: #d1d8dd;
}
.date-indicator.blue {
color: #5e64ff;
}
.date-indicator.blue::after {
background: #5e64ff;
}
.activity-row {
}
.activity-message {
border-left: 1px solid #d1d8dd;
}
.activity-message .row {
padding: 15px;
margin-right: 0px;
border-bottom: 1px solid #d1d8dd;
}
.activity-row:last-child .activity-message .row {
border-bottom: none;
}
.activity-row .content {
padding-left: 0px;
padding-right: 30px;
}
.activity-date {
padding: 15px;
padding-right: 0px;
z-index: 1;
}
.for-more {
border-top: 1px solid #d1d8dd;
padding: 10px;
}
|
2302_79757062/hrms
|
hrms/hr/page/team_updates/team_updates.css
|
CSS
|
agpl-3.0
| 828
|
frappe.pages["team-updates"].on_page_load = function (wrapper) {
var page = frappe.ui.make_app_page({
parent: wrapper,
title: __("Team Updates"),
single_column: true,
});
frappe.team_updates.make(page);
frappe.team_updates.run();
if (frappe.model.can_read("Daily Work Summary Group")) {
page.add_menu_item(__("Daily Work Summary Group"), function () {
frappe.set_route("Form", "Daily Work Summary Group");
});
}
};
frappe.team_updates = {
start: 0,
make: function (page) {
var me = frappe.team_updates;
me.page = page;
me.body = $("<div></div>").appendTo(me.page.main);
me.more = $(
'<div class="for-more"><button class="btn btn-sm btn-default btn-more">' +
__("More") +
"</button></div>",
)
.appendTo(me.page.main)
.find(".btn-more")
.on("click", function () {
me.start += 40;
me.run();
});
},
run: function () {
var me = frappe.team_updates;
frappe.call({
method: "hrms.hr.page.team_updates.team_updates.get_data",
args: {
start: me.start,
},
callback: function (r) {
if (r.message && r.message.length > 0) {
r.message.forEach(function (d) {
me.add_row(d);
});
} else {
frappe.show_alert({ message: __("No more updates"), indicator: "gray" });
me.more.parent().addClass("hidden");
}
},
});
},
add_row: function (data) {
var me = frappe.team_updates;
data.by = frappe.user.full_name(data.sender);
data.avatar = frappe.avatar(data.sender);
data.when = comment_when(data.creation);
var date = frappe.datetime.str_to_obj(data.creation);
var last = me.last_feed_date;
if (
(last && frappe.datetime.obj_to_str(last) != frappe.datetime.obj_to_str(date)) ||
!last
) {
var diff = frappe.datetime.get_day_diff(
frappe.datetime.get_today(),
frappe.datetime.obj_to_str(date),
);
var pdate;
if (diff < 1) {
pdate = "Today";
} else if (diff < 2) {
pdate = "Yesterday";
} else {
pdate = frappe.datetime.global_date_format(date);
}
data.date_sep = pdate;
data.date_class = pdate == "Today" ? "date-indicator blue" : "date-indicator";
} else {
data.date_sep = null;
data.date_class = "";
}
me.last_feed_date = date;
$(frappe.render_template("team_update_row", data)).appendTo(me.body);
},
};
|
2302_79757062/hrms
|
hrms/hr/page/team_updates/team_updates.js
|
JavaScript
|
agpl-3.0
| 2,297
|
from email_reply_parser import EmailReplyParser
import frappe
@frappe.whitelist()
def get_data(start=0):
# frappe.only_for('Employee', 'System Manager')
data = frappe.get_all(
"Communication",
fields=("content", "text_content", "sender", "creation"),
filters=dict(reference_doctype="Daily Work Summary"),
order_by="creation desc",
limit=40,
start=start,
)
for d in data:
d.sender_name = frappe.db.get_value("Employee", {"user_id": d.sender}, "employee_name") or d.sender
if d.text_content:
d.content = frappe.utils.md_to_html(EmailReplyParser.parse_reply(d.text_content))
return data
|
2302_79757062/hrms
|
hrms/hr/page/team_updates/team_updates.py
|
Python
|
agpl-3.0
| 613
|
{%- from "templates/print_formats/standard_macros.html" import add_header -%}
<div class="text-center" style="margin-bottom: 10%;"><h3>Appointment Letter</h3></div>
<div class ='row' style="margin-bottom: 5%;">
<div class = "col-sm-6">
<b>{{ doc.applicant_name }},</b>
</div>
<div class="col-sm-6">
<span style = "float: right;"><b> Date: </b>{{ doc.appointment_date }}</span>
</div>
</div>
<div style="margin-bottom: 5%;">
{{ doc.introduction }}
</div>
<div style="margin-bottom: 5%;">
<ul>
{% for content in doc.terms %}
<li style="padding-bottom: 3%;">
<span>
<span><b>{{ content.title }}: </b></span> {{ content.description }}
</span>
</li>
{% endfor %}
</ul>
</div>
<div style="margin-bottom: 5%;">
<span>Your sincerely,</span><br>
<span><b>For {{ doc.company }}</b></span>
</div>
<div style="margin-bottom: 5%;">
<span>{{ doc.closing_notes }}</span>
</div>
<div>
<span><b>________________</b></span><br>
<span><b>{{ doc.applicant_name }}</b></span>
</div>
|
2302_79757062/hrms
|
hrms/hr/print_format/standard_appointment_letter/standard_appointment_letter.html
|
HTML
|
agpl-3.0
| 1,085
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
/* eslint-disable */
frappe.query_reports["Appraisal Overview"] = {
filters: [
{
fieldname: "company",
label: __("Company"),
fieldtype: "Link",
options: "Company",
reqd: 1,
default: frappe.defaults.get_user_default("Company"),
},
{
fieldname: "appraisal_cycle",
fieldtype: "Link",
label: __("Appraisal Cycle"),
options: "Appraisal Cycle",
},
{
fieldname: "employee",
fieldtype: "Link",
label: __("Employee"),
options: "Employee",
},
{
fieldname: "department",
label: __("Department"),
fieldtype: "Link",
options: "Department",
},
{
fieldname: "designation",
label: __("Designation"),
fieldtype: "Link",
options: "Designation",
},
],
};
|
2302_79757062/hrms
|
hrms/hr/report/appraisal_overview/appraisal_overview.js
|
JavaScript
|
agpl-3.0
| 846
|