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) 2023, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ def execute(filters: dict | None = None) -> tuple: filters = frappe._dict(filters or {}) columns = get_columns() data = get_data(filters) chart = get_chart_data(data) return columns, data, None, chart def get_columns() -> list[dict]: return [ { "fieldname": "employee", "fieldtype": "Link", "label": _("Employee"), "options": "Employee", "width": 100, }, {"fieldname": "employee_name", "fieldtype": "Data", "label": _("Employee Name"), "width": 0}, { "fieldname": "designation", "fieldtype": "Link", "label": _("Designation"), "options": "Designation", "width": 100, }, { "fieldname": "appraisal_cycle", "fieldtype": "Link", "label": _("Appraisal Cycle"), "options": "Appraisal Cycle", "width": 100, }, { "fieldname": "appraisal", "fieldtype": "Link", "label": _("Appraisal"), "options": "Appraisal", "width": 0, }, {"fieldname": "feedback_count", "fieldtype": "Int", "label": _("Feedback Count"), "width": 0}, { "fieldname": "avg_feedback_score", "fieldtype": "Float", "label": _("Avg Feedback Score"), "width": 0, }, {"fieldname": "goal_score", "fieldtype": "Float", "label": _("Goal Score"), "width": 0}, {"fieldname": "self_score", "fieldtype": "Float", "label": _("Self Score"), "width": 0}, {"fieldname": "final_score", "fieldtype": "Float", "label": _("Final Score"), "width": 0}, { "fieldname": "department", "fieldtype": "Link", "label": _("Department"), "options": "Department", "width": 150, }, ] def get_data(filters: dict | None = None) -> list[dict]: Appraisal = frappe.qb.DocType("Appraisal") query = ( frappe.qb.from_(Appraisal) .select( Appraisal.employee, Appraisal.employee_name, Appraisal.designation, Appraisal.department, Appraisal.appraisal_cycle, Appraisal.name.as_("appraisal"), Appraisal.avg_feedback_score, Appraisal.total_score.as_("goal_score"), Appraisal.self_score, Appraisal.final_score, ) .where(Appraisal.docstatus != 2) ) for condition in ["appraisal_cycle", "employee", "department", "designation", "company"]: if filters.get(condition): query = query.where(Appraisal[condition] == filters.get(condition)) query = query.orderby(Appraisal.appraisal_cycle) query = query.orderby(Appraisal.final_score, order=frappe.qb.desc) appraisals = query.run(as_dict=True) for row in appraisals: row["feedback_count"] = frappe.db.count( "Employee Performance Feedback", {"appraisal": row.appraisal, "docstatus": 1} ) return appraisals def get_chart_data(data: list[dict]) -> dict: labels = [] goal_score = [] self_score = [] feedback_score = [] final_score = [] # show only top 10 in the chart for better readability for row in data[:10]: labels.append(row.employee_name) goal_score.append(row.goal_score) self_score.append(row.self_score) feedback_score.append(row.avg_feedback_score) final_score.append(row.final_score) return { "data": { "labels": labels, "datasets": [ {"name": _("Goal Score"), "values": goal_score}, {"name": _("Self Score"), "values": self_score}, {"name": _("Feedback Score"), "values": feedback_score}, {"name": _("Final Score"), "values": final_score}, ], }, "type": "bar", "barOptions": {"spaceRatio": 0.7}, "height": 250, }
2302_79757062/hrms
hrms/hr/report/appraisal_overview/appraisal_overview.py
Python
agpl-3.0
3,485
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Daily Work Summary Replies"] = { filters: [ { fieldname: "group", label: __("Group"), fieldtype: "Link", options: "Daily Work Summary Group", reqd: 1, }, { fieldname: "range", label: __("Date Range"), fieldtype: "DateRange", reqd: 1, }, ], };
2302_79757062/hrms
hrms/hr/report/daily_work_summary_replies/daily_work_summary_replies.js
JavaScript
agpl-3.0
445
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from hrms.hr.doctype.daily_work_summary.daily_work_summary import get_user_emails_from_group def execute(filters=None): if not filters.group: return [], [] columns, data = get_columns(), get_data(filters) return columns, data def get_columns(filters=None): columns = [ {"label": _("User"), "fieldname": "user", "fieldtype": "Data", "width": 300}, { "label": _("Replies"), "fieldname": "count", "fieldtype": "data", "width": 100, "align": "right", }, { "label": _("Total"), "fieldname": "total", "fieldtype": "data", "width": 100, "align": "right", }, ] return columns def get_data(filters): daily_summary_emails = frappe.get_all( "Daily Work Summary", fields=["name"], filters=[["creation", "Between", filters.range]] ) daily_summary_emails = [d.get("name") for d in daily_summary_emails] replies = frappe.get_all( "Communication", fields=["content", "text_content", "sender"], filters=[ ["reference_doctype", "=", "Daily Work Summary"], ["reference_name", "in", daily_summary_emails], ["communication_type", "=", "Communication"], ["sent_or_received", "=", "Received"], ], order_by="creation asc", ) data = [] total = len(daily_summary_emails) for user in get_user_emails_from_group(filters.group): user_name = frappe.get_value("User", user, "full_name") count = len([d for d in replies if d.sender == user]) data.append([user_name, count, total]) return data
2302_79757062/hrms
hrms/hr/report/daily_work_summary_replies/daily_work_summary_replies.py
Python
agpl-3.0
1,611
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Employee Advance Summary"] = { filters: [ { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", width: "80", }, { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", default: erpnext.utils.get_fiscal_year(frappe.datetime.get_today(), true)[1], width: "80", }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", default: frappe.datetime.get_today(), }, { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", }, { fieldname: "status", label: __("Status"), fieldtype: "Select", options: "\nDraft\nPaid\nUnpaid\nClaimed\nCancelled", }, ], };
2302_79757062/hrms
hrms/hr/report/employee_advance_summary/employee_advance_summary.js
JavaScript
agpl-3.0
884
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _, msgprint def execute(filters=None): if not filters: filters = {} advances_list = get_advances(filters) columns = get_columns() if not advances_list: msgprint(_("No record found")) return columns, advances_list data = [] for advance in advances_list: row = [ advance.name, advance.employee, advance.company, advance.posting_date, advance.advance_amount, advance.paid_amount, advance.claimed_amount, advance.status, ] data.append(row) return columns, data def get_columns(): return [ { "label": _("Title"), "fieldname": "title", "fieldtype": "Link", "options": "Employee Advance", "width": 120, }, { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 120, }, { "label": _("Company"), "fieldname": "company", "fieldtype": "Link", "options": "Company", "width": 120, }, {"label": _("Posting Date"), "fieldname": "posting_date", "fieldtype": "Date", "width": 120}, { "label": _("Advance Amount"), "fieldname": "advance_amount", "fieldtype": "Currency", "width": 120, }, {"label": _("Paid Amount"), "fieldname": "paid_amount", "fieldtype": "Currency", "width": 120}, { "label": _("Claimed Amount"), "fieldname": "claimed_amount", "fieldtype": "Currency", "width": 120, }, {"label": _("Status"), "fieldname": "status", "fieldtype": "Data", "width": 120}, ] def get_conditions(filters): conditions = "" if filters.get("employee"): conditions += "and employee = %(employee)s" if filters.get("company"): conditions += " and company = %(company)s" if filters.get("status"): conditions += " and status = %(status)s" if filters.get("from_date"): conditions += " and posting_date>=%(from_date)s" if filters.get("to_date"): conditions += " and posting_date<=%(to_date)s" return conditions def get_advances(filters): conditions = get_conditions(filters) return frappe.db.sql( """select name, employee, paid_amount, status, advance_amount, claimed_amount, company, posting_date, purpose from `tabEmployee Advance` where docstatus<2 %s order by posting_date, name desc""" % conditions, filters, as_dict=1, )
2302_79757062/hrms
hrms/hr/report/employee_advance_summary/employee_advance_summary.py
Python
agpl-3.0
2,386
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Employee Analytics"] = { filters: [ { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), reqd: 1, }, { fieldname: "parameter", label: __("Parameter"), fieldtype: "Select", options: ["Branch", "Grade", "Department", "Designation", "Employment Type"], reqd: 1, }, ], };
2302_79757062/hrms
hrms/hr/report/employee_analytics/employee_analytics.js
JavaScript
agpl-3.0
562
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} if not filters["company"]: frappe.throw(_("{0} is mandatory").format(_("Company"))) columns = get_columns() employees = get_employees(filters) parameters_result = get_parameters(filters) parameters = [] if parameters_result: for department in parameters_result: parameters.append(department) chart = get_chart_data(parameters, employees, filters) return columns, employees, None, chart def get_columns(): return [ _("Employee") + ":Link/Employee:120", _("Name") + ":Data:200", _("Date of Birth") + ":Date:100", _("Branch") + ":Link/Branch:120", _("Department") + ":Link/Department:120", _("Designation") + ":Link/Designation:120", _("Gender") + "::100", _("Company") + ":Link/Company:120", ] def get_conditions(filters): conditions = " and " + filters.get("parameter").lower().replace(" ", "_") + " IS NOT NULL " if filters.get("company"): conditions += " and company = '%s'" % filters["company"].replace("'", "\\'") return conditions def get_employees(filters): conditions = get_conditions(filters) # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql return frappe.db.sql( """select name, employee_name, date_of_birth, branch, department, designation, gender, company from `tabEmployee` where status = 'Active' %s""" % conditions, as_list=1, ) def get_parameters(filters): if filters.get("parameter") == "Grade": parameter = "Employee Grade" else: parameter = filters.get("parameter") return frappe.db.sql("""select name from `tab""" + parameter + """` """, as_list=1) def get_chart_data(parameters, employees, filters): if not parameters: parameters = [] datasets = [] parameter_field_name = filters.get("parameter").lower().replace(" ", "_") label = [] for parameter in parameters: if parameter: total_employee = frappe.db.sql( """select count(*) from `tabEmployee` where """ + parameter_field_name + """ = %s and company = %s""", (parameter[0], filters.get("company")), as_list=1, ) if total_employee[0][0]: label.append(parameter) datasets.append(total_employee[0][0]) values = [value for value in datasets if value != 0] total_employee = frappe.db.count("Employee", {"status": "Active"}) others = total_employee - sum(values) label.append(["Not Set"]) values.append(others) chart = {"data": {"labels": label, "datasets": [{"name": "Employees", "values": values}]}} chart["type"] = "donut" return chart
2302_79757062/hrms
hrms/hr/report/employee_analytics/employee_analytics.py
Python
agpl-3.0
2,667
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.query_reports["Employee Birthday"] = { filters: [ { fieldname: "month", label: __("Month"), fieldtype: "Select", options: "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec", default: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ][frappe.datetime.str_to_obj(frappe.datetime.get_today()).getMonth()], }, { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), }, ], };
2302_79757062/hrms
hrms/hr/report/employee_birthday/employee_birthday.js
JavaScript
agpl-3.0
729
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data def get_columns(): return [ _("Employee") + ":Link/Employee:120", _("Name") + ":Data:200", _("Date of Birth") + ":Date:100", _("Branch") + ":Link/Branch:120", _("Department") + ":Link/Department:120", _("Designation") + ":Link/Designation:120", _("Gender") + "::60", _("Company") + ":Link/Company:120", ] def get_employees(filters): conditions = get_conditions(filters) return frappe.db.sql( """select name, employee_name, date_of_birth, branch, department, designation, gender, company from tabEmployee where status = 'Active' %s""" % conditions, as_list=1, ) def get_conditions(filters): conditions = "" if filters.get("month"): month = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ].index(filters["month"]) + 1 conditions += " and month(date_of_birth) = '%s'" % month if filters.get("company"): conditions += " and company = '%s'" % filters["company"].replace("'", "\\'") return conditions
2302_79757062/hrms
hrms/hr/report/employee_birthday/employee_birthday.py
Python
agpl-3.0
1,324
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Employee Exits"] = { filters: [ { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", default: frappe.datetime.add_months(frappe.datetime.nowdate(), -12), }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", default: frappe.datetime.nowdate(), }, { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", }, { fieldname: "department", label: __("Department"), fieldtype: "Link", options: "Department", }, { fieldname: "designation", label: __("Designation"), fieldtype: "Link", options: "Designation", }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, { fieldname: "reports_to", label: __("Reports To"), fieldtype: "Link", options: "Employee", }, { fieldname: "interview_status", label: __("Interview Status"), fieldtype: "Select", options: ["", "Pending", "Scheduled", "Completed"], }, { fieldname: "final_decision", label: __("Final Decision"), fieldtype: "Select", options: ["", "Employee Retained", "Exit Confirmed"], }, { fieldname: "exit_interview_pending", label: __("Exit Interview Pending"), fieldtype: "Check", }, { fieldname: "questionnaire_pending", label: __("Exit Questionnaire Pending"), fieldtype: "Check", }, { fieldname: "fnf_pending", label: __("FnF Pending"), fieldtype: "Check", }, ], };
2302_79757062/hrms
hrms/hr/report/employee_exits/employee_exits.js
JavaScript
agpl-3.0
1,660
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # License: MIT. See LICENSE from pypika import functions as fn import frappe from frappe import _ from frappe.query_builder import Order from frappe.utils import getdate def execute(filters=None): columns = get_columns() data = get_data(filters) chart = get_chart_data(data) report_summary = get_report_summary(data) return columns, data, None, chart, report_summary def get_columns(): return [ { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 150, }, {"label": _("Employee Name"), "fieldname": "employee_name", "fieldtype": "Data", "width": 150}, { "label": _("Date of Joining"), "fieldname": "date_of_joining", "fieldtype": "Date", "width": 120, }, {"label": _("Relieving Date"), "fieldname": "relieving_date", "fieldtype": "Date", "width": 120}, { "label": _("Exit Interview"), "fieldname": "exit_interview", "fieldtype": "Link", "options": "Exit Interview", "width": 150, }, { "label": _("Interview Status"), "fieldname": "interview_status", "fieldtype": "Data", "width": 130, }, { "label": _("Final Decision"), "fieldname": "employee_status", "fieldtype": "Data", "width": 150, }, { "label": _("Full and Final Statement"), "fieldname": "full_and_final_statement", "fieldtype": "Link", "options": "Full and Final Statement", "width": 180, }, { "label": _("Department"), "fieldname": "department", "fieldtype": "Link", "options": "Department", "width": 120, }, { "label": _("Designation"), "fieldname": "designation", "fieldtype": "Link", "options": "Designation", "width": 120, }, { "label": _("Reports To"), "fieldname": "reports_to", "fieldtype": "Link", "options": "Employee", "width": 120, }, ] def get_data(filters): employee = frappe.qb.DocType("Employee") interview = frappe.qb.DocType("Exit Interview") fnf = frappe.qb.DocType("Full and Final Statement") query = ( frappe.qb.from_(employee) .left_join(interview) .on(interview.employee == employee.name) .left_join(fnf) .on(fnf.employee == employee.name) .select( employee.name.as_("employee"), employee.employee_name.as_("employee_name"), employee.date_of_joining.as_("date_of_joining"), employee.relieving_date.as_("relieving_date"), employee.department.as_("department"), employee.designation.as_("designation"), employee.reports_to.as_("reports_to"), interview.name.as_("exit_interview"), interview.status.as_("interview_status"), interview.employee_status.as_("employee_status"), interview.reference_document_name.as_("questionnaire"), fnf.name.as_("full_and_final_statement"), ) .distinct() .where( (fn.Coalesce(fn.Cast(employee.relieving_date, "char"), "") != "") & ((interview.name.isnull()) | ((interview.name.isnotnull()) & (interview.docstatus != 2))) & ((fnf.name.isnull()) | ((fnf.name.isnotnull()) & (fnf.docstatus != 2))) ) .orderby(employee.relieving_date, order=Order.asc) ) query = get_conditions(filters, query, employee, interview, fnf) result = query.run(as_dict=True) return result def get_conditions(filters, query, employee, interview, fnf): if filters.get("from_date") and filters.get("to_date"): query = query.where( employee.relieving_date[getdate(filters.get("from_date")) : getdate(filters.get("to_date"))] ) elif filters.get("from_date"): query = query.where(employee.relieving_date >= filters.get("from_date")) elif filters.get("to_date"): query = query.where(employee.relieving_date <= filters.get("to_date")) if filters.get("company"): query = query.where(employee.company == filters.get("company")) if filters.get("department"): query = query.where(employee.department == filters.get("department")) if filters.get("designation"): query = query.where(employee.designation == filters.get("designation")) if filters.get("employee"): query = query.where(employee.name == filters.get("employee")) if filters.get("reports_to"): query = query.where(employee.reports_to == filters.get("reports_to")) if filters.get("interview_status"): query = query.where(interview.status == filters.get("interview_status")) if filters.get("final_decision"): query = query.where(interview.employee_status == filters.get("final_decision")) if filters.get("exit_interview_pending"): query = query.where((interview.name == "") | (interview.name.isnull())) if filters.get("questionnaire_pending"): query = query.where( (interview.reference_document_name == "") | (interview.reference_document_name.isnull()) ) if filters.get("fnf_pending"): query = query.where((fnf.name == "") | (fnf.name.isnull())) return query def get_chart_data(data): if not data: return None retained = 0 exit_confirmed = 0 pending = 0 for entry in data: if entry.employee_status == "Employee Retained": retained += 1 elif entry.employee_status == "Exit Confirmed": exit_confirmed += 1 else: pending += 1 chart = { "data": { "labels": [_("Retained"), _("Exit Confirmed"), _("Decision Pending")], "datasets": [{"name": _("Employee Status"), "values": [retained, exit_confirmed, pending]}], }, "type": "donut", "colors": ["green", "red", "blue"], } return chart def get_report_summary(data): if not data: return None total_resignations = len(data) interviews_pending = len([entry.name for entry in data if not entry.exit_interview]) fnf_pending = len([entry.name for entry in data if not entry.full_and_final_statement]) questionnaires_pending = len([entry.name for entry in data if not entry.questionnaire]) return [ { "value": total_resignations, "label": _("Total Resignations"), "indicator": "Red" if total_resignations > 0 else "Green", "datatype": "Int", }, { "value": interviews_pending, "label": _("Pending Interviews"), "indicator": "Blue" if interviews_pending > 0 else "Green", "datatype": "Int", }, { "value": fnf_pending, "label": _("Pending FnF"), "indicator": "Blue" if fnf_pending > 0 else "Green", "datatype": "Int", }, { "value": questionnaires_pending, "label": _("Pending Questionnaires"), "indicator": "Blue" if questionnaires_pending > 0 else "Green", "datatype": "Int", }, ]
2302_79757062/hrms
hrms/hr/report/employee_exits/employee_exits.py
Python
agpl-3.0
6,408
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Employee Hours Utilization Based On Timesheet"] = { filters: [ { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), reqd: 1, }, { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", default: frappe.datetime.add_months(frappe.datetime.get_today(), -1), reqd: 1, }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", default: frappe.datetime.now_date(), reqd: 1, }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, { fieldname: "department", label: __("Department"), fieldtype: "Link", options: "Department", }, { fieldname: "project", label: __("Project"), fieldtype: "Link", options: "Project", }, ], };
2302_79757062/hrms
hrms/hr/report/employee_hours_utilization_based_on_timesheet/employee_hours_utilization_based_on_timesheet.js
JavaScript
agpl-3.0
1,036
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.utils import flt, getdate def execute(filters=None): return EmployeeHoursReport(filters).run() class EmployeeHoursReport: """Employee Hours Utilization Report Based On Timesheet""" def __init__(self, filters=None): self.filters = frappe._dict(filters or {}) self.from_date = getdate(self.filters.from_date) self.to_date = getdate(self.filters.to_date) self.validate_dates() self.validate_standard_working_hours() def validate_dates(self): self.day_span = (self.to_date - self.from_date).days if self.day_span <= 0: frappe.throw(_("From Date must come before To Date")) def validate_standard_working_hours(self): self.standard_working_hours = frappe.db.get_single_value("HR Settings", "standard_working_hours") if not self.standard_working_hours: msg = _("The metrics for this report are calculated based on {0}. Please set {0} in {1}.").format( frappe.bold(_("Standard Working Hours")), frappe.utils.get_link_to_form("HR Settings", "HR Settings"), ) frappe.throw(msg) def run(self): self.generate_columns() self.generate_data() self.generate_report_summary() self.generate_chart_data() return self.columns, self.data, None, self.chart, self.report_summary def generate_columns(self): self.columns = [ { "label": _("Employee"), "options": "Employee", "fieldname": "employee", "fieldtype": "Link", "width": 230, }, { "label": _("Department"), "options": "Department", "fieldname": "department", "fieldtype": "Link", "width": 120, }, {"label": _("Total Hours (T)"), "fieldname": "total_hours", "fieldtype": "Float", "width": 120}, { "label": _("Billed Hours (B)"), "fieldname": "billed_hours", "fieldtype": "Float", "width": 170, }, { "label": _("Non-Billed Hours (NB)"), "fieldname": "non_billed_hours", "fieldtype": "Float", "width": 170, }, { "label": _("Untracked Hours (U)"), "fieldname": "untracked_hours", "fieldtype": "Float", "width": 170, }, { "label": _("% Utilization (B + NB) / T"), "fieldname": "per_util", "fieldtype": "Percentage", "width": 200, }, { "label": _("% Utilization (B / T)"), "fieldname": "per_util_billed_only", "fieldtype": "Percentage", "width": 200, }, ] def generate_data(self): self.generate_filtered_time_logs() self.generate_stats_by_employee() self.set_employee_department_and_name() if self.filters.department: self.filter_stats_by_department() self.calculate_utilizations() self.data = [] for emp, data in self.stats_by_employee.items(): row = frappe._dict() row["employee"] = emp row.update(data) self.data.append(row) # Sort by descending order of percentage utilization self.data.sort(key=lambda x: x["per_util"], reverse=True) def filter_stats_by_department(self): filtered_data = frappe._dict() for emp, data in self.stats_by_employee.items(): if data["department"] == self.filters.department: filtered_data[emp] = data # Update stats self.stats_by_employee = filtered_data def generate_filtered_time_logs(self): additional_filters = "" filter_fields = ["employee", "project", "company"] for field in filter_fields: if self.filters.get(field): if field == "project": additional_filters += f" AND ttd.{field} = {self.filters.get(field)!r}" else: additional_filters += f" AND tt.{field} = {self.filters.get(field)!r}" # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql self.filtered_time_logs = frappe.db.sql( f""" SELECT tt.employee AS employee, ttd.hours AS hours, ttd.is_billable AS is_billable, ttd.project AS project FROM `tabTimesheet Detail` AS ttd JOIN `tabTimesheet` AS tt ON ttd.parent = tt.name WHERE tt.employee IS NOT NULL AND tt.start_date BETWEEN '{self.filters.from_date}' AND '{self.filters.to_date}' AND tt.end_date BETWEEN '{self.filters.from_date}' AND '{self.filters.to_date}' {additional_filters} """ ) def generate_stats_by_employee(self): self.stats_by_employee = frappe._dict() for emp, hours, is_billable, __ in self.filtered_time_logs: self.stats_by_employee.setdefault(emp, frappe._dict()).setdefault("billed_hours", 0.0) self.stats_by_employee[emp].setdefault("non_billed_hours", 0.0) if is_billable: self.stats_by_employee[emp]["billed_hours"] += flt(hours, 2) else: self.stats_by_employee[emp]["non_billed_hours"] += flt(hours, 2) def set_employee_department_and_name(self): for emp in self.stats_by_employee: emp_name = frappe.db.get_value("Employee", emp, "employee_name") emp_dept = frappe.db.get_value("Employee", emp, "department") self.stats_by_employee[emp]["department"] = emp_dept self.stats_by_employee[emp]["employee_name"] = emp_name def calculate_utilizations(self): TOTAL_HOURS = flt(self.standard_working_hours * self.day_span, 2) for __, data in self.stats_by_employee.items(): data["total_hours"] = TOTAL_HOURS data["untracked_hours"] = flt(TOTAL_HOURS - data["billed_hours"] - data["non_billed_hours"], 2) # To handle overtime edge-case if data["untracked_hours"] < 0: data["untracked_hours"] = 0.0 data["per_util"] = flt(((data["billed_hours"] + data["non_billed_hours"]) / TOTAL_HOURS) * 100, 2) data["per_util_billed_only"] = flt((data["billed_hours"] / TOTAL_HOURS) * 100, 2) def generate_report_summary(self): self.report_summary = [] if not self.data: return avg_utilization = 0.0 avg_utilization_billed_only = 0.0 total_billed, total_non_billed = 0.0, 0.0 total_untracked = 0.0 for row in self.data: avg_utilization += row["per_util"] avg_utilization_billed_only += row["per_util_billed_only"] total_billed += row["billed_hours"] total_non_billed += row["non_billed_hours"] total_untracked += row["untracked_hours"] avg_utilization /= len(self.data) avg_utilization = flt(avg_utilization, 2) avg_utilization_billed_only /= len(self.data) avg_utilization_billed_only = flt(avg_utilization_billed_only, 2) THRESHOLD_PERCENTAGE = 70.0 self.report_summary = [ { "value": f"{avg_utilization}%", "indicator": "Red" if avg_utilization < THRESHOLD_PERCENTAGE else "Green", "label": _("Avg Utilization"), "datatype": "Percentage", }, { "value": f"{avg_utilization_billed_only}%", "indicator": "Red" if avg_utilization_billed_only < THRESHOLD_PERCENTAGE else "Green", "label": _("Avg Utilization (Billed Only)"), "datatype": "Percentage", }, {"value": total_billed, "label": _("Total Billed Hours"), "datatype": "Float"}, {"value": total_non_billed, "label": _("Total Non-Billed Hours"), "datatype": "Float"}, ] def generate_chart_data(self): self.chart = {} labels = [] billed_hours = [] non_billed_hours = [] untracked_hours = [] for row in self.data: labels.append(row.get("employee_name")) billed_hours.append(row.get("billed_hours")) non_billed_hours.append(row.get("non_billed_hours")) untracked_hours.append(row.get("untracked_hours")) self.chart = { "data": { "labels": labels[:30], "datasets": [ {"name": _("Billed Hours"), "values": billed_hours[:30]}, {"name": _("Non-Billed Hours"), "values": non_billed_hours[:30]}, {"name": _("Untracked Hours"), "values": untracked_hours[:30]}, ], }, "type": "bar", "barOptions": {"stacked": True}, }
2302_79757062/hrms
hrms/hr/report/employee_hours_utilization_based_on_timesheet/employee_hours_utilization_based_on_timesheet.py
Python
agpl-3.0
7,628
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.query_reports["Employee Leave Balance"] = { filters: [ { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", reqd: 1, }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", reqd: 1, }, { label: __("Company"), fieldname: "company", fieldtype: "Link", options: "Company", reqd: 1, default: frappe.defaults.get_user_default("Company"), }, { fieldname: "department", label: __("Department"), fieldtype: "Link", options: "Department", }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, { fieldname: "employee_status", label: __("Employee Status"), fieldtype: "Select", options: [ "", { value: "Active", label: __("Active") }, { value: "Inactive", label: __("Inactive") }, { value: "Suspended", label: __("Suspended") }, { value: "Left", label: __("Left", null, "Employee") }, ], default: "Active", }, { fieldname: "consolidate_leave_types", label: __("Consolidate Leave Types"), fieldtype: "Check", default: 1, depends_on: "eval: !doc.employee", }, ], onload: () => { const today = frappe.datetime.now_date(); frappe.call({ type: "GET", method: "hrms.hr.utils.get_leave_period", args: { from_date: today, to_date: today, company: frappe.defaults.get_user_default("Company"), }, freeze: true, callback: (data) => { frappe.query_report.set_filter_value("from_date", data.message[0].from_date); frappe.query_report.set_filter_value("to_date", data.message[0].to_date); }, }); }, };
2302_79757062/hrms
hrms/hr/report/employee_leave_balance/employee_leave_balance.js
JavaScript
agpl-3.0
1,781
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from itertools import groupby import frappe from frappe import _ from frappe.utils import add_days, cint, flt, getdate from hrms.hr.doctype.leave_allocation.leave_allocation import get_previous_allocation from hrms.hr.doctype.leave_application.leave_application import ( get_leave_balance_on, get_leaves_for_period, ) Filters = frappe._dict def execute(filters: Filters | None = None) -> tuple: if filters.to_date <= filters.from_date: frappe.throw(_('"From Date" can not be greater than or equal to "To Date"')) columns = get_columns() data = get_data(filters) charts = get_chart_data(data, filters) return columns, data, None, charts def get_columns() -> list[dict]: return [ { "label": _("Leave Type"), "fieldtype": "Link", "fieldname": "leave_type", "width": 200, "options": "Leave Type", }, { "label": _("Employee"), "fieldtype": "Link", "fieldname": "employee", "width": 100, "options": "Employee", }, { "label": _("Employee Name"), "fieldtype": "Dynamic Link", "fieldname": "employee_name", "width": 100, "options": "employee", }, { "label": _("Opening Balance"), "fieldtype": "float", "fieldname": "opening_balance", "width": 150, }, { "label": _("New Leave(s) Allocated"), "fieldtype": "float", "fieldname": "leaves_allocated", "width": 200, }, { "label": _("Leave(s) Taken"), "fieldtype": "float", "fieldname": "leaves_taken", "width": 150, }, { "label": _("Leave(s) Expired"), "fieldtype": "float", "fieldname": "leaves_expired", "width": 150, }, { "label": _("Closing Balance"), "fieldtype": "float", "fieldname": "closing_balance", "width": 150, }, ] def get_data(filters: Filters) -> list: leave_types = get_leave_types() active_employees = get_employees(filters) precision = cint(frappe.db.get_single_value("System Settings", "float_precision")) consolidate_leave_types = len(active_employees) > 1 and filters.consolidate_leave_types row = None data = [] for leave_type in leave_types: if consolidate_leave_types: data.append({"leave_type": leave_type}) else: row = frappe._dict({"leave_type": leave_type}) for employee in active_employees: if consolidate_leave_types: row = frappe._dict() else: row = frappe._dict({"leave_type": leave_type}) row.employee = employee.name row.employee_name = employee.employee_name leaves_taken = ( get_leaves_for_period(employee.name, leave_type, filters.from_date, filters.to_date) * -1 ) new_allocation, expired_leaves, carry_forwarded_leaves = get_allocated_and_expired_leaves( filters.from_date, filters.to_date, employee.name, leave_type ) opening = get_opening_balance(employee.name, leave_type, filters, carry_forwarded_leaves) row.leaves_allocated = flt(new_allocation, precision) row.leaves_expired = flt(expired_leaves, precision) row.opening_balance = flt(opening, precision) row.leaves_taken = flt(leaves_taken, precision) closing = new_allocation + opening - (row.leaves_expired + leaves_taken) row.closing_balance = flt(closing, precision) row.indent = 1 data.append(row) return data def get_leave_types() -> list[str]: LeaveType = frappe.qb.DocType("Leave Type") return (frappe.qb.from_(LeaveType).select(LeaveType.name).orderby(LeaveType.name)).run(pluck="name") def get_employees(filters: Filters) -> list[dict]: Employee = frappe.qb.DocType("Employee") query = frappe.qb.from_(Employee).select( Employee.name, Employee.employee_name, Employee.department, ) for field in ["company", "department"]: if filters.get(field): query = query.where(getattr(Employee, field) == filters.get(field)) if filters.get("employee"): query = query.where(Employee.name == filters.get("employee")) if filters.get("employee_status"): query = query.where(Employee.status == filters.get("employee_status")) return query.run(as_dict=True) def get_opening_balance( employee: str, leave_type: str, filters: Filters, carry_forwarded_leaves: float ) -> float: # allocation boundary condition # opening balance is the closing leave balance 1 day before the filter start date opening_balance_date = add_days(filters.from_date, -1) allocation = get_previous_allocation(filters.from_date, leave_type, employee) if ( allocation and allocation.get("to_date") and opening_balance_date and getdate(allocation.get("to_date")) == getdate(opening_balance_date) ): # if opening balance date is same as the previous allocation's expiry # then opening balance should only consider carry forwarded leaves opening_balance = carry_forwarded_leaves else: # else directly get leave balance on the previous day opening_balance = get_leave_balance_on(employee, leave_type, opening_balance_date) return opening_balance def get_allocated_and_expired_leaves( from_date: str, to_date: str, employee: str, leave_type: str ) -> tuple[float, float, float]: new_allocation = 0 expired_leaves = 0 carry_forwarded_leaves = 0 records = get_leave_ledger_entries(from_date, to_date, employee, leave_type) for record in records: # new allocation records with `is_expired=1` are created when leave expires # these new records should not be considered, else it leads to negative leave balance if record.is_expired: continue if record.to_date < getdate(to_date): # leave allocations ending before to_date, reduce leaves taken within that period # since they are already used, they won't expire expired_leaves += record.leaves leaves_for_period = get_leaves_for_period(employee, leave_type, record.from_date, record.to_date) expired_leaves -= min(abs(leaves_for_period), record.leaves) if record.from_date >= getdate(from_date): if record.is_carry_forward: carry_forwarded_leaves += record.leaves else: new_allocation += record.leaves return new_allocation, expired_leaves, carry_forwarded_leaves def get_leave_ledger_entries(from_date: str, to_date: str, employee: str, leave_type: str) -> list[dict]: ledger = frappe.qb.DocType("Leave Ledger Entry") return ( frappe.qb.from_(ledger) .select( ledger.employee, ledger.leave_type, ledger.from_date, ledger.to_date, ledger.leaves, ledger.transaction_name, ledger.transaction_type, ledger.is_carry_forward, ledger.is_expired, ) .where( (ledger.docstatus == 1) & (ledger.transaction_type == "Leave Allocation") & (ledger.employee == employee) & (ledger.leave_type == leave_type) & ( (ledger.from_date[from_date:to_date]) | (ledger.to_date[from_date:to_date]) | ((ledger.from_date < from_date) & (ledger.to_date > to_date)) ) ) ).run(as_dict=True) def get_chart_data(data: list, filters: Filters) -> dict: labels = [] datasets = [] employee_data = data if not data: return None if data and filters.employee: get_dataset_for_chart(employee_data, datasets, labels) chart = { "data": {"labels": labels, "datasets": datasets}, "type": "bar", "colors": ["#456789", "#EE8888", "#7E77BF"], } return chart def get_dataset_for_chart(employee_data: list, datasets: list, labels: list) -> list: leaves = [] employee_data = sorted(employee_data, key=lambda k: k["employee_name"]) for key, group in groupby(employee_data, lambda x: x["employee_name"]): for grp in group: if grp.closing_balance: leaves.append( frappe._dict({"leave_type": grp.leave_type, "closing_balance": grp.closing_balance}) ) if leaves: labels.append(key) for leave in leaves: datasets.append({"name": leave.leave_type, "values": [leave.closing_balance]})
2302_79757062/hrms
hrms/hr/report/employee_leave_balance/employee_leave_balance.py
Python
agpl-3.0
7,784
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Employee Leave Balance Summary"] = { filters: [ { fieldname: "date", label: __("Date"), fieldtype: "Date", reqd: 1, default: frappe.datetime.now_date(), }, { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", reqd: 1, default: frappe.defaults.get_user_default("Company"), }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, { fieldname: "department", label: __("Department"), fieldtype: "Link", options: "Department", }, { fieldname: "employee_status", label: __("Employee Status"), fieldtype: "Select", options: [ "", { value: "Active", label: __("Active") }, { value: "Inactive", label: __("Inactive") }, { value: "Suspended", label: __("Suspended") }, { value: "Left", label: __("Left") }, ], default: "Active", }, ], };
2302_79757062/hrms
hrms/hr/report/employee_leave_balance_summary/employee_leave_balance_summary.js
JavaScript
agpl-3.0
1,080
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ from hrms.hr.doctype.leave_application.leave_application import get_leave_details def execute(filters=None): leave_types = frappe.db.sql_list("select name from `tabLeave Type` order by name asc") columns = get_columns(leave_types) data = get_data(filters, leave_types) return columns, data def get_columns(leave_types): columns = [ _("Employee") + ":Link/Employee:150", _("Employee Name") + "::200", _("Department") + ":Link/Department:150", ] for leave_type in leave_types: columns.append(_(leave_type) + ":Float:160") return columns def get_conditions(filters): conditions = { "company": filters.company, } if filters.get("employee_status"): conditions.update({"status": filters.get("employee_status")}) if filters.get("department"): conditions.update({"department": filters.get("department")}) if filters.get("employee"): conditions.update({"employee": filters.get("employee")}) return conditions def get_data(filters, leave_types): conditions = get_conditions(filters) active_employees = frappe.get_list( "Employee", filters=conditions, fields=["name", "employee_name", "department", "user_id"], ) data = [] for employee in active_employees: row = [employee.name, employee.employee_name, employee.department] available_leave = get_leave_details(employee.name, filters.date) for leave_type in leave_types: remaining = 0 if leave_type in available_leave["leave_allocation"]: # opening balance remaining = available_leave["leave_allocation"][leave_type]["remaining_leaves"] row += [remaining] data.append(row) return data
2302_79757062/hrms
hrms/hr/report/employee_leave_balance_summary/employee_leave_balance_summary.py
Python
agpl-3.0
1,773
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.query_reports["Employees working on a holiday"] = { filters: [ { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", reqd: 1, default: frappe.datetime.year_start(), }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", reqd: 1, default: frappe.datetime.year_end(), }, { fieldname: "holiday_list", label: __("Holiday List"), fieldtype: "Link", options: "Holiday List", }, ], };
2302_79757062/hrms
hrms/hr/report/employees_working_on_a_holiday/employees_working_on_a_holiday.js
JavaScript
agpl-3.0
591
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data def get_columns(): return [ _("Employee") + ":Link/Employee:120", _("Name") + ":Data:200", _("Date") + ":Date:100", _("Status") + ":Data:70", _("Holiday") + ":Data:200", ] def get_employees(filters): holiday_filter = [ ["holiday_date", ">=", filters.from_date], ["holiday_date", "<=", filters.to_date], ] if filters.holiday_list: holiday_filter.append(["parent", "=", filters.holiday_list]) holidays = frappe.get_all("Holiday", fields=["holiday_date", "description"], filters=holiday_filter) holiday_names = {} holidays_list = [] for holiday in holidays: holidays_list.append(holiday.holiday_date) holiday_names[holiday.holiday_date] = holiday.description if holidays_list: cond = " attendance_date in %(holidays_list)s and status not in ('On Leave','Absent') " if filters.holiday_list: cond += ( """ and (employee in (select employee from tabEmployee where holiday_list = %(holidays)s))""" ) employee_list = frappe.db.sql( """select employee, employee_name, attendance_date, status from tabAttendance where %s""" % cond.format(", ".join(["%s"] * len(holidays_list))), {"holidays_list": holidays_list, "holidays": filters.holiday_list}, as_list=True, ) for employee_data in employee_list: employee_data.append(holiday_names[employee_data[2]]) return employee_list else: return []
2302_79757062/hrms
hrms/hr/report/employees_working_on_a_holiday/employees_working_on_a_holiday.py
Python
agpl-3.0
1,668
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.query_reports["Leave Ledger"] = { filters: [ { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", reqd: 1, default: frappe.defaults.get_default("year_start_date"), }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", reqd: 1, default: frappe.defaults.get_default("year_end_date"), }, { fieldname: "leave_type", label: __("Leave Type"), fieldtype: "Link", options: "Leave Type", }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, { fieldname: "status", label: __("Employee Status"), fieldtype: "Select", options: [ "", { value: "Active", label: __("Active") }, { value: "Inactive", label: __("Inactive") }, { value: "Suspended", label: __("Suspended") }, { value: "Left", label: __("Left") }, ], default: "Active", }, { label: __("Company"), fieldname: "company", fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), }, { fieldname: "department", label: __("Department"), fieldtype: "Link", options: "Department", }, { fieldname: "transaction_type", label: __("Transaction Type"), fieldtype: "Select", options: ["", "Leave Allocation", "Leave Application", "Leave Encashment"], }, { fieldname: "transaction_name", label: __("Transaction Name"), fieldtype: "Data", }, ], formatter: (value, row, column, data, default_formatter) => { value = default_formatter(value, row, column, data); if (column.fieldname === "leaves") { if (data?.leaves < 0) value = `<span style='color:red!important'>${value}</span>`; else value = `<span style='color:green!important'>${value}</span>`; } return value; }, onload: () => { if ( frappe.query_report.get_filter_value("from_date") && frappe.query_report.get_filter_value("to_date") ) return; const today = frappe.datetime.now_date(); frappe.call({ type: "GET", method: "hrms.hr.utils.get_leave_period", args: { from_date: today, to_date: today, company: frappe.defaults.get_user_default("Company"), }, freeze: true, callback: (data) => { frappe.query_report.set_filter_value("from_date", data.message[0].from_date); frappe.query_report.set_filter_value("to_date", data.message[0].to_date); }, }); }, };
2302_79757062/hrms
hrms/hr/report/leave_ledger/leave_ledger.js
JavaScript
agpl-3.0
2,535
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.query_builder.functions import Date Filters = frappe._dict def execute(filters: Filters = None) -> tuple: columns = get_columns() data = get_data(filters) return columns, data def get_columns() -> list[dict]: return [ { "label": _("Leave Ledger Entry"), "fieldname": "leave_ledger_entry", "fieldtype": "Link", "options": "Leave Ledger Entry", "hidden": 1, }, { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 240, }, { "label": _("Employee Name"), "fieldname": "employee_name", "fieldtype": "Data", "hidden": 1, }, { "label": _("Creation Date"), "fieldname": "date", "fieldtype": "Date", "width": 120, }, { "label": _("From Date"), "fieldname": "from_date", "fieldtype": "Date", "width": 120, }, { "label": _("To Date"), "fieldname": "to_date", "fieldtype": "Date", "width": 120, }, { "label": _("Leaves"), "fieldname": "leaves", "fieldtype": "Float", "width": 80, }, { "label": _("Leave Type"), "fieldname": "leave_type", "fieldtype": "Link", "options": "Leave Type", "width": 150, }, { "label": _("Transaction Type"), "fieldname": "transaction_type", "fieldtype": "Link", "options": "DocType", "width": 130, }, { "label": _("Transaction Name"), "fieldname": "transaction_name", "fieldtype": "Dynamic Link", "options": "transaction_type", "width": 180, }, { "label": _("Is Carry Forward"), "fieldname": "is_carry_forward", "fieldtype": "Check", "width": 80, }, { "label": _("Is Expired"), "fieldname": "is_expired", "fieldtype": "Check", "width": 80, }, { "label": _("Is Leave Without Pay"), "fieldname": "is_lwp", "fieldtype": "Check", "width": 80, }, { "label": _("Company"), "fieldname": "company", "fieldtype": "Link", "options": "Company", "width": 150, }, { "label": _("Holiday List"), "fieldname": "holiday_list", "fieldtype": "Link", "options": "Holiday List", "width": 150, }, ] def get_data(filters: Filters) -> list[dict]: Employee = frappe.qb.DocType("Employee") Ledger = frappe.qb.DocType("Leave Ledger Entry") from_date, to_date = filters.get("from_date"), filters.get("to_date") query = ( frappe.qb.from_(Ledger) .inner_join(Employee) .on(Ledger.employee == Employee.name) .select( Ledger.name.as_("leave_ledger_entry"), Ledger.employee, Ledger.employee_name, Date(Ledger.creation).as_("date"), Ledger.from_date, Ledger.to_date, Ledger.leave_type, Ledger.transaction_type, Ledger.transaction_name, Ledger.leaves, Ledger.is_carry_forward, Ledger.is_expired, Ledger.is_lwp, Ledger.company, Ledger.holiday_list, ) .where( (Ledger.docstatus == 1) & (Ledger.from_date[from_date:to_date]) & (Ledger.to_date[from_date:to_date]) ) ) for field in ("employee", "leave_type", "company", "transaction_type", "transaction_name"): if filters.get(field): query = query.where(Ledger[field] == filters.get(field)) for field in ("department", "status"): if filters.get(field): query = query.where(Employee[field] == filters.get(field)) query = query.orderby(Ledger.employee, Ledger.leave_type, Ledger.from_date) result = query.run(as_dict=True) result = add_total_row(result, filters) return result def add_total_row(result: list[dict], filters: Filters) -> list[dict]: add_total_row = False leave_type = filters.get("leave_type") if filters.get("employee") and filters.get("leave_type"): add_total_row = True if not add_total_row: if not filters.get("employee"): # check if all rows have the same employee employees_from_result = list(set([row.employee for row in result])) if len(employees_from_result) != 1: return result # check if all rows have the same leave type leave_types_from_result = list(set([row.leave_type for row in result])) if len(leave_types_from_result) == 1: leave_type = leave_types_from_result[0] add_total_row = True if not add_total_row: return result total_row = frappe._dict({"employee": _("Total Leaves ({0})").format(leave_type)}) total_row["leaves"] = sum((row.get("leaves") or 0) for row in result) result.append(total_row) return result
2302_79757062/hrms
hrms/hr/report/leave_ledger/leave_ledger.py
Python
agpl-3.0
4,506
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.query_reports["Monthly Attendance Sheet"] = { filters: [ { fieldname: "month", label: __("Month"), fieldtype: "Select", reqd: 1, options: [ { value: 1, label: __("Jan") }, { value: 2, label: __("Feb") }, { value: 3, label: __("Mar") }, { value: 4, label: __("Apr") }, { value: 5, label: __("May") }, { value: 6, label: __("June") }, { value: 7, label: __("July") }, { value: 8, label: __("Aug") }, { value: 9, label: __("Sep") }, { value: 10, label: __("Oct") }, { value: 11, label: __("Nov") }, { value: 12, label: __("Dec") }, ], default: frappe.datetime.str_to_obj(frappe.datetime.get_today()).getMonth() + 1, }, { fieldname: "year", label: __("Year"), fieldtype: "Select", reqd: 1, }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", get_query: () => { var company = frappe.query_report.get_filter_value("company"); return { filters: { company: company, }, }; }, }, { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), reqd: 1, }, { fieldname: "group_by", label: __("Group By"), fieldtype: "Select", options: ["", "Branch", "Grade", "Department", "Designation"], }, { fieldname: "include_company_descendants", label: __("Include Company Descendants"), fieldtype: "Check", default: 1, }, { fieldname: "summarized_view", label: __("Summarized View"), fieldtype: "Check", default: 0, }, ], onload: function () { return frappe.call({ method: "hrms.hr.report.monthly_attendance_sheet.monthly_attendance_sheet.get_attendance_years", callback: function (r) { var year_filter = frappe.query_report.get_filter("year"); year_filter.df.options = r.message; year_filter.df.default = r.message.split("\n")[0]; year_filter.refresh(); year_filter.set_input(year_filter.df.default); }, }); }, formatter: function (value, row, column, data, default_formatter) { value = default_formatter(value, row, column, data); const summarized_view = frappe.query_report.get_filter_value("summarized_view"); const group_by = frappe.query_report.get_filter_value("group_by"); if (group_by && column.colIndex === 1) { value = "<strong>" + value + "</strong>"; } if (!summarized_view) { if ((group_by && column.colIndex > 3) || (!group_by && column.colIndex > 2)) { if (value == "P" || value == "WFH") value = "<span style='color:green'>" + value + "</span>"; else if (value == "A") value = "<span style='color:red'>" + value + "</span>"; else if (value == "HD") value = "<span style='color:orange'>" + value + "</span>"; else if (value == "L") value = "<span style='color:#318AD8'>" + value + "</span>"; } } return value; }, };
2302_79757062/hrms
hrms/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.js
JavaScript
agpl-3.0
3,060
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from calendar import monthrange from itertools import groupby import frappe from frappe import _ from frappe.query_builder.functions import Count, Extract, Sum from frappe.utils import cint, cstr, getdate from frappe.utils.nestedset import get_descendants_of Filters = frappe._dict status_map = { "Present": "P", "Absent": "A", "Half Day": "HD", "Work From Home": "WFH", "On Leave": "L", "Holiday": "H", "Weekly Off": "WO", } day_abbr = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] def execute(filters: Filters | None = None) -> tuple: filters = frappe._dict(filters or {}) if not (filters.month and filters.year): frappe.throw(_("Please select month and year.")) if filters.company: filters.companies = [filters.company] if filters.include_company_descendants: filters.companies.extend(get_descendants_of("Company", filters.company)) attendance_map = get_attendance_map(filters) if not attendance_map: frappe.msgprint(_("No attendance records found."), alert=True, indicator="orange") return [], [], None, None columns = get_columns(filters) data = get_data(filters, attendance_map) if not data: frappe.msgprint(_("No attendance records found for this criteria."), alert=True, indicator="orange") return columns, [], None, None message = get_message() if not filters.summarized_view else "" chart = get_chart_data(attendance_map, filters) return columns, data, message, chart def get_message() -> str: message = "" colors = ["green", "red", "orange", "green", "#318AD8", "", ""] count = 0 for status, abbr in status_map.items(): message += f""" <span style='border-left: 2px solid {colors[count]}; padding-right: 12px; padding-left: 5px; margin-right: 3px;'> {status} - {abbr} </span> """ count += 1 return message def get_columns(filters: Filters) -> list[dict]: columns = [] if filters.group_by: options_mapping = { "Branch": "Branch", "Grade": "Employee Grade", "Department": "Department", "Designation": "Designation", } options = options_mapping.get(filters.group_by) columns.append( { "label": _(filters.group_by), "fieldname": frappe.scrub(filters.group_by), "fieldtype": "Link", "options": options, "width": 120, } ) columns.extend( [ { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 135, }, {"label": _("Employee Name"), "fieldname": "employee_name", "fieldtype": "Data", "width": 120}, ] ) if filters.summarized_view: columns.extend( [ { "label": _("Total Present"), "fieldname": "total_present", "fieldtype": "Float", "width": 110, }, {"label": _("Total Leaves"), "fieldname": "total_leaves", "fieldtype": "Float", "width": 110}, {"label": _("Total Absent"), "fieldname": "total_absent", "fieldtype": "Float", "width": 110}, { "label": _("Total Holidays"), "fieldname": "total_holidays", "fieldtype": "Float", "width": 120, }, { "label": _("Unmarked Days"), "fieldname": "unmarked_days", "fieldtype": "Float", "width": 130, }, ] ) columns.extend(get_columns_for_leave_types()) columns.extend( [ { "label": _("Total Late Entries"), "fieldname": "total_late_entries", "fieldtype": "Float", "width": 140, }, { "label": _("Total Early Exits"), "fieldname": "total_early_exits", "fieldtype": "Float", "width": 140, }, ] ) else: columns.append({"label": _("Shift"), "fieldname": "shift", "fieldtype": "Data", "width": 120}) columns.extend(get_columns_for_days(filters)) return columns def get_columns_for_leave_types() -> list[dict]: leave_types = frappe.db.get_all("Leave Type", pluck="name") types = [] for entry in leave_types: types.append({"label": entry, "fieldname": frappe.scrub(entry), "fieldtype": "Float", "width": 120}) return types def get_columns_for_days(filters: Filters) -> list[dict]: total_days = get_total_days_in_month(filters) days = [] for day in range(1, total_days + 1): day = cstr(day) # forms the dates from selected year and month from filters date = f"{cstr(filters.year)}-{cstr(filters.month)}-{day}" # gets abbr from weekday number weekday = day_abbr[getdate(date).weekday()] # sets days as 1 Mon, 2 Tue, 3 Wed label = f"{day} {weekday}" days.append({"label": label, "fieldtype": "Data", "fieldname": day, "width": 65}) return days def get_total_days_in_month(filters: Filters) -> int: return monthrange(cint(filters.year), cint(filters.month))[1] def get_data(filters: Filters, attendance_map: dict) -> list[dict]: employee_details, group_by_param_values = get_employee_related_details(filters) holiday_map = get_holiday_map(filters) data = [] if filters.group_by: group_by_column = frappe.scrub(filters.group_by) for value in group_by_param_values: if not value: continue records = get_rows(employee_details[value], filters, holiday_map, attendance_map) if records: data.append({group_by_column: value}) data.extend(records) else: data = get_rows(employee_details, filters, holiday_map, attendance_map) return data def get_attendance_map(filters: Filters) -> dict: """Returns a dictionary of employee wise attendance map as per shifts for all the days of the month like { 'employee1': { 'Morning Shift': {1: 'Present', 2: 'Absent', ...} 'Evening Shift': {1: 'Absent', 2: 'Present', ...} }, 'employee2': { 'Afternoon Shift': {1: 'Present', 2: 'Absent', ...} 'Night Shift': {1: 'Absent', 2: 'Absent', ...} }, 'employee3': { None: {1: 'On Leave'} } } """ attendance_list = get_attendance_records(filters) attendance_map = {} leave_map = {} for d in attendance_list: if d.status == "On Leave": leave_map.setdefault(d.employee, {}).setdefault(d.shift, []).append(d.day_of_month) continue if d.shift is None: d.shift = "" attendance_map.setdefault(d.employee, {}).setdefault(d.shift, {}) attendance_map[d.employee][d.shift][d.day_of_month] = d.status # leave is applicable for the entire day so all shifts should show the leave entry for employee, leave_days in leave_map.items(): for assigned_shift, days in leave_days.items(): # no attendance records exist except leaves if employee not in attendance_map: attendance_map.setdefault(employee, {}).setdefault(assigned_shift, {}) for day in days: for shift in attendance_map[employee].keys(): attendance_map[employee][shift][day] = "On Leave" return attendance_map def get_attendance_records(filters: Filters) -> list[dict]: Attendance = frappe.qb.DocType("Attendance") query = ( frappe.qb.from_(Attendance) .select( Attendance.employee, Extract("day", Attendance.attendance_date).as_("day_of_month"), Attendance.status, Attendance.shift, ) .where( (Attendance.docstatus == 1) & (Attendance.company.isin(filters.companies)) & (Extract("month", Attendance.attendance_date) == filters.month) & (Extract("year", Attendance.attendance_date) == filters.year) ) ) if filters.employee: query = query.where(Attendance.employee == filters.employee) query = query.orderby(Attendance.employee, Attendance.attendance_date) return query.run(as_dict=1) def get_employee_related_details(filters: Filters) -> tuple[dict, list]: """Returns 1. nested dict for employee details 2. list of values for the group by filter """ Employee = frappe.qb.DocType("Employee") query = ( frappe.qb.from_(Employee) .select( Employee.name, Employee.employee_name, Employee.designation, Employee.grade, Employee.department, Employee.branch, Employee.company, Employee.holiday_list, ) .where(Employee.company.isin(filters.companies)) ) if filters.employee: query = query.where(Employee.name == filters.employee) group_by = filters.group_by if group_by: group_by = group_by.lower() query = query.orderby(group_by) employee_details = query.run(as_dict=True) group_by_param_values = [] emp_map = {} if group_by: group_key = lambda d: "" if d[group_by] is None else d[group_by] # noqa for parameter, employees in groupby(sorted(employee_details, key=group_key), key=group_key): group_by_param_values.append(parameter) emp_map.setdefault(parameter, frappe._dict()) for emp in employees: emp_map[parameter][emp.name] = emp else: for emp in employee_details: emp_map[emp.name] = emp return emp_map, group_by_param_values def get_holiday_map(filters: Filters) -> dict[str, list[dict]]: """ Returns a dict of holidays falling in the filter month and year with list name as key and list of holidays as values like { 'Holiday List 1': [ {'day_of_month': '0' , 'weekly_off': 1}, {'day_of_month': '1', 'weekly_off': 0} ], 'Holiday List 2': [ {'day_of_month': '0' , 'weekly_off': 1}, {'day_of_month': '1', 'weekly_off': 0} ] } """ # add default holiday list too holiday_lists = frappe.db.get_all("Holiday List", pluck="name") default_holiday_list = frappe.get_cached_value("Company", filters.company, "default_holiday_list") holiday_lists.append(default_holiday_list) holiday_map = frappe._dict() Holiday = frappe.qb.DocType("Holiday") for d in holiday_lists: if not d: continue holidays = ( frappe.qb.from_(Holiday) .select(Extract("day", Holiday.holiday_date).as_("day_of_month"), Holiday.weekly_off) .where( (Holiday.parent == d) & (Extract("month", Holiday.holiday_date) == filters.month) & (Extract("year", Holiday.holiday_date) == filters.year) ) ).run(as_dict=True) holiday_map.setdefault(d, holidays) return holiday_map def get_rows(employee_details: dict, filters: Filters, holiday_map: dict, attendance_map: dict) -> list[dict]: records = [] default_holiday_list = frappe.get_cached_value("Company", filters.company, "default_holiday_list") for employee, details in employee_details.items(): emp_holiday_list = details.holiday_list or default_holiday_list holidays = holiday_map.get(emp_holiday_list) if filters.summarized_view: attendance = get_attendance_status_for_summarized_view(employee, filters, holidays) if not attendance: continue leave_summary = get_leave_summary(employee, filters) entry_exits_summary = get_entry_exits_summary(employee, filters) row = {"employee": employee, "employee_name": details.employee_name} set_defaults_for_summarized_view(filters, row) row.update(attendance) row.update(leave_summary) row.update(entry_exits_summary) records.append(row) else: employee_attendance = attendance_map.get(employee) if not employee_attendance: continue attendance_for_employee = get_attendance_status_for_detailed_view( employee, filters, employee_attendance, holidays ) # set employee details in the first row attendance_for_employee[0].update({"employee": employee, "employee_name": details.employee_name}) records.extend(attendance_for_employee) return records def set_defaults_for_summarized_view(filters, row): for entry in get_columns(filters): if entry.get("fieldtype") == "Float": row[entry.get("fieldname")] = 0.0 def get_attendance_status_for_summarized_view(employee: str, filters: Filters, holidays: list) -> dict: """Returns dict of attendance status for employee like {'total_present': 1.5, 'total_leaves': 0.5, 'total_absent': 13.5, 'total_holidays': 8, 'unmarked_days': 5} """ summary, attendance_days = get_attendance_summary_and_days(employee, filters) if not any(summary.values()): return {} total_days = get_total_days_in_month(filters) total_holidays = total_unmarked_days = 0 for day in range(1, total_days + 1): if day in attendance_days: continue status = get_holiday_status(day, holidays) if status in ["Weekly Off", "Holiday"]: total_holidays += 1 elif not status: total_unmarked_days += 1 return { "total_present": summary.total_present + summary.total_half_days, "total_leaves": summary.total_leaves + summary.total_half_days, "total_absent": summary.total_absent, "total_holidays": total_holidays, "unmarked_days": total_unmarked_days, } def get_attendance_summary_and_days(employee: str, filters: Filters) -> tuple[dict, list]: Attendance = frappe.qb.DocType("Attendance") present_case = ( frappe.qb.terms.Case() .when(((Attendance.status == "Present") | (Attendance.status == "Work From Home")), 1) .else_(0) ) sum_present = Sum(present_case).as_("total_present") absent_case = frappe.qb.terms.Case().when(Attendance.status == "Absent", 1).else_(0) sum_absent = Sum(absent_case).as_("total_absent") leave_case = frappe.qb.terms.Case().when(Attendance.status == "On Leave", 1).else_(0) sum_leave = Sum(leave_case).as_("total_leaves") half_day_case = frappe.qb.terms.Case().when(Attendance.status == "Half Day", 0.5).else_(0) sum_half_day = Sum(half_day_case).as_("total_half_days") summary = ( frappe.qb.from_(Attendance) .select( sum_present, sum_absent, sum_leave, sum_half_day, ) .where( (Attendance.docstatus == 1) & (Attendance.employee == employee) & (Attendance.company.isin(filters.companies)) & (Extract("month", Attendance.attendance_date) == filters.month) & (Extract("year", Attendance.attendance_date) == filters.year) ) ).run(as_dict=True) days = ( frappe.qb.from_(Attendance) .select(Extract("day", Attendance.attendance_date).as_("day_of_month")) .distinct() .where( (Attendance.docstatus == 1) & (Attendance.employee == employee) & (Attendance.company.isin(filters.companies)) & (Extract("month", Attendance.attendance_date) == filters.month) & (Extract("year", Attendance.attendance_date) == filters.year) ) ).run(pluck=True) return summary[0], days def get_attendance_status_for_detailed_view( employee: str, filters: Filters, employee_attendance: dict, holidays: list ) -> list[dict]: """Returns list of shift-wise attendance status for employee [ {'shift': 'Morning Shift', 1: 'A', 2: 'P', 3: 'A'....}, {'shift': 'Evening Shift', 1: 'P', 2: 'A', 3: 'P'....} ] """ total_days = get_total_days_in_month(filters) attendance_values = [] for shift, status_dict in employee_attendance.items(): row = {"shift": shift} for day in range(1, total_days + 1): status = status_dict.get(day) if status is None and holidays: status = get_holiday_status(day, holidays) abbr = status_map.get(status, "") row[cstr(day)] = abbr attendance_values.append(row) return attendance_values def get_holiday_status(day: int, holidays: list) -> str: status = None if holidays: for holiday in holidays: if day == holiday.get("day_of_month"): if holiday.get("weekly_off"): status = "Weekly Off" else: status = "Holiday" break return status def get_leave_summary(employee: str, filters: Filters) -> dict[str, float]: """Returns a dict of leave type and corresponding leaves taken by employee like: {'leave_without_pay': 1.0, 'sick_leave': 2.0} """ Attendance = frappe.qb.DocType("Attendance") day_case = frappe.qb.terms.Case().when(Attendance.status == "Half Day", 0.5).else_(1) sum_leave_days = Sum(day_case).as_("leave_days") leave_details = ( frappe.qb.from_(Attendance) .select(Attendance.leave_type, sum_leave_days) .where( (Attendance.employee == employee) & (Attendance.docstatus == 1) & (Attendance.company.isin(filters.companies)) & ((Attendance.leave_type.isnotnull()) | (Attendance.leave_type != "")) & (Extract("month", Attendance.attendance_date) == filters.month) & (Extract("year", Attendance.attendance_date) == filters.year) ) .groupby(Attendance.leave_type) ).run(as_dict=True) leaves = {} for d in leave_details: leave_type = frappe.scrub(d.leave_type) leaves[leave_type] = d.leave_days return leaves def get_entry_exits_summary(employee: str, filters: Filters) -> dict[str, float]: """Returns total late entries and total early exits for employee like: {'total_late_entries': 5, 'total_early_exits': 2} """ Attendance = frappe.qb.DocType("Attendance") late_entry_case = frappe.qb.terms.Case().when(Attendance.late_entry == "1", "1") count_late_entries = Count(late_entry_case).as_("total_late_entries") early_exit_case = frappe.qb.terms.Case().when(Attendance.early_exit == "1", "1") count_early_exits = Count(early_exit_case).as_("total_early_exits") entry_exits = ( frappe.qb.from_(Attendance) .select(count_late_entries, count_early_exits) .where( (Attendance.docstatus == 1) & (Attendance.employee == employee) & (Attendance.company.isin(filters.companies)) & (Extract("month", Attendance.attendance_date) == filters.month) & (Extract("year", Attendance.attendance_date) == filters.year) ) ).run(as_dict=True) return entry_exits[0] @frappe.whitelist() def get_attendance_years() -> str: """Returns all the years for which attendance records exist""" Attendance = frappe.qb.DocType("Attendance") year_list = ( frappe.qb.from_(Attendance).select(Extract("year", Attendance.attendance_date).as_("year")).distinct() ).run(as_dict=True) if year_list: year_list.sort(key=lambda d: d.year, reverse=True) else: year_list = [frappe._dict({"year": getdate().year})] return "\n".join(cstr(entry.year) for entry in year_list) def get_chart_data(attendance_map: dict, filters: Filters) -> dict: days = get_columns_for_days(filters) labels = [] absent = [] present = [] leave = [] for day in days: labels.append(day["label"]) total_absent_on_day = total_leaves_on_day = total_present_on_day = 0 for __, attendance_dict in attendance_map.items(): for __, attendance in attendance_dict.items(): attendance_on_day = attendance.get(cint(day["fieldname"])) if attendance_on_day == "On Leave": # leave should be counted only once for the entire day total_leaves_on_day += 1 break elif attendance_on_day == "Absent": total_absent_on_day += 1 elif attendance_on_day in ["Present", "Work From Home"]: total_present_on_day += 1 elif attendance_on_day == "Half Day": total_present_on_day += 0.5 total_leaves_on_day += 0.5 absent.append(total_absent_on_day) present.append(total_present_on_day) leave.append(total_leaves_on_day) return { "data": { "labels": labels, "datasets": [ {"name": "Absent", "values": absent}, {"name": "Present", "values": present}, {"name": "Leave", "values": leave}, ], }, "type": "line", "colors": ["red", "green", "blue"], }
2302_79757062/hrms
hrms/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
Python
agpl-3.0
18,920
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Project Profitability"] = { filters: [ { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), reqd: 1, }, { fieldname: "start_date", label: __("Start Date"), fieldtype: "Date", reqd: 1, default: frappe.datetime.add_months(frappe.datetime.get_today(), -1), }, { fieldname: "end_date", label: __("End Date"), fieldtype: "Date", reqd: 1, default: frappe.datetime.now_date(), }, { fieldname: "customer", label: __("Customer"), fieldtype: "Link", options: "Customer", }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, { fieldname: "project", label: __("Project"), fieldtype: "Link", options: "Project", }, ], };
2302_79757062/hrms
hrms/hr/report/project_profitability/project_profitability.js
JavaScript
agpl-3.0
1,010
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.utils import cint, flt def execute(filters=None): data = get_data(filters) columns = get_columns() charts = get_chart_data(data) return columns, data, None, charts def get_data(filters): data = get_rows(filters) data = calculate_cost_and_profit(data) return data def get_rows(filters): Timesheet = frappe.qb.DocType("Timesheet") SalarySlip = frappe.qb.DocType("Salary Slip") SalesInvoice = frappe.qb.DocType("Sales Invoice") SalesInvoiceTimesheet = frappe.qb.DocType("Sales Invoice Timesheet") SalarySlipTimesheet = frappe.qb.DocType("Salary Slip Timesheet") query = ( frappe.qb.from_(SalarySlipTimesheet) .inner_join(Timesheet) .on(SalarySlipTimesheet.time_sheet == Timesheet.name) .inner_join(SalarySlip) .on(SalarySlipTimesheet.parent == SalarySlip.name) .inner_join(SalesInvoiceTimesheet) .on(SalesInvoiceTimesheet.time_sheet == Timesheet.name) .inner_join(SalesInvoice) .on(SalesInvoiceTimesheet.parent == SalesInvoice.name) .select( SalesInvoice.customer_name, SalesInvoice.base_grand_total, SalesInvoice.name.as_("voucher_no"), Timesheet.employee, Timesheet.title.as_("employee_name"), Timesheet.parent_project.as_("project"), Timesheet.start_date, Timesheet.end_date, Timesheet.total_billed_hours, Timesheet.name.as_("timesheet"), SalarySlip.base_gross_pay, SalarySlip.total_working_days, Timesheet.total_billed_hours, ) .distinct() .where((SalesInvoice.docstatus == 1) & (SalarySlip.docstatus == 1)) ) if filters.get("company"): query = query.where(Timesheet.company == filters.get("company")) if filters.get("start_date"): query = query.where(Timesheet.start_date >= filters.get("start_date")) if filters.get("end_date"): query = query.where(Timesheet.end_date <= filters.get("end_date")) if filters.get("customer"): query = query.where(SalesInvoice.customer == filters.get("customer")) if filters.get("employee"): query = query.where(Timesheet.employee == filters.get("employee")) if filters.get("project"): query = query.where(Timesheet.parent_project == filters.get("project")) return query.run(as_dict=True) def calculate_cost_and_profit(data): standard_working_hours = get_standard_working_hours() precision = cint(frappe.db.get_default("float_precision")) or 2 for row in data: row.utilization = flt( flt(row.total_billed_hours) / (flt(row.total_working_days) * flt(standard_working_hours)), precision, ) row.fractional_cost = flt(flt(row.base_gross_pay) * flt(row.utilization), precision) row.profit = flt( flt(row.base_grand_total) - flt(row.base_gross_pay) * flt(row.utilization), precision ) return data def get_standard_working_hours() -> float | None: standard_working_hours = frappe.db.get_single_value("HR Settings", "standard_working_hours") if not standard_working_hours: frappe.throw( _("The metrics for this report are calculated based on the {0}. Please set {0} in {1}.").format( frappe.bold(_("Standard Working Hours")), frappe.utils.get_link_to_form("HR Settings", "HR Settings"), ) ) return standard_working_hours def get_chart_data(data): if not data: return None labels = [] utilization = [] for entry in data: labels.append(f"{entry.get('employee_name')} - {entry.get('end_date')}") utilization.append(entry.get("utilization")) charts = { "data": {"labels": labels, "datasets": [{"name": "Utilization", "values": utilization}]}, "type": "bar", "colors": ["#84BDD5"], } return charts def get_columns(): return [ { "fieldname": "customer_name", "label": _("Customer"), "fieldtype": "Link", "options": "Customer", "width": 150, }, { "fieldname": "employee", "label": _("Employee"), "fieldtype": "Link", "options": "Employee", "width": 130, }, {"fieldname": "employee_name", "label": _("Employee Name"), "fieldtype": "Data", "width": 120}, { "fieldname": "voucher_no", "label": _("Sales Invoice"), "fieldtype": "Link", "options": "Sales Invoice", "width": 120, }, { "fieldname": "timesheet", "label": _("Timesheet"), "fieldtype": "Link", "options": "Timesheet", "width": 120, }, { "fieldname": "project", "label": _("Project"), "fieldtype": "Link", "options": "Project", "width": 100, }, { "fieldname": "base_grand_total", "label": _("Bill Amount"), "fieldtype": "Currency", "options": "currency", "width": 100, }, { "fieldname": "base_gross_pay", "label": _("Cost"), "fieldtype": "Currency", "options": "currency", "width": 100, }, { "fieldname": "profit", "label": _("Profit"), "fieldtype": "Currency", "options": "currency", "width": 100, }, {"fieldname": "utilization", "label": _("Utilization"), "fieldtype": "Percentage", "width": 100}, { "fieldname": "fractional_cost", "label": _("Fractional Cost"), "fieldtype": "Int", "width": 120, }, { "fieldname": "total_billed_hours", "label": _("Total Billed Hours"), "fieldtype": "Int", "width": 150, }, {"fieldname": "start_date", "label": _("Start Date"), "fieldtype": "Date", "width": 100}, {"fieldname": "end_date", "label": _("End Date"), "fieldtype": "Date", "width": 100}, { "label": _("Currency"), "fieldname": "currency", "fieldtype": "Link", "options": "Currency", "width": 80, }, ]
2302_79757062/hrms
hrms/hr/report/project_profitability/project_profitability.py
Python
agpl-3.0
5,543
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Recruitment Analytics"] = { filters: [ { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), reqd: 1, }, { fieldname: "on_date", label: __("On Date"), fieldtype: "Date", default: frappe.datetime.now_date(), reqd: 1, }, ], };
2302_79757062/hrms
hrms/hr/report/recruitment_analytics/recruitment_analytics.js
JavaScript
agpl-3.0
518
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} filters = frappe._dict(filters) columns = get_columns() data = get_data(filters) return columns, data def get_columns(): return [ { "label": _("Staffing Plan"), "fieldtype": "Link", "fieldname": "staffing_plan", "options": "Staffing Plan", "width": 150, }, { "label": _("Job Opening"), "fieldtype": "Link", "fieldname": "job_opening", "options": "Job Opening", "width": 105, }, { "label": _("Job Applicant"), "fieldtype": "Link", "fieldname": "job_applicant", "options": "Job Applicant", "width": 150, }, {"label": _("Applicant name"), "fieldtype": "data", "fieldname": "applicant_name", "width": 130}, { "label": _("Application Status"), "fieldtype": "Data", "fieldname": "application_status", "width": 150, }, { "label": _("Job Offer"), "fieldtype": "Link", "fieldname": "job_offer", "options": "job Offer", "width": 150, }, {"label": _("Designation"), "fieldtype": "Data", "fieldname": "designation", "width": 100}, {"label": _("Offer Date"), "fieldtype": "date", "fieldname": "offer_date", "width": 100}, { "label": _("Job Offer status"), "fieldtype": "Data", "fieldname": "job_offer_status", "width": 150, }, ] def get_data(filters): data = [] staffing_plan_details = get_staffing_plan(filters) staffing_plan_list = list(set([details["name"] for details in staffing_plan_details])) sp_jo_map, jo_list = get_job_opening(staffing_plan_list) jo_ja_map, ja_list = get_job_applicant(jo_list) ja_joff_map = get_job_offer(ja_list) for sp in sp_jo_map.keys(): parent_row = get_parent_row(sp_jo_map, sp, jo_ja_map, ja_joff_map) data += parent_row return data def get_parent_row(sp_jo_map, sp, jo_ja_map, ja_joff_map): data = [] if sp in sp_jo_map.keys(): for jo in sp_jo_map[sp]: row = { "staffing_plan": sp, "job_opening": jo["name"], } data.append(row) child_row = get_child_row(jo["name"], jo_ja_map, ja_joff_map) data += child_row return data def get_child_row(jo, jo_ja_map, ja_joff_map): data = [] if jo in jo_ja_map.keys(): for ja in jo_ja_map[jo]: row = { "indent": 1, "job_applicant": ja.name, "applicant_name": ja.applicant_name, "application_status": ja.status, } if ja.name in ja_joff_map.keys(): jo_detail = ja_joff_map[ja.name][0] row["job_offer"] = jo_detail.name row["job_offer_status"] = jo_detail.status row["offer_date"] = jo_detail.offer_date.strftime("%d-%m-%Y") row["designation"] = jo_detail.designation data.append(row) return data def get_staffing_plan(filters): # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql staffing_plan = frappe.db.sql( f""" select sp.name, sp.department, spd.designation, spd.vacancies, spd.current_count, spd.parent, sp.to_date from `tabStaffing Plan Detail` spd , `tabStaffing Plan` sp where spd.parent = sp.name And sp.to_date > '{filters.on_date}' """, as_dict=1, ) return staffing_plan def get_job_opening(sp_list): job_openings = frappe.get_all( "Job Opening", filters=[["staffing_plan", "IN", sp_list]], fields=["name", "staffing_plan"] ) sp_jo_map = {} jo_list = [] for openings in job_openings: if openings.staffing_plan not in sp_jo_map.keys(): sp_jo_map[openings.staffing_plan] = [openings] else: sp_jo_map[openings.staffing_plan].append(openings) jo_list.append(openings.name) return sp_jo_map, jo_list def get_job_applicant(jo_list): jo_ja_map = {} ja_list = [] applicants = frappe.get_all( "Job Applicant", filters=[["job_title", "IN", jo_list]], fields=["name", "job_title", "applicant_name", "status"], ) for applicant in applicants: if applicant.job_title not in jo_ja_map.keys(): jo_ja_map[applicant.job_title] = [applicant] else: jo_ja_map[applicant.job_title].append(applicant) ja_list.append(applicant.name) return jo_ja_map, ja_list def get_job_offer(ja_list): ja_joff_map = {} offers = frappe.get_all( "Job Offer", filters=[["job_applicant", "IN", ja_list]], fields=["name", "job_applicant", "status", "offer_date", "designation"], ) for offer in offers: if offer.job_applicant not in ja_joff_map.keys(): ja_joff_map[offer.job_applicant] = [offer] else: ja_joff_map[offer.job_applicant].append(offer) return ja_joff_map
2302_79757062/hrms
hrms/hr/report/recruitment_analytics/recruitment_analytics.py
Python
agpl-3.0
4,553
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.query_reports["Shift Attendance"] = { filters: [ { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", reqd: 1, default: frappe.datetime.month_start(), }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", reqd: 1, default: frappe.datetime.month_end(), }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, { fieldname: "shift", label: __("Shift Type"), fieldtype: "Link", options: "Shift Type", }, { fieldname: "department", label: __("Department"), fieldtype: "Link", options: "Department", }, { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", reqd: 1, default: frappe.defaults.get_user_default("Company"), }, { fieldname: "late_entry", label: __("Late Entry"), fieldtype: "Check", }, { fieldname: "early_exit", label: __("Early Exit"), fieldtype: "Check", }, { fieldname: "consider_grace_period", label: __("Consider Grace Period"), fieldtype: "Check", default: 1, }, ], formatter: (value, row, column, data, default_formatter) => { value = default_formatter(value, row, column, data); if ( (column.fieldname === "in_time" && data.late_entry) || (column.fieldname === "out_time" && data.early_exit) ) { value = `<span style='color:red!important'>${value}</span>`; } return value; }, };
2302_79757062/hrms
hrms/hr/report/shift_attendance/shift_attendance.js
JavaScript
agpl-3.0
1,595
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from datetime import timedelta import frappe from frappe import _ from frappe.utils import cint, flt, format_datetime, format_duration def execute(filters=None): columns = get_columns() data = get_data(filters) chart = get_chart_data(data) report_summary = get_report_summary(data) return columns, data, None, chart, report_summary def get_columns(): return [ { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 220, }, { "fieldname": "employee_name", "fieldtype": "Data", "label": _("Employee Name"), "width": 0, "hidden": 1, }, { "label": _("Shift"), "fieldname": "shift", "fieldtype": "Link", "options": "Shift Type", "width": 120, }, { "label": _("Attendance Date"), "fieldname": "attendance_date", "fieldtype": "Date", "width": 130, }, { "label": _("Status"), "fieldname": "status", "fieldtype": "Data", "width": 80, }, { "label": _("Shift Start Time"), "fieldname": "shift_start", "fieldtype": "Data", "width": 125, }, { "label": _("Shift End Time"), "fieldname": "shift_end", "fieldtype": "Data", "width": 125, }, { "label": _("In Time"), "fieldname": "in_time", "fieldtype": "Data", "width": 120, }, { "label": _("Out Time"), "fieldname": "out_time", "fieldtype": "Data", "width": 120, }, { "label": _("Total Working Hours"), "fieldname": "working_hours", "fieldtype": "Data", "width": 100, }, { "label": _("Late Entry By"), "fieldname": "late_entry_hrs", "fieldtype": "Data", "width": 120, }, { "label": _("Early Exit By"), "fieldname": "early_exit_hrs", "fieldtype": "Data", "width": 120, }, { "label": _("Department"), "fieldname": "department", "fieldtype": "Link", "options": "Department", "width": 150, }, { "label": _("Company"), "fieldname": "company", "fieldtype": "Link", "options": "Company", "width": 150, }, { "label": _("Shift Actual Start Time"), "fieldname": "shift_actual_start", "fieldtype": "Data", "width": 165, }, { "label": _("Shift Actual End Time"), "fieldname": "shift_actual_end", "fieldtype": "Data", "width": 165, }, { "label": _("Attendance ID"), "fieldname": "name", "fieldtype": "Link", "options": "Attendance", "width": 150, }, ] def get_data(filters): query = get_query(filters) data = query.run(as_dict=True) data = update_data(data, filters) return data def get_report_summary(data): if not data: return None present_records = half_day_records = absent_records = late_entries = early_exits = 0 for entry in data: if entry.status == "Present": present_records += 1 elif entry.status == "Half Day": half_day_records += 1 else: absent_records += 1 if entry.late_entry: late_entries += 1 if entry.early_exit: early_exits += 1 return [ { "value": present_records, "indicator": "Green", "label": _("Present Records"), "datatype": "Int", }, { "value": half_day_records, "indicator": "Blue", "label": _("Half Day Records"), "datatype": "Int", }, { "value": absent_records, "indicator": "Red", "label": _("Absent Records"), "datatype": "Int", }, { "value": late_entries, "indicator": "Red", "label": _("Late Entries"), "datatype": "Int", }, { "value": early_exits, "indicator": "Red", "label": _("Early Exits"), "datatype": "Int", }, ] def get_chart_data(data): if not data: return None total_shift_records = {} for entry in data: total_shift_records.setdefault(entry.shift, 0) total_shift_records[entry.shift] += 1 labels = [_(d) for d in list(total_shift_records)] chart = { "data": { "labels": labels, "datasets": [{"name": _("Shift"), "values": list(total_shift_records.values())}], }, "type": "percentage", } return chart def get_query(filters): attendance = frappe.qb.DocType("Attendance") checkin = frappe.qb.DocType("Employee Checkin") shift_type = frappe.qb.DocType("Shift Type") query = ( frappe.qb.from_(attendance) .inner_join(checkin) .on(checkin.attendance == attendance.name) .inner_join(shift_type) .on(attendance.shift == shift_type.name) .select( attendance.name, attendance.employee, attendance.employee_name, attendance.shift, attendance.attendance_date, attendance.status, attendance.in_time, attendance.out_time, attendance.working_hours, attendance.late_entry, attendance.early_exit, attendance.department, attendance.company, checkin.shift_start, checkin.shift_end, checkin.shift_actual_start, checkin.shift_actual_end, shift_type.enable_late_entry_marking, shift_type.late_entry_grace_period, shift_type.enable_early_exit_marking, shift_type.early_exit_grace_period, ) .where(attendance.docstatus == 1) .groupby(attendance.name) ) for filter in filters: if filter == "from_date": query = query.where(attendance.attendance_date >= filters.from_date) elif filter == "to_date": query = query.where(attendance.attendance_date <= filters.to_date) elif filter == "consider_grace_period": continue elif filter == "late_entry" and not filters.consider_grace_period: query = query.where(attendance.in_time > checkin.shift_start) elif filter == "early_exit" and not filters.consider_grace_period: query = query.where(attendance.out_time < checkin.shift_end) else: query = query.where(attendance[filter] == filters[filter]) return query def update_data(data, filters): for d in data: update_late_entry(d, filters.consider_grace_period) update_early_exit(d, filters.consider_grace_period) d.working_hours = format_float_precision(d.working_hours) d.in_time, d.out_time = format_in_out_time(d.in_time, d.out_time, d.attendance_date) d.shift_start, d.shift_end = convert_datetime_to_time_for_same_date(d.shift_start, d.shift_end) d.shift_actual_start, d.shift_actual_end = convert_datetime_to_time_for_same_date( d.shift_actual_start, d.shift_actual_end ) return data def format_float_precision(value): precision = cint(frappe.db.get_default("float_precision")) or 2 return flt(value, precision) def format_in_out_time(in_time, out_time, attendance_date): if in_time and not out_time and in_time.date() == attendance_date: in_time = in_time.time() elif out_time and not in_time and out_time.date() == attendance_date: out_time = out_time.time() else: in_time, out_time = convert_datetime_to_time_for_same_date(in_time, out_time) return in_time, out_time def convert_datetime_to_time_for_same_date(start, end): if start and end and start.date() == end.date(): start = start.time() end = end.time() else: start = format_datetime(start) end = format_datetime(end) return start, end def update_late_entry(entry, consider_grace_period): if consider_grace_period: if entry.late_entry: entry_grace_period = entry.late_entry_grace_period if entry.enable_late_entry_marking else 0 start_time = entry.shift_start + timedelta(minutes=entry_grace_period) entry.late_entry_hrs = entry.in_time - start_time elif entry.in_time and entry.in_time > entry.shift_start: entry.late_entry = 1 entry.late_entry_hrs = entry.in_time - entry.shift_start if entry.late_entry_hrs: entry.late_entry_hrs = format_duration(entry.late_entry_hrs.total_seconds()) def update_early_exit(entry, consider_grace_period): if consider_grace_period: if entry.early_exit: exit_grace_period = entry.early_exit_grace_period if entry.enable_early_exit_marking else 0 end_time = entry.shift_end - timedelta(minutes=exit_grace_period) entry.early_exit_hrs = end_time - entry.out_time elif entry.out_time and entry.out_time < entry.shift_end: entry.early_exit = 1 entry.early_exit_hrs = entry.shift_end - entry.out_time if entry.early_exit_hrs: entry.early_exit_hrs = format_duration(entry.early_exit_hrs.total_seconds())
2302_79757062/hrms
hrms/hr/report/shift_attendance/shift_attendance.py
Python
agpl-3.0
8,165
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.query_reports["Unpaid Expense Claim"] = { filters: [ { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, ], };
2302_79757062/hrms
hrms/hr/report/unpaid_expense_claim/unpaid_expense_claim.js
JavaScript
agpl-3.0
297
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ def execute(filters=None): columns, data = [], [] columns = get_columns() data = get_unclaimed_expese_claims(filters) return columns, data def get_columns(): return [ _("Employee") + ":Link/Employee:120", _("Employee Name") + "::120", _("Expense Claim") + ":Link/Expense Claim:120", _("Sanctioned Amount") + ":Currency:120", _("Paid Amount") + ":Currency:120", _("Outstanding Amount") + ":Currency:150", ] def get_unclaimed_expese_claims(filters): cond = "1=1" if filters.get("employee"): cond = "ec.employee = %(employee)s" # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql return frappe.db.sql( f""" select ec.employee, ec.employee_name, ec.name, ec.total_sanctioned_amount, ec.total_amount_reimbursed, sum(gle.credit_in_account_currency - gle.debit_in_account_currency) as outstanding_amt from `tabExpense Claim` ec, `tabGL Entry` gle where gle.against_voucher_type = "Expense Claim" and gle.against_voucher = ec.name and gle.party is not null and ec.docstatus = 1 and ec.is_paid = 0 and {cond} group by ec.name having outstanding_amt > 0 """, filters, as_list=1, )
2302_79757062/hrms
hrms/hr/report/unpaid_expense_claim/unpaid_expense_claim.py
Python
agpl-3.0
1,300
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.query_reports["Vehicle Expenses"] = { filters: [ { fieldname: "filter_based_on", label: __("Filter Based On"), fieldtype: "Select", options: ["Fiscal Year", "Date Range"], default: ["Fiscal Year"], reqd: 1, }, { fieldname: "fiscal_year", label: __("Fiscal Year"), fieldtype: "Link", options: "Fiscal Year", default: frappe.defaults.get_user_default("fiscal_year"), depends_on: "eval: doc.filter_based_on == 'Fiscal Year'", reqd: 1, }, { fieldname: "from_date", label: __("From Date"), fieldtype: "Date", reqd: 1, depends_on: "eval: doc.filter_based_on == 'Date Range'", default: frappe.datetime.add_months(frappe.datetime.nowdate(), -12), }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", reqd: 1, depends_on: "eval: doc.filter_based_on == 'Date Range'", default: frappe.datetime.nowdate(), }, { fieldname: "vehicle", label: __("Vehicle"), fieldtype: "Link", options: "Vehicle", }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", }, ], };
2302_79757062/hrms
hrms/hr/report/vehicle_expenses/vehicle_expenses.js
JavaScript
agpl-3.0
1,250
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.utils import flt from erpnext.accounts.report.financial_statements import get_period_list def execute(filters=None): filters = frappe._dict(filters or {}) columns = get_columns() data = get_vehicle_log_data(filters) chart = get_chart_data(data, filters) return columns, data, None, chart def get_columns(): return [ { "fieldname": "vehicle", "fieldtype": "Link", "label": _("Vehicle"), "options": "Vehicle", "width": 150, }, {"fieldname": "make", "fieldtype": "Data", "label": _("Make"), "width": 100}, {"fieldname": "model", "fieldtype": "Data", "label": _("Model"), "width": 80}, {"fieldname": "location", "fieldtype": "Data", "label": _("Location"), "width": 100}, { "fieldname": "log_name", "fieldtype": "Link", "label": _("Vehicle Log"), "options": "Vehicle Log", "width": 100, }, {"fieldname": "odometer", "fieldtype": "Int", "label": _("Odometer Value"), "width": 120}, {"fieldname": "date", "fieldtype": "Date", "label": _("Date"), "width": 100}, {"fieldname": "fuel_qty", "fieldtype": "Float", "label": _("Fuel Qty"), "width": 80}, {"fieldname": "fuel_price", "fieldtype": "Float", "label": _("Fuel Price"), "width": 100}, {"fieldname": "fuel_expense", "fieldtype": "Currency", "label": _("Fuel Expense"), "width": 150}, { "fieldname": "service_expense", "fieldtype": "Currency", "label": _("Service Expense"), "width": 150, }, { "fieldname": "employee", "fieldtype": "Link", "label": _("Employee"), "options": "Employee", "width": 150, }, ] def get_vehicle_log_data(filters): start_date, end_date = get_period_dates(filters) conditions, values = get_conditions(filters) # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql data = frappe.db.sql( f""" SELECT vhcl.license_plate as vehicle, vhcl.make, vhcl.model, vhcl.location, log.name as log_name, log.odometer, log.date, log.employee, log.fuel_qty, log.price as fuel_price, log.fuel_qty * log.price as fuel_expense FROM `tabVehicle` vhcl,`tabVehicle Log` log WHERE vhcl.license_plate = log.license_plate and log.docstatus = 1 and date between %(start_date)s and %(end_date)s {conditions} ORDER BY date""", values, as_dict=1, ) for row in data: row["service_expense"] = get_service_expense(row.log_name) return data def get_conditions(filters): conditions = "" start_date, end_date = get_period_dates(filters) values = {"start_date": start_date, "end_date": end_date} if filters.employee: conditions += " and log.employee = %(employee)s" values["employee"] = filters.employee if filters.vehicle: conditions += " and vhcl.license_plate = %(vehicle)s" values["vehicle"] = filters.vehicle return conditions, values def get_period_dates(filters): if filters.filter_based_on == "Fiscal Year" and filters.fiscal_year: fy = frappe.db.get_value( "Fiscal Year", filters.fiscal_year, ["year_start_date", "year_end_date"], as_dict=True ) return fy.year_start_date, fy.year_end_date else: return filters.from_date, filters.to_date def get_service_expense(logname): expense_amount = frappe.db.sql( """ SELECT sum(expense_amount) FROM `tabVehicle Log` log, `tabVehicle Service` service WHERE service.parent=log.name and log.name=%s """, logname, ) return flt(expense_amount[0][0]) if expense_amount else 0.0 def get_chart_data(data, filters): period_list = get_period_list( filters.fiscal_year, filters.fiscal_year, filters.from_date, filters.to_date, filters.filter_based_on, "Monthly", ) fuel_data, service_data = [], [] for period in period_list: total_fuel_exp = 0 total_service_exp = 0 for row in data: if row.date <= period.to_date and row.date >= period.from_date: total_fuel_exp += flt(row.fuel_expense) total_service_exp += flt(row.service_expense) fuel_data.append([period.key, total_fuel_exp]) service_data.append([period.key, total_service_exp]) labels = [period.label for period in period_list] fuel_exp_data = [row[1] for row in fuel_data] service_exp_data = [row[1] for row in service_data] datasets = [] if fuel_exp_data: datasets.append({"name": _("Fuel Expenses"), "values": fuel_exp_data}) if service_exp_data: datasets.append({"name": _("Service Expenses"), "values": service_exp_data}) chart = { "data": {"labels": labels, "datasets": datasets}, "type": "line", "fieldtype": "Currency", } return chart
2302_79757062/hrms
hrms/hr/report/vehicle_expenses/vehicle_expenses.py
Python
agpl-3.0
4,630
# 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 _, qb from frappe.model.document import Document from frappe.query_builder import Criterion from frappe.query_builder.custom import ConstantColumn from frappe.utils import ( add_days, comma_and, cstr, flt, format_datetime, formatdate, get_datetime, get_first_day, get_last_day, get_link_to_form, get_number_format_info, getdate, nowdate, ) import erpnext from erpnext import get_company_currency from erpnext.setup.doctype.employee.employee import ( InactiveEmployeeStatusError, get_holiday_list_for_employee, ) from hrms.hr.doctype.leave_policy_assignment.leave_policy_assignment import ( calculate_pro_rated_leaves, ) DateTimeLikeObject = str | datetime.date | datetime.datetime class DuplicateDeclarationError(frappe.ValidationError): pass def set_employee_name(doc): if doc.employee and not doc.employee_name: doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name") def update_employee_work_history(employee, details, date=None, cancel=False): if not details: return employee if not employee.internal_work_history and not cancel: employee.append( "internal_work_history", { "branch": employee.branch, "designation": employee.designation, "department": employee.department, "from_date": employee.date_of_joining, }, ) internal_work_history = {} for item in details: field = frappe.get_meta("Employee").get_field(item.fieldname) if not field: continue new_value = item.new if not cancel else item.current new_value = get_formatted_value(new_value, field.fieldtype) setattr(employee, item.fieldname, new_value) if item.fieldname in ["department", "designation", "branch"]: internal_work_history[item.fieldname] = item.new if internal_work_history and not cancel: internal_work_history["from_date"] = date employee.append("internal_work_history", internal_work_history) if cancel: delete_employee_work_history(details, employee, date) update_to_date_in_work_history(employee, cancel) return employee def get_formatted_value(value, fieldtype): """ Since the fields in Internal Work History table are `Data` fields format them as per relevant field types """ if not value: return if fieldtype == "Date": value = getdate(value) elif fieldtype == "Datetime": value = get_datetime(value) elif fieldtype in ["Currency", "Float"]: # in case of currency/float, the value might be in user's prefered number format # instead of machine readable format. Convert it into a machine readable format number_format = frappe.db.get_default("number_format") or "#,###.##" decimal_str, comma_str, _number_format_precision = get_number_format_info(number_format) if comma_str == "." and decimal_str == ",": value = value.replace(",", "#$") value = value.replace(".", ",") value = value.replace("#$", ".") value = flt(value) return value def delete_employee_work_history(details, employee, date): filters = {} for d in details: for history in employee.internal_work_history: if d.property == "Department" and history.department == d.new: department = d.new filters["department"] = department if d.property == "Designation" and history.designation == d.new: designation = d.new filters["designation"] = designation if d.property == "Branch" and history.branch == d.new: branch = d.new filters["branch"] = branch if date and date == history.from_date: filters["from_date"] = date if filters: frappe.db.delete("Employee Internal Work History", filters) employee.save() def update_to_date_in_work_history(employee, cancel): if not employee.internal_work_history: return for idx, row in enumerate(employee.internal_work_history): if not row.from_date or idx == 0: continue prev_row = employee.internal_work_history[idx - 1] if not prev_row.to_date: prev_row.to_date = add_days(row.from_date, -1) if cancel: employee.internal_work_history[-1].to_date = None @frappe.whitelist() def get_employee_field_property(employee, fieldname): if not (employee and fieldname): return field = frappe.get_meta("Employee").get_field(fieldname) if not field: return value = frappe.db.get_value("Employee", employee, fieldname) if field.fieldtype == "Date": value = formatdate(value) elif field.fieldtype == "Datetime": value = format_datetime(value) return { "value": value, "datatype": field.fieldtype, "label": field.label, "options": field.options, } def validate_dates(doc, from_date, to_date): date_of_joining, relieving_date = frappe.db.get_value( "Employee", doc.employee, ["date_of_joining", "relieving_date"] ) if getdate(from_date) > getdate(to_date): frappe.throw(_("To date can not be less than from date")) elif getdate(from_date) > getdate(nowdate()): frappe.throw(_("Future dates not allowed")) elif date_of_joining and getdate(from_date) < getdate(date_of_joining): frappe.throw(_("From date can not be less than employee's joining date")) elif relieving_date and getdate(to_date) > getdate(relieving_date): frappe.throw(_("To date can not greater than employee's relieving date")) def validate_overlap(doc, from_date, to_date, company=None): query = """ select name from `tab{0}` where name != %(name)s """ query += get_doc_condition(doc.doctype) if not doc.name: # hack! if name is null, it could cause problems with != doc.name = "New " + doc.doctype overlap_doc = frappe.db.sql( query.format(doc.doctype), { "employee": doc.get("employee"), "from_date": from_date, "to_date": to_date, "name": doc.name, "company": company, }, as_dict=1, ) if overlap_doc: if doc.get("employee"): exists_for = doc.employee if company: exists_for = company throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date) def get_doc_condition(doctype): if doctype == "Compensatory Leave Request": return "and employee = %(employee)s and docstatus < 2 \ and (work_from_date between %(from_date)s and %(to_date)s \ or work_end_date between %(from_date)s and %(to_date)s \ or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))" elif doctype == "Leave Period": return "and company = %(company)s 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))" def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date): msg = ( _("A {0} exists between {1} and {2} (").format( doc.doctype, formatdate(from_date), formatdate(to_date) ) + f""" <b><a href="/app/Form/{doc.doctype}/{overlap_doc}">{overlap_doc}</a></b>""" + _(") for {0}").format(exists_for) ) frappe.throw(msg) def validate_duplicate_exemption_for_payroll_period(doctype, docname, payroll_period, employee): existing_record = frappe.db.exists( doctype, { "payroll_period": payroll_period, "employee": employee, "docstatus": ["<", 2], "name": ["!=", docname], }, ) if existing_record: frappe.throw( _("{0} already exists for employee {1} and period {2}").format(doctype, employee, payroll_period), DuplicateDeclarationError, ) def validate_tax_declaration(declarations): subcategories = [] for d in declarations: if d.exemption_sub_category in subcategories: frappe.throw(_("More than one selection for {0} not allowed").format(d.exemption_sub_category)) subcategories.append(d.exemption_sub_category) def get_total_exemption_amount(declarations): exemptions = frappe._dict() for d in declarations: exemptions.setdefault(d.exemption_category, frappe._dict()) category_max_amount = exemptions.get(d.exemption_category).max_amount if not category_max_amount: category_max_amount = frappe.db.get_value( "Employee Tax Exemption Category", d.exemption_category, "max_amount" ) exemptions.get(d.exemption_category).max_amount = category_max_amount sub_category_exemption_amount = ( d.max_amount if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount ) exemptions.get(d.exemption_category).setdefault("total_exemption_amount", 0.0) exemptions.get(d.exemption_category).total_exemption_amount += flt(sub_category_exemption_amount) if ( category_max_amount and exemptions.get(d.exemption_category).total_exemption_amount > category_max_amount ): exemptions.get(d.exemption_category).total_exemption_amount = category_max_amount total_exemption_amount = sum([flt(d.total_exemption_amount) for d in exemptions.values()]) return total_exemption_amount @frappe.whitelist() def get_leave_period(from_date, to_date, company): leave_period = frappe.db.sql( """ select name, from_date, to_date from `tabLeave Period` where company=%(company)s and is_active=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, "company": company}, as_dict=1, ) if leave_period: return leave_period def generate_leave_encashment(): """Generates a draft leave encashment on allocation expiry""" from hrms.hr.doctype.leave_encashment.leave_encashment import create_leave_encashment if frappe.db.get_single_value("HR Settings", "auto_leave_encashment"): leave_type = frappe.get_all("Leave Type", filters={"allow_encashment": 1}, fields=["name"]) leave_type = [l["name"] for l in leave_type] leave_allocation = frappe.get_all( "Leave Allocation", filters={"to_date": add_days(getdate(), -1), "leave_type": ("in", leave_type)}, fields=[ "employee", "leave_period", "leave_type", "to_date", "total_leaves_allocated", "new_leaves_allocated", ], ) create_leave_encashment(leave_allocation=leave_allocation) def allocate_earned_leaves(): """Allocate earned leaves to Employees""" e_leave_types = get_earned_leaves() today = frappe.flags.current_date or getdate() for e_leave_type in e_leave_types: leave_allocations = get_leave_allocations(today, e_leave_type.name) for allocation in leave_allocations: if not allocation.leave_policy_assignment and not allocation.leave_policy: continue leave_policy = ( allocation.leave_policy if allocation.leave_policy else frappe.db.get_value( "Leave Policy Assignment", allocation.leave_policy_assignment, ["leave_policy"] ) ) annual_allocation = frappe.db.get_value( "Leave Policy Detail", filters={"parent": leave_policy, "leave_type": e_leave_type.name}, fieldname=["annual_allocation"], ) date_of_joining = frappe.db.get_value("Employee", allocation.employee, "date_of_joining") from_date = allocation.from_date if e_leave_type.allocate_on_day == "Date of Joining": from_date = date_of_joining if check_effective_date( from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.allocate_on_day ): update_previous_leave_allocation(allocation, annual_allocation, e_leave_type, date_of_joining) def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type, date_of_joining): allocation = frappe.get_doc("Leave Allocation", allocation.name) annual_allocation = flt(annual_allocation, allocation.precision("total_leaves_allocated")) earned_leaves = get_monthly_earned_leave( date_of_joining, annual_allocation, e_leave_type.earned_leave_frequency, e_leave_type.rounding, ) new_allocation = flt(allocation.total_leaves_allocated) + flt(earned_leaves) new_allocation_without_cf = flt( flt(allocation.get_existing_leave_count()) + flt(earned_leaves), allocation.precision("total_leaves_allocated"), ) if new_allocation > e_leave_type.max_leaves_allowed and e_leave_type.max_leaves_allowed > 0: new_allocation = e_leave_type.max_leaves_allowed if ( new_allocation != allocation.total_leaves_allocated # annual allocation as per policy should not be exceeded and new_allocation_without_cf <= annual_allocation ): today_date = frappe.flags.current_date or getdate() allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False) create_additional_leave_ledger_entry(allocation, earned_leaves, today_date) if e_leave_type.allocate_on_day: text = _( "Allocated {0} leave(s) via scheduler on {1} based on the 'Allocate on Day' option set to {2}" ).format( frappe.bold(earned_leaves), frappe.bold(formatdate(today_date)), e_leave_type.allocate_on_day ) allocation.add_comment(comment_type="Info", text=text) def get_monthly_earned_leave( date_of_joining, annual_leaves, frequency, rounding, period_start_date=None, period_end_date=None, pro_rated=True, ): earned_leaves = 0.0 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 2, "Quarterly": 4, "Monthly": 12} if annual_leaves: earned_leaves = flt(annual_leaves) / divide_by_frequency[frequency] if pro_rated: if not (period_start_date or period_end_date): today_date = frappe.flags.current_date or getdate() period_end_date = get_last_day(today_date) period_start_date = get_first_day(today_date) earned_leaves = calculate_pro_rated_leaves( earned_leaves, date_of_joining, period_start_date, period_end_date, is_earned_leave=True ) earned_leaves = round_earned_leaves(earned_leaves, rounding) return earned_leaves def round_earned_leaves(earned_leaves, rounding): if not rounding: return earned_leaves if rounding == "0.25": earned_leaves = round(earned_leaves * 4) / 4 elif rounding == "0.5": earned_leaves = round(earned_leaves * 2) / 2 else: earned_leaves = round(earned_leaves) return earned_leaves def get_leave_allocations(date, leave_type): return frappe.db.sql( """select name, employee, from_date, to_date, leave_policy_assignment, leave_policy from `tabLeave Allocation` where %s between from_date and to_date and docstatus=1 and leave_type=%s""", (date, leave_type), as_dict=1, ) def get_earned_leaves(): return frappe.get_all( "Leave Type", fields=[ "name", "max_leaves_allowed", "earned_leave_frequency", "rounding", "allocate_on_day", ], filters={"is_earned_leave": 1}, ) def create_additional_leave_ledger_entry(allocation, leaves, date): """Create leave ledger entry for leave types""" allocation.new_leaves_allocated = leaves allocation.from_date = date allocation.unused_leaves = 0 allocation.create_leave_ledger_entry() def check_effective_date(from_date, today, frequency, allocate_on_day): from dateutil import relativedelta from_date = get_datetime(from_date) today = frappe.flags.current_date or get_datetime(today) rd = relativedelta.relativedelta(today, from_date) expected_date = { "First Day": get_first_day(today), "Last Day": get_last_day(today), "Date of Joining": from_date, }[allocate_on_day] if expected_date.day == today.day: if frequency == "Monthly": return True elif frequency == "Quarterly" and rd.months % 3: return True elif frequency == "Half-Yearly" and rd.months % 6: return True elif frequency == "Yearly" and rd.months % 12: return True return False def get_salary_assignments(employee, payroll_period): start_date, end_date = frappe.db.get_value("Payroll Period", payroll_period, ["start_date", "end_date"]) assignments = frappe.get_all( "Salary Structure Assignment", filters={"employee": employee, "docstatus": 1, "from_date": ["between", (start_date, end_date)]}, fields=["*"], order_by="from_date", ) if not assignments: # if no assignments found for the given period # get the last one assigned before the period that is still active assignments = frappe.get_all( "Salary Structure Assignment", filters={"employee": employee, "docstatus": 1, "from_date": ["<=", start_date]}, fields=["*"], order_by="from_date desc", limit=1, ) return assignments def get_sal_slip_total_benefit_given(employee, payroll_period, component=False): total_given_benefit_amount = 0 query = """ select sum(sd.amount) as total_amount from `tabSalary Slip` ss, `tabSalary Detail` sd where ss.employee=%(employee)s and ss.docstatus = 1 and ss.name = sd.parent and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings" and sd.parenttype = "Salary Slip" and (ss.start_date between %(start_date)s and %(end_date)s or ss.end_date between %(start_date)s and %(end_date)s or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s)) """ if component: query += "and sd.salary_component = %(component)s" sum_of_given_benefit = frappe.db.sql( query, { "employee": employee, "start_date": payroll_period.start_date, "end_date": payroll_period.end_date, "component": component, }, as_dict=True, ) if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0: total_given_benefit_amount = sum_of_given_benefit[0].total_amount return total_given_benefit_amount def get_holiday_dates_for_employee(employee, start_date, end_date): """return a list of holiday dates for the given employee between start_date and end_date""" # return only date holidays = get_holidays_for_employee(employee, start_date, end_date) return [cstr(h.holiday_date) for h in holidays] def get_holidays_for_employee(employee, start_date, end_date, raise_exception=True, only_non_weekly=False): """Get Holidays for a given employee `employee` (str) `start_date` (str or datetime) `end_date` (str or datetime) `raise_exception` (bool) `only_non_weekly` (bool) return: list of dicts with `holiday_date` and `description` """ holiday_list = get_holiday_list_for_employee(employee, raise_exception=raise_exception) if not holiday_list: return [] filters = {"parent": holiday_list, "holiday_date": ("between", [start_date, end_date])} if only_non_weekly: filters["weekly_off"] = False holidays = frappe.get_all( "Holiday", fields=["description", "holiday_date"], filters=filters, order_by="holiday_date" ) return holidays @erpnext.allow_regional def calculate_annual_eligible_hra_exemption(doc): # Don't delete this method, used for localization # Indian HRA Exemption Calculation return {} @erpnext.allow_regional def calculate_hra_exemption_for_period(doc): # Don't delete this method, used for localization # Indian HRA Exemption Calculation return {} def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False): total_claimed_amount = 0 query = """ select sum(claimed_amount) as 'total_amount' from `tabEmployee Benefit Claim` where employee=%(employee)s and docstatus = 1 and (claim_date between %(start_date)s and %(end_date)s) """ if non_pro_rata: query += "and pay_against_benefit_claim = 1" if component: query += "and earning_component = %(component)s" sum_of_claimed_amount = frappe.db.sql( query, { "employee": employee, "start_date": payroll_period.start_date, "end_date": payroll_period.end_date, "component": component, }, as_dict=True, ) if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0: total_claimed_amount = sum_of_claimed_amount[0].total_amount return total_claimed_amount def share_doc_with_approver(doc, user): if not user: return # if approver does not have permissions, share if not frappe.has_permission(doc=doc, ptype="submit", user=user): frappe.share.add_docshare( doc.doctype, doc.name, user, submit=1, flags={"ignore_share_permission": True} ) frappe.msgprint(_("Shared with the user {0} with 'submit' permisions").format(user, alert=True)) # remove shared doc if approver changes doc_before_save = doc.get_doc_before_save() if doc_before_save: approvers = { "Leave Application": "leave_approver", "Expense Claim": "expense_approver", "Shift Request": "approver", } approver = approvers.get(doc.doctype) if doc_before_save.get(approver) != doc.get(approver): frappe.share.remove(doc.doctype, doc.name, doc_before_save.get(approver)) def validate_active_employee(employee, method=None): if isinstance(employee, dict | Document): employee = employee.get("employee") if employee and frappe.db.get_value("Employee", employee, "status") == "Inactive": frappe.throw( _("Transactions cannot be created for an Inactive Employee {0}.").format( get_link_to_form("Employee", employee) ), InactiveEmployeeStatusError, ) def validate_loan_repay_from_salary(doc, method=None): if doc.applicant_type == "Employee" and doc.repay_from_salary: from hrms.payroll.doctype.salary_structure_assignment.salary_structure_assignment import ( get_employee_currency, ) if not doc.applicant: frappe.throw(_("Please select an Applicant")) if not doc.company: frappe.throw(_("Please select a Company")) employee_currency = get_employee_currency(doc.applicant) company_currency = erpnext.get_company_currency(doc.company) if employee_currency != company_currency: frappe.throw( _( "Loan cannot be repayed from salary for Employee {0} because salary is processed in currency {1}" ).format(doc.applicant, employee_currency) ) if not doc.is_term_loan and doc.repay_from_salary: frappe.throw(_("Repay From Salary can be selected only for term loans")) def get_matching_queries( bank_account, company, transaction, document_types, exact_match, account_from_to=None, from_date=None, to_date=None, filter_by_reference_date=None, from_reference_date=None, to_reference_date=None, common_filters=None, ): """Returns matching queries for Bank Reconciliation""" queries = [] if transaction.withdrawal > 0: if "expense_claim" in document_types: ec_amount_matching = get_ec_matching_query( bank_account, company, exact_match, from_date, to_date, common_filters ) queries.extend([ec_amount_matching]) return queries def get_ec_matching_query( bank_account, company, exact_match, from_date=None, to_date=None, common_filters=None ): # get matching Expense Claim query filters = [] ec = qb.DocType("Expense Claim") mode_of_payments = [ x["parent"] for x in frappe.db.get_all( "Mode of Payment Account", filters={"default_account": bank_account}, fields=["parent"] ) ] company_currency = get_company_currency(company) filters.append(ec.docstatus == 1) filters.append(ec.is_paid == 1) filters.append(ec.clearance_date.isnull()) filters.append(ec.mode_of_payment.isin(mode_of_payments)) if exact_match: filters.append(ec.total_sanctioned_amount == common_filters.amount) else: filters.append(ec.total_sanctioned_amount.gt(common_filters.amount)) if from_date and to_date: filters.append(ec.posting_date[from_date:to_date]) ref_rank = frappe.qb.terms.Case().when(ec.employee == common_filters.party, 1).else_(0) ec_query = ( qb.from_(ec) .select( (ref_rank + 1).as_("rank"), ec.name, ec.total_sanctioned_amount.as_("paid_amount"), ConstantColumn("").as_("reference_no"), ConstantColumn("").as_("reference_date"), ec.employee.as_("party"), ConstantColumn("Employee").as_("party_type"), ec.posting_date, ConstantColumn(company_currency).as_("currency"), ) .where(Criterion.all(filters)) ) if from_date and to_date: ec_query = ec_query.orderby(ec.posting_date) return ec_query def validate_bulk_tool_fields( self, fields: list, employees: list, from_date: str | None = None, to_date: str | None = None ) -> None: for d in fields: if not self.get(d): frappe.throw(_("{0} is required").format(self.meta.get_label(d)), title=_("Missing Field")) if self.get(from_date) and self.get(to_date): self.validate_from_to_dates(from_date, to_date) if not employees: frappe.throw( _("Please select at least one employee to perform this action."), title=_("No Employees Selected"), ) def notify_bulk_action_status(doctype: str, failure: list, success: list) -> None: frappe.clear_messages() msg = "" title = "" if failure: msg += _("Failed to create/submit {0} for employees:").format(doctype) msg += " " + comma_and(failure, False) + "<hr>" msg += ( _("Check {0} for more details") .format("<a href='/app/List/Error Log?reference_doctype={0}'>{1}</a>") .format(doctype, _("Error Log")) ) if success: title = _("Partial Success") msg += "<hr>" else: title = _("Creation Failed") else: title = _("Success") if success: msg += _("Successfully created {0} for employees:").format(doctype) msg += " " + comma_and(success, False) if failure: indicator = "orange" if success else "red" else: indicator = "green" frappe.msgprint( msg, indicator=indicator, title=title, is_minimizable=True, ) def check_app_permission(): """Check if user has permission to access the app (for showing the app on app screen)""" if frappe.session.user == "Administrator": return True if frappe.has_permission("Employee", ptype="read"): return True return False def get_exact_month_diff(string_ed_date: DateTimeLikeObject, string_st_date: DateTimeLikeObject) -> int: """Return the difference between given two dates in months.""" ed_date = getdate(string_ed_date) st_date = getdate(string_st_date) diff = (ed_date.year - st_date.year) * 12 + ed_date.month - st_date.month # count the last month only if end date's day > start date's day # to handle cases like 16th Jul 2024 - 15th Jul 2025 # where framework's month_diff will calculate diff as 13 months if ed_date.day > st_date.day: diff += 1 return diff
2302_79757062/hrms
hrms/hr/utils.py
Python
agpl-3.0
25,711
frappe.ready(function () { // bind events here });
2302_79757062/hrms
hrms/hr/web_form/job_application/job_application.js
JavaScript
agpl-3.0
52
def get_context(context): # do your magic here pass
2302_79757062/hrms
hrms/hr/web_form/job_application/job_application.py
Python
agpl-3.0
54
import click from hrms.setup import after_install as setup def after_install(): try: print("Setting up Frappe HR...") setup() click.secho("Thank you for installing Frappe HR!", fg="green") except Exception as e: BUG_REPORT_URL = "https://github.com/frappe/hrms/issues/new" click.secho( "Installation for Frappe HR app failed due to an error." " Please try re-installing the app or" f" report the issue on {BUG_REPORT_URL} if not resolved.", fg="bright_red", ) raise e
2302_79757062/hrms
hrms/install.py
Python
agpl-3.0
501
import frappe from frappe import _ from frappe.utils import flt class AppraisalMixin: """Mixin class for common validations in Appraisal doctypes""" def validate_total_weightage(self, table_name: str, table_label: str) -> None: if not self.get(table_name): return total_weightage = sum(flt(d.per_weightage) for d in self.get(table_name)) if flt(total_weightage, 2) != 100.0: frappe.throw( _("Total weightage for all {0} must add up to 100. Currently, it is {1}%").format( frappe.bold(_(table_label)), total_weightage ), title=_("Incorrect Weightage Allocation"), )
2302_79757062/hrms
hrms/mixins/appraisal.py
Python
agpl-3.0
604
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import bold class PWANotificationsMixin: """Mixin class for managing PWA updates""" def notify_approval_status(self): """Send Leave Application & Expense Claim Approval status notification - to employees""" status_field = self._get_doc_status_field() status = self.get(status_field) if self.has_value_changed(status_field) and status in ["Approved", "Rejected"]: from_user = frappe.session.user from_user_name = self._get_user_name(from_user) to_user = self._get_employee_user() if from_user == to_user: return notification = frappe.new_doc("PWA Notification") notification.from_user = from_user notification.to_user = to_user notification.message = f"{bold('Your')} {bold(self.doctype)} {self.name} has been {bold(status)} by {bold(from_user_name)}" notification.reference_document_type = self.doctype notification.reference_document_name = self.name notification.insert(ignore_permissions=True) def notify_approver(self): """Send new Leave Application & Expense Claim request notification - to approvers""" from_user = self._get_employee_user() to_user = self._get_doc_approver() if not to_user or from_user == to_user: return notification = frappe.new_doc("PWA Notification") notification.message = ( f"{bold(self.employee_name)} raised a new {bold(self.doctype)} for approval: {self.name}" ) notification.from_user = from_user notification.to_user = to_user notification.reference_document_type = self.doctype notification.reference_document_name = self.name notification.insert(ignore_permissions=True) def _get_doc_status_field(self) -> str: APPROVAL_STATUS_FIELD = { "Leave Application": "status", "Expense Claim": "approval_status", } return APPROVAL_STATUS_FIELD[self.doctype] def _get_doc_approver(self) -> str: APPROVER_FIELD = { "Leave Application": "leave_approver", "Expense Claim": "expense_approver", } approver_field = APPROVER_FIELD[self.doctype] return self.get(approver_field) def _get_employee_user(self) -> str: return frappe.db.get_value("Employee", self.employee, "user_id", cache=True) def _get_user_name(self, user) -> str: return frappe.db.get_value("User", user, "full_name", cache=True)
2302_79757062/hrms
hrms/mixins/pwa_notifications.py
Python
agpl-3.0
2,389
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import json import frappe from frappe import _ from erpnext.accounts.doctype.account.account import get_account_currency def make_company_fixtures(doc, method=None): if not frappe.flags.country_change: return run_regional_setup(doc.country) make_salary_components(doc.country) def delete_company_fixtures(): countries = frappe.get_all( "Company", distinct="True", pluck="country", ) for country in countries: try: module_name = f"hrms.regional.{frappe.scrub(country)}.setup.uninstall" frappe.get_attr(module_name)() except (ImportError, AttributeError): # regional file or method does not exist pass except Exception as e: frappe.log_error("Unable to delete country fixtures for Frappe HR") msg = _("Failed to delete defaults for country {0}.").format(frappe.bold(country)) msg += "<br><br>" + _("{0}: {1}").format(frappe.bold(_("Error")), get_error_message(e)) frappe.throw(msg, title=_("Country Fixture Deletion Failed")) def run_regional_setup(country): try: module_name = f"hrms.regional.{frappe.scrub(country)}.setup.setup" frappe.get_attr(module_name)() except ImportError: pass except Exception as e: frappe.log_error("Unable to setup country fixtures for Frappe HR") msg = _("Failed to setup defaults for country {0}.").format(frappe.bold(country)) msg += "<br><br>" + _("{0}: {1}").format(frappe.bold(_("Error")), get_error_message(e)) frappe.throw(msg, title=_("Country Setup failed")) def get_error_message(error) -> str: try: message_log = frappe.message_log.pop() if frappe.message_log else str(error) if isinstance(message_log, str): error_message = json.loads(message_log).get("message") else: error_message = message_log.get("message") except Exception: error_message = message_log return error_message def make_salary_components(country): docs = [] file_name = "salary_components.json" # default components already added if not frappe.db.exists("Salary Component", "Basic"): file_path = frappe.get_app_path("hrms", "payroll", "data", file_name) docs.extend(json.loads(read_data_file(file_path))) file_path = frappe.get_app_path("hrms", "regional", frappe.scrub(country), "data", file_name) docs.extend(json.loads(read_data_file(file_path))) for d in docs: try: doc = frappe.get_doc(d) doc.flags.ignore_permissions = True doc.flags.ignore_mandatory = True doc.insert(ignore_if_duplicate=True) except frappe.NameError: frappe.clear_messages() except frappe.DuplicateEntryError: frappe.clear_messages() def read_data_file(file_path): try: with open(file_path) as f: return f.read() except OSError: return "{}" def set_default_hr_accounts(doc, method=None): if frappe.local.flags.ignore_chart_of_accounts: return if not doc.default_payroll_payable_account: payroll_payable_account = frappe.db.get_value( "Account", {"account_name": _("Payroll Payable"), "company": doc.name, "is_group": 0} ) doc.db_set("default_payroll_payable_account", payroll_payable_account) if not doc.default_employee_advance_account: employe_advance_account = frappe.db.get_value( "Account", {"account_name": _("Employee Advances"), "company": doc.name, "is_group": 0} ) doc.db_set("default_employee_advance_account", employe_advance_account) def validate_default_accounts(doc, method=None): if doc.default_payroll_payable_account: for_company = frappe.db.get_value("Account", doc.default_payroll_payable_account, "company") if for_company != doc.name: frappe.throw( _("Account {0} does not belong to company: {1}").format( doc.default_payroll_payable_account, doc.name ) ) if get_account_currency(doc.default_payroll_payable_account) != doc.default_currency: frappe.throw( _( "The currency of {0} should be same as the company's default currency. Please select another account." ).format(frappe.bold(_("Default Payroll Payable Account"))) )
2302_79757062/hrms
hrms/overrides/company.py
Python
agpl-3.0
4,077
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from frappe import _ def get_dashboard_for_employee(data): data["transactions"].extend( [ {"label": _("Attendance"), "items": ["Attendance", "Attendance Request", "Employee Checkin"]}, { "label": _("Leave"), "items": ["Leave Application", "Leave Allocation", "Leave Policy Assignment"], }, { "label": _("Lifecycle"), "items": [ "Employee Onboarding", "Employee Transfer", "Employee Promotion", "Employee Grievance", ], }, { "label": _("Exit"), "items": [ "Employee Separation", "Exit Interview", "Full and Final Statement", "Salary Withholding", ], }, {"label": _("Shift"), "items": ["Shift Request", "Shift Assignment"]}, {"label": _("Expense"), "items": ["Expense Claim", "Travel Request", "Employee Advance"]}, {"label": _("Benefit"), "items": ["Employee Benefit Application", "Employee Benefit Claim"]}, { "label": _("Payroll"), "items": [ "Salary Structure Assignment", "Salary Slip", "Additional Salary", "Timesheet", "Employee Incentive", "Retention Bonus", "Bank Account", ], }, { "label": _("Training"), "items": ["Training Event", "Training Result", "Training Feedback", "Employee Skill Map"], }, {"label": _("Evaluation"), "items": ["Appraisal"]}, ] ) data["non_standard_fieldnames"].update({"Bank Account": "party", "Employee Grievance": "raised_by"}) data.update( { "heatmap": True, "heatmap_message": _("This is based on the attendance of this Employee"), "fieldname": "employee", "method": "hrms.overrides.employee_master.get_timeline_data", } ) return data def get_dashboard_for_holiday_list(data): data["non_standard_fieldnames"].update({"Leave Period": "optional_holiday_list"}) data["transactions"].append({"items": ["Leave Period", "Shift Type"]}) return data def get_dashboard_for_timesheet(data): data["transactions"].append({"label": _("Payroll"), "items": ["Salary Slip"]}) return data def get_dashboard_for_project(data): data["transactions"].append( {"label": _("Claims"), "items": ["Expense Claim"]}, ) return data
2302_79757062/hrms
hrms/overrides/dashboard_overrides.py
Python
agpl-3.0
2,291
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ from frappe.model.naming import set_name_by_naming_series from frappe.utils import add_years, cint, get_link_to_form, getdate from erpnext.setup.doctype.employee.employee import Employee class EmployeeMaster(Employee): def autoname(self): naming_method = frappe.db.get_value("HR Settings", None, "emp_created_by") if not naming_method: frappe.throw(_("Please setup Employee Naming System in Human Resource > HR Settings")) else: if naming_method == "Naming Series": set_name_by_naming_series(self) elif naming_method == "Employee Number": self.name = self.employee_number elif naming_method == "Full Name": self.set_employee_name() self.name = self.employee_name self.employee = self.name def validate_onboarding_process(doc, method=None): """Validates Employee Creation for linked Employee Onboarding""" if not doc.job_applicant: return employee_onboarding = frappe.get_all( "Employee Onboarding", filters={ "job_applicant": doc.job_applicant, "docstatus": 1, "boarding_status": ("!=", "Completed"), }, ) if employee_onboarding: onboarding = frappe.get_doc("Employee Onboarding", employee_onboarding[0].name) onboarding.validate_employee_creation() onboarding.db_set("employee", doc.name) def publish_update(doc, method=None): import hrms hrms.refetch_resource("hrms:employee", doc.user_id) def update_job_applicant_and_offer(doc, method=None): """Updates Job Applicant and Job Offer status as 'Accepted' and submits them""" if not doc.job_applicant: return applicant_status_before_change = frappe.db.get_value("Job Applicant", doc.job_applicant, "status") if applicant_status_before_change != "Accepted": frappe.db.set_value("Job Applicant", doc.job_applicant, "status", "Accepted") frappe.msgprint( _("Updated the status of linked Job Applicant {0} to {1}").format( get_link_to_form("Job Applicant", doc.job_applicant), frappe.bold(_("Accepted")) ) ) offer_status_before_change = frappe.db.get_value( "Job Offer", {"job_applicant": doc.job_applicant, "docstatus": ["!=", 2]}, "status" ) if offer_status_before_change and offer_status_before_change != "Accepted": job_offer = frappe.get_last_doc("Job Offer", filters={"job_applicant": doc.job_applicant}) job_offer.status = "Accepted" job_offer.flags.ignore_mandatory = True job_offer.flags.ignore_permissions = True job_offer.save() msg = _("Updated the status of Job Offer {0} for the linked Job Applicant {1} to {2}").format( get_link_to_form("Job Offer", job_offer.name), frappe.bold(doc.job_applicant), frappe.bold(_("Accepted")), ) if job_offer.docstatus == 0: msg += "<br>" + _("You may add additional details, if any, and submit the offer.") frappe.msgprint(msg) def update_approver_role(doc, method=None): """Adds relevant approver role for the user linked to Employee""" if doc.leave_approver: user = frappe.get_doc("User", doc.leave_approver) user.flags.ignore_permissions = True user.add_roles("Leave Approver") if doc.expense_approver: user = frappe.get_doc("User", doc.expense_approver) user.flags.ignore_permissions = True user.add_roles("Expense Approver") def update_employee_transfer(doc, method=None): """Unsets Employee ID in Employee Transfer if doc is deleted""" if frappe.db.exists("Employee Transfer", {"new_employee_id": doc.name, "docstatus": 1}): emp_transfer = frappe.get_doc("Employee Transfer", {"new_employee_id": doc.name, "docstatus": 1}) emp_transfer.db_set("new_employee_id", "") @frappe.whitelist() def get_timeline_data(doctype, name): """Return timeline for attendance""" from frappe.desk.notifications import get_open_count out = {} open_count = get_open_count(doctype, name) out["count"] = open_count["count"] timeline_data = dict( frappe.db.sql( """ select unix_timestamp(attendance_date), count(*) from `tabAttendance` where employee=%s and attendance_date > date_sub(curdate(), interval 1 year) and status in ('Present', 'Half Day') group by attendance_date""", name, ) ) out["timeline_data"] = timeline_data return out @frappe.whitelist() def get_retirement_date(date_of_birth=None): if date_of_birth: try: retirement_age = cint(frappe.db.get_single_value("HR Settings", "retirement_age") or 60) dt = add_years(getdate(date_of_birth), retirement_age) return dt.strftime("%Y-%m-%d") except ValueError: # invalid date return
2302_79757062/hrms
hrms/overrides/employee_master.py
Python
agpl-3.0
4,609
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe.utils import flt, nowdate import erpnext from erpnext.accounts.doctype.payment_entry.payment_entry import ( PaymentEntry, get_bank_cash_account, get_reference_details, ) from erpnext.accounts.utils import get_account_currency from erpnext.setup.utils import get_exchange_rate from hrms.hr.doctype.expense_claim.expense_claim import get_outstanding_amount_for_claim class EmployeePaymentEntry(PaymentEntry): def get_valid_reference_doctypes(self): if self.party_type == "Customer": return ("Sales Order", "Sales Invoice", "Journal Entry", "Dunning", "Payment Entry") elif self.party_type == "Supplier": return ("Purchase Order", "Purchase Invoice", "Journal Entry", "Payment Entry") elif self.party_type == "Shareholder": return ("Journal Entry",) elif self.party_type == "Employee": return ("Expense Claim", "Journal Entry", "Employee Advance", "Gratuity") def set_missing_ref_details( self, force: bool = False, update_ref_details_only_for: list | None = None, reference_exchange_details: dict | None = None, ) -> None: for d in self.get("references"): if d.allocated_amount: if update_ref_details_only_for and ( (d.reference_doctype, d.reference_name) not in update_ref_details_only_for ): continue ref_details = get_payment_reference_details( d.reference_doctype, d.reference_name, self.party_account_currency, self.party_type, self.party, ) # Only update exchange rate when the reference is Journal Entry if ( reference_exchange_details and d.reference_doctype == reference_exchange_details.reference_doctype and d.reference_name == reference_exchange_details.reference_name ): ref_details.update({"exchange_rate": reference_exchange_details.exchange_rate}) for field, value in ref_details.items(): if d.exchange_gain_loss: # for cases where gain/loss is booked into invoice # exchange_gain_loss is calculated from invoice & populated # and row.exchange_rate is already set to payment entry's exchange rate # refer -> `update_reference_in_payment_entry()` in utils.py continue if field == "exchange_rate" or not d.get(field) or force: d.db_set(field, value) @frappe.whitelist() def get_payment_entry_for_employee(dt, dn, party_amount=None, bank_account=None, bank_amount=None): """Function to make Payment Entry for Employee Advance, Gratuity, Expense Claim""" doc = frappe.get_doc(dt, dn) party_account = get_party_account(doc) party_account_currency = get_account_currency(party_account) payment_type = "Pay" grand_total, outstanding_amount = get_grand_total_and_outstanding_amount( doc, party_amount, party_account_currency ) # bank or cash bank = get_bank_cash_account(doc, bank_account) paid_amount, received_amount = get_paid_amount_and_received_amount( doc, party_account_currency, bank, outstanding_amount, payment_type, bank_amount ) pe = frappe.new_doc("Payment Entry") pe.payment_type = payment_type pe.company = doc.company pe.cost_center = doc.get("cost_center") pe.posting_date = nowdate() pe.mode_of_payment = doc.get("mode_of_payment") pe.party_type = "Employee" pe.party = doc.get("employee") pe.contact_person = doc.get("contact_person") pe.contact_email = doc.get("contact_email") pe.letter_head = doc.get("letter_head") pe.paid_from = bank.account pe.paid_to = party_account pe.paid_from_account_currency = bank.account_currency pe.paid_to_account_currency = party_account_currency pe.paid_amount = paid_amount pe.received_amount = received_amount pe.append( "references", { "reference_doctype": dt, "reference_name": dn, "bill_no": doc.get("bill_no"), "due_date": doc.get("due_date"), "total_amount": grand_total, "outstanding_amount": outstanding_amount, "allocated_amount": outstanding_amount, }, ) pe.setup_party_account_field() pe.set_missing_values() pe.set_missing_ref_details() if party_account and bank: reference_doc = None if dt == "Employee Advance": reference_doc = doc pe.set_exchange_rate(ref_doc=reference_doc) pe.set_amounts() return pe def get_party_account(doc): party_account = None if doc.doctype == "Employee Advance": party_account = doc.advance_account elif doc.doctype in ("Expense Claim", "Gratuity"): party_account = doc.payable_account return party_account def get_grand_total_and_outstanding_amount(doc, party_amount, party_account_currency): grand_total = outstanding_amount = 0 if party_amount: grand_total = outstanding_amount = party_amount elif doc.doctype == "Expense Claim": grand_total = flt(doc.total_sanctioned_amount) + flt(doc.total_taxes_and_charges) outstanding_amount = flt(doc.grand_total) - flt(doc.total_amount_reimbursed) elif doc.doctype == "Employee Advance": grand_total = flt(doc.advance_amount) outstanding_amount = flt(doc.advance_amount) - flt(doc.paid_amount) if party_account_currency != doc.currency: grand_total = flt(doc.advance_amount) * flt(doc.exchange_rate) outstanding_amount = (flt(doc.advance_amount) - flt(doc.paid_amount)) * flt(doc.exchange_rate) elif doc.doctype == "Gratuity": grand_total = doc.amount outstanding_amount = flt(doc.amount) - flt(doc.paid_amount) else: if party_account_currency == doc.company_currency: grand_total = flt(doc.get("base_rounded_total") or doc.base_grand_total) else: grand_total = flt(doc.get("rounded_total") or doc.grand_total) outstanding_amount = grand_total - flt(doc.advance_paid) return grand_total, outstanding_amount def get_paid_amount_and_received_amount( doc, party_account_currency, bank, outstanding_amount, payment_type, bank_amount ): paid_amount = received_amount = 0 if party_account_currency == bank.account_currency: paid_amount = received_amount = abs(outstanding_amount) elif payment_type == "Receive": paid_amount = abs(outstanding_amount) if bank_amount: received_amount = bank_amount else: received_amount = paid_amount * doc.get("conversion_rate", 1) if doc.doctype == "Employee Advance": received_amount = paid_amount * doc.get("exchange_rate", 1) else: received_amount = abs(outstanding_amount) if bank_amount: paid_amount = bank_amount else: # if party account currency and bank currency is different then populate paid amount as well paid_amount = received_amount * doc.get("conversion_rate", 1) if doc.doctype == "Employee Advance": paid_amount = received_amount * doc.get("exchange_rate", 1) return paid_amount, received_amount @frappe.whitelist() def get_payment_reference_details( reference_doctype, reference_name, party_account_currency, party_type=None, party=None ): if reference_doctype in ("Expense Claim", "Employee Advance", "Gratuity"): return get_reference_details_for_employee(reference_doctype, reference_name, party_account_currency) else: return get_reference_details( reference_doctype, reference_name, party_account_currency, party_type, party ) @frappe.whitelist() def get_reference_details_for_employee(reference_doctype, reference_name, party_account_currency): """ Returns payment reference details for employee related doctypes: Employee Advance, Expense Claim, Gratuity """ total_amount = outstanding_amount = exchange_rate = None ref_doc = frappe.get_doc(reference_doctype, reference_name) company_currency = ref_doc.get("company_currency") or erpnext.get_company_currency(ref_doc.company) total_amount, exchange_rate = get_total_amount_and_exchange_rate( ref_doc, party_account_currency, company_currency ) if reference_doctype == "Expense Claim": outstanding_amount = get_outstanding_amount_for_claim(ref_doc) elif reference_doctype == "Employee Advance": outstanding_amount = flt(ref_doc.advance_amount) - flt(ref_doc.paid_amount) if party_account_currency != ref_doc.currency: outstanding_amount = flt(outstanding_amount) * flt(exchange_rate) elif reference_doctype == "Gratuity": outstanding_amount = ref_doc.amount - flt(ref_doc.paid_amount) else: outstanding_amount = flt(total_amount) - flt(ref_doc.advance_paid) return frappe._dict( { "due_date": ref_doc.get("due_date"), "total_amount": flt(total_amount), "outstanding_amount": flt(outstanding_amount), "exchange_rate": flt(exchange_rate), } ) def get_total_amount_and_exchange_rate(ref_doc, party_account_currency, company_currency): total_amount = exchange_rate = None if ref_doc.doctype == "Expense Claim": total_amount = flt(ref_doc.total_sanctioned_amount) + flt(ref_doc.total_taxes_and_charges) elif ref_doc.doctype == "Employee Advance": total_amount = ref_doc.advance_amount exchange_rate = ref_doc.get("exchange_rate") if party_account_currency != ref_doc.currency: total_amount = flt(total_amount) * flt(exchange_rate) if party_account_currency == company_currency: exchange_rate = 1 elif ref_doc.doctype == "Gratuity": total_amount = ref_doc.amount if not total_amount: if party_account_currency == company_currency: total_amount = ref_doc.base_grand_total exchange_rate = 1 else: total_amount = ref_doc.grand_total if not exchange_rate: # Get the exchange rate from the original ref doc # or get it based on the posting date of the ref doc. exchange_rate = ref_doc.get("conversion_rate") or get_exchange_rate( party_account_currency, company_currency, ref_doc.posting_date ) return total_amount, exchange_rate
2302_79757062/hrms
hrms/overrides/employee_payment_entry.py
Python
agpl-3.0
9,626
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe.query_builder.functions import Max, Min, Sum from frappe.utils import flt from erpnext.projects.doctype.project.project import Project class EmployeeProject(Project): def calculate_gross_margin(self): expense_amount = ( flt(self.total_costing_amount) # add expense claim amount + flt(self.total_expense_claim) + flt(self.total_purchase_cost) + flt(self.get("total_consumed_material_cost", 0)) ) self.gross_margin = flt(self.total_billed_amount) - expense_amount if self.total_billed_amount: self.per_gross_margin = (self.gross_margin / flt(self.total_billed_amount)) * 100 def update_costing(self): ExpenseClaim = frappe.qb.DocType("Expense Claim") self.total_expense_claim = ( frappe.qb.from_(ExpenseClaim) .select(Sum(ExpenseClaim.total_sanctioned_amount)) .where((ExpenseClaim.docstatus == 1) & (ExpenseClaim.project == self.name)) ).run()[0][0] TimesheetDetail = frappe.qb.DocType("Timesheet Detail") from_time_sheet = ( frappe.qb.from_(TimesheetDetail) .select( Sum(TimesheetDetail.costing_amount).as_("costing_amount"), Sum(TimesheetDetail.billing_amount).as_("billing_amount"), Min(TimesheetDetail.from_time).as_("start_date"), Max(TimesheetDetail.to_time).as_("end_date"), Sum(TimesheetDetail.hours).as_("time"), ) .where((TimesheetDetail.project == self.name) & (TimesheetDetail.docstatus == 1)) ).run(as_dict=True)[0] self.actual_start_date = from_time_sheet.start_date self.actual_end_date = from_time_sheet.end_date self.total_costing_amount = from_time_sheet.costing_amount self.total_billable_amount = from_time_sheet.billing_amount self.actual_time = from_time_sheet.time self.update_purchase_costing() self.update_sales_amount() self.update_billed_amount() self.calculate_gross_margin()
2302_79757062/hrms
hrms/overrides/employee_project.py
Python
agpl-3.0
1,965
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from erpnext.projects.doctype.timesheet.timesheet import Timesheet class EmployeeTimesheet(Timesheet): def set_status(self): self.status = {"0": "Draft", "1": "Submitted", "2": "Cancelled"}[str(self.docstatus or 0)] if self.per_billed == 100: self.status = "Billed" if self.salary_slip: self.status = "Payslip" if self.sales_invoice and self.salary_slip: self.status = "Completed"
2302_79757062/hrms
hrms/overrides/employee_timesheet.py
Python
agpl-3.0
532
import frappe from hrms.overrides.company import make_salary_components, run_regional_setup def execute(): for country in frappe.get_all("Company", pluck="country", distinct=True): run_regional_setup(country) make_salary_components(country)
2302_79757062/hrms
hrms/patches/post_install/create_country_fixtures.py
Python
agpl-3.0
249
import frappe def execute(): frappe.delete_doc("DocType", "Employee Transfer Property", ignore_missing=True)
2302_79757062/hrms
hrms/patches/post_install/delete_employee_transfer_property_doctype.py
Python
agpl-3.0
112
# Copyright (c) 2019, Frappe and Contributors # License: GNU General Public License v3. See license.txt import frappe def execute(): frappe.db.sql( """UPDATE `tabPrint Format` SET module = 'Payroll' WHERE name IN ('Salary Slip Based On Timesheet', 'Salary Slip Standard')""" ) doctypes_moved = [ "Employee Benefit Application Detail", "Employee Tax Exemption Declaration Category", "Salary Component", "Employee Tax Exemption Proof Submission Detail", "Income Tax Slab Other Charges", "Taxable Salary Slab", "Payroll Period Date", "Salary Slip Timesheet", "Payroll Employee Detail", "Salary Detail", "Employee Tax Exemption Sub Category", "Employee Tax Exemption Category", "Employee Benefit Claim", "Employee Benefit Application", "Employee Other Income", "Employee Tax Exemption Proof Submission", "Employee Tax Exemption Declaration", "Employee Incentive", "Retention Bonus", "Additional Salary", "Income Tax Slab", "Payroll Period", "Salary Slip", "Payroll Entry", "Salary Structure Assignment", "Salary Structure", ] for doctype in doctypes_moved: frappe.delete_doc_if_exists("DocType", {"name": doctype, "module": "HR"})
2302_79757062/hrms
hrms/patches/post_install/move_doctype_reports_and_notification_from_hr_to_payroll.py
Python
agpl-3.0
1,198
# Copyright (c) 2019, Frappe and Contributors # License: GNU General Public License v3. See license.txt import frappe def execute(): data = frappe.db.sql( """SELECT * FROM `tabSingles` WHERE doctype = "HR Settings" AND field in ( "encrypt_salary_slips_in_emails", "email_salary_slip_to_employee", "daily_wages_fraction_for_half_day", "disable_rounded_total", "include_holidays_in_total_working_days", "max_working_hours_against_timesheet", "payroll_based_on", "password_policy" ) """, as_dict=1, ) for d in data: frappe.db.set_value("Payroll Settings", None, d.field, d.value)
2302_79757062/hrms
hrms/patches/post_install/move_payroll_setting_separately_from_hr_settings.py
Python
agpl-3.0
791
# Copyright (c) 2019, Frappe and Contributors # License: GNU General Public License v3. See license.txt import frappe def execute(): if not (frappe.db.table_exists("Payroll Period") and frappe.db.table_exists("Taxable Salary Slab")): return if frappe.db.a_row_exists("Income Tax Slab"): return for doctype in ( "income_tax_slab", "salary_structure_assignment", "employee_other_income", "income_tax_slab_other_charges", ): frappe.reload_doc("Payroll", "doctype", doctype) standard_tax_exemption_amount_exists = frappe.db.has_column( "Payroll Period", "standard_tax_exemption_amount" ) select_fields = "name, start_date, end_date" if standard_tax_exemption_amount_exists: select_fields = "name, start_date, end_date, standard_tax_exemption_amount" for company in frappe.get_all("Company"): payroll_periods = frappe.db.sql( f""" SELECT {select_fields} FROM `tabPayroll Period` WHERE company=%s ORDER BY start_date DESC """, company.name, as_dict=1, ) for i, period in enumerate(payroll_periods): income_tax_slab = frappe.new_doc("Income Tax Slab") income_tax_slab.name = "Tax Slab:" + period.name if i == 0: income_tax_slab.disabled = 0 else: income_tax_slab.disabled = 1 income_tax_slab.effective_from = period.start_date income_tax_slab.company = company.name income_tax_slab.allow_tax_exemption = 1 if standard_tax_exemption_amount_exists: income_tax_slab.standard_tax_exemption_amount = period.standard_tax_exemption_amount income_tax_slab.flags.ignore_mandatory = True income_tax_slab.submit() frappe.db.sql( """ UPDATE `tabTaxable Salary Slab` SET parent = %s , parentfield = 'slabs' , parenttype = "Income Tax Slab" WHERE parent = %s """, (income_tax_slab.name, period.name), as_dict=1, ) if i == 0: frappe.db.sql( """ UPDATE `tabSalary Structure Assignment` set income_tax_slab = %s where company = %s and from_date >= %s and docstatus < 2 """, (income_tax_slab.name, company.name, period.start_date), ) # move other incomes to separate document if not frappe.db.table_exists("Employee Tax Exemption Proof Submission"): return if not frappe.db.has_column("Employee Tax Exemption Proof Submission", "income_from_other_sources"): return migrated = [] proofs = frappe.get_all( "Employee Tax Exemption Proof Submission", filters={"docstatus": 1}, fields=["payroll_period", "employee", "company", "income_from_other_sources"], ) for proof in proofs: if proof.income_from_other_sources: employee_other_income = frappe.new_doc("Employee Other Income") employee_other_income.employee = proof.employee employee_other_income.payroll_period = proof.payroll_period employee_other_income.company = proof.company employee_other_income.amount = proof.income_from_other_sources try: employee_other_income.submit() migrated.append([proof.employee, proof.payroll_period]) except Exception: pass if not frappe.db.table_exists("Employee Tax Exemption Declaration"): return if not frappe.db.has_column("Employee Tax Exemption Declaration", "income_from_other_sources"): return declerations = frappe.get_all( "Employee Tax Exemption Declaration", filters={"docstatus": 1}, fields=["payroll_period", "employee", "company", "income_from_other_sources"], ) for declaration in declerations: if ( declaration.income_from_other_sources and [declaration.employee, declaration.payroll_period] not in migrated ): employee_other_income = frappe.new_doc("Employee Other Income") employee_other_income.employee = declaration.employee employee_other_income.payroll_period = declaration.payroll_period employee_other_income.company = declaration.company employee_other_income.amount = declaration.income_from_other_sources try: employee_other_income.submit() except Exception: pass
2302_79757062/hrms
hrms/patches/post_install/move_tax_slabs_from_payroll_period_to_income_tax_slab.py
Python
agpl-3.0
3,986
import frappe from frappe.model.utils.rename_field import rename_field def execute(): frappe.reload_doc("hr", "doctype", "hr_settings") try: # Rename the field rename_field("HR Settings", "stop_birthday_reminders", "send_birthday_reminders") # Reverse the value old_value = frappe.db.get_single_value("HR Settings", "send_birthday_reminders") frappe.db.set_single_value("HR Settings", "send_birthday_reminders", 1 if old_value == 0 else 0) except Exception as e: if e.args[0] != 1054: raise
2302_79757062/hrms
hrms/patches/post_install/rename_stop_to_send_birthday_reminders.py
Python
agpl-3.0
515
import frappe def execute(): frappe.reload_doc("HR", "doctype", "Leave Allocation") frappe.reload_doc("HR", "doctype", "Leave Ledger Entry") frappe.db.sql( """ UPDATE `tabLeave Ledger Entry` as lle SET company = (select company from `tabEmployee` where employee = lle.employee) WHERE company IS NULL """ ) frappe.db.sql( """ UPDATE `tabLeave Allocation` as la SET company = (select company from `tabEmployee` where employee = la.employee) WHERE company IS NULL """ )
2302_79757062/hrms
hrms/patches/post_install/set_company_in_leave_ledger_entry.py
Python
agpl-3.0
495
import frappe # Set department value based on employee value def execute(): doctypes_to_update = { "hr": [ "Appraisal", "Leave Allocation", "Expense Claim", "Salary Slip", "Attendance", "Training Feedback", "Training Result Employee", "Leave Application", "Employee Advance", "Training Event Employee", "Payroll Employee Detail", ], "education": ["Instructor"], "projects": ["Activity Cost", "Timesheet"], "setup": ["Sales Person"], } for module, doctypes in doctypes_to_update.items(): for doctype in doctypes: if frappe.db.table_exists(doctype): frappe.reload_doc(module, "doctype", frappe.scrub(doctype)) frappe.db.sql( f""" update `tab{doctype}` dt set department=(select department from `tabEmployee` where name=dt.employee) where coalesce(`tab{doctype}`.`department`, '') = '' """ )
2302_79757062/hrms
hrms/patches/post_install/set_department_for_doctypes.py
Python
agpl-3.0
881
import frappe def execute(): frappe.reload_doc("payroll", "doctype", "employee_cost_center") frappe.reload_doc("payroll", "doctype", "salary_structure_assignment") employees = frappe.get_all("Employee", fields=["department", "payroll_cost_center", "name"]) employee_cost_center = {} for d in employees: cost_center = d.payroll_cost_center if not cost_center and d.department: cost_center = frappe.get_cached_value("Department", d.department, "payroll_cost_center") if cost_center: employee_cost_center.setdefault(d.name, cost_center) salary_structure_assignments = frappe.get_all( "Salary Structure Assignment", filters={"docstatus": ["!=", 2]}, fields=["name", "employee"] ) for d in salary_structure_assignments: cost_center = employee_cost_center.get(d.employee) if cost_center: assignment = frappe.get_doc("Salary Structure Assignment", d.name) if not assignment.get("payroll_cost_centers"): assignment.append("payroll_cost_centers", {"cost_center": cost_center, "percentage": 100}) assignment.save()
2302_79757062/hrms
hrms/patches/post_install/set_payroll_cost_centers.py
Python
agpl-3.0
1,052
import frappe def execute(): PayrollEntry = frappe.qb.DocType("Payroll Entry") status = ( frappe.qb.terms.Case() .when(PayrollEntry.docstatus == 0, "Draft") .when(PayrollEntry.docstatus == 1, "Submitted") .else_("Cancelled") ) (frappe.qb.update(PayrollEntry).set("status", status).where(PayrollEntry.status.isnull())).run()
2302_79757062/hrms
hrms/patches/post_install/set_payroll_entry_status.py
Python
agpl-3.0
340
import frappe def execute(): frappe.reload_doc("hr", "doctype", "training_event") frappe.reload_doc("hr", "doctype", "training_event_employee") # no need to run the update query as there is no old data if not frappe.db.exists("Training Event Employee", {"attendance": ("in", ("Mandatory", "Optional"))}): return frappe.db.sql( """ UPDATE `tabTraining Event Employee` SET is_mandatory = 1 WHERE attendance = 'Mandatory' """ ) frappe.db.sql( """ UPDATE `tabTraining Event Employee` SET attendance = 'Present' WHERE attendance in ('Mandatory', 'Optional') """ )
2302_79757062/hrms
hrms/patches/post_install/set_training_event_attendance.py
Python
agpl-3.0
592
import frappe def execute(): frappe.clear_cache(doctype="Leave Type") if frappe.db.has_column("Leave Type", "based_on_date_of_joining"): LeaveType = frappe.qb.DocType("Leave Type") frappe.qb.update(LeaveType).set(LeaveType.allocate_on_day, "Last Day").where( (LeaveType.based_on_date_of_joining == 0) & (LeaveType.is_earned_leave == 1) ).run() frappe.qb.update(LeaveType).set(LeaveType.allocate_on_day, "Date of Joining").where( LeaveType.based_on_date_of_joining == 1 ).run() frappe.db.sql_ddl("alter table `tabLeave Type` drop column `based_on_date_of_joining`") # clear cache for doctype as it stores table columns in cache frappe.clear_cache(doctype="Leave Type")
2302_79757062/hrms
hrms/patches/post_install/update_allocate_on_in_leave_type.py
Python
agpl-3.0
697
import frappe def execute(): frappe.reload_doc("hr", "doctype", "employee_advance") advance = frappe.qb.DocType("Employee Advance") ( frappe.qb.update(advance) .set(advance.status, "Returned") .where( (advance.docstatus == 1) & ((advance.return_amount) & (advance.paid_amount == advance.return_amount)) & (advance.status == "Paid") ) ).run() ( frappe.qb.update(advance) .set(advance.status, "Partly Claimed and Returned") .where( (advance.docstatus == 1) & ( (advance.claimed_amount & advance.return_amount) & (advance.paid_amount == (advance.return_amount + advance.claimed_amount)) ) & (advance.status == "Paid") ) ).run()
2302_79757062/hrms
hrms/patches/post_install/update_employee_advance_status.py
Python
agpl-3.0
680
import frappe def execute(): """ Update Expense Claim status to Paid if: - the entire required amount is already covered via linked advances - the claim is partially paid via advances and the rest is reimbursed """ ExpenseClaim = frappe.qb.DocType("Expense Claim") ( frappe.qb.update(ExpenseClaim) .set(ExpenseClaim.status, "Paid") .where( ( (ExpenseClaim.grand_total == 0) | (ExpenseClaim.grand_total == ExpenseClaim.total_amount_reimbursed) ) & (ExpenseClaim.approval_status == "Approved") & (ExpenseClaim.docstatus == 1) & (ExpenseClaim.total_sanctioned_amount > 0) ) ).run()
2302_79757062/hrms
hrms/patches/post_install/update_expense_claim_status_for_paid_advances.py
Python
agpl-3.0
638
import frappe from frappe.model.utils.rename_field import rename_field from frappe.utils import cstr def execute(): create_kras() rename_fields() update_kra_evaluation_method() def create_kras(): # A new Link field `key_result_area` was added in the Appraisal Template Goal table # Old field's (`kra` (Small Text)) data now needs to be copied to the new field # This patch will create KRA's for all existing Appraisal Template Goal entries # keeping 140 characters as the KRA title and the whole KRA as the description # and then set the new title (140 characters) in the `key_result_area` field if not frappe.db.has_column("Appraisal Template Goal", "kra"): return template_goals = frappe.get_all( "Appraisal Template Goal", filters={"parenttype": "Appraisal Template", "key_result_area": ("is", "not set")}, fields=["name", "kra"], as_list=True, ) if len(template_goals) > 10000: frappe.db.auto_commit_on_many_writes = 1 for name, kra in template_goals: if not kra: kra = "Key Result Area" kra_title = cstr(kra).replace("\n", " ").strip()[:140] if not frappe.db.exists("KRA", kra_title): frappe.get_doc( { "doctype": "KRA", "title": kra_title, "description": kra, "name": kra_title, "owner": "Administrator", "modified_by": "Administrator", } ).db_insert() # set 140 char kra in the `key_result_area` field frappe.db.set_value( "Appraisal Template Goal", name, "key_result_area", kra_title, update_modified=False ) if frappe.db.auto_commit_on_many_writes: frappe.db.auto_commit_on_many_writes = 0 def rename_fields(): try: rename_field("Appraisal Template", "kra_title", "template_title") rename_field("Appraisal", "kra_template", "appraisal_template") except Exception as e: if e.args[0] != 1054: raise def update_kra_evaluation_method(): """ Update existing appraisals for backward compatibility - Set rate_goals_manually = True in existing Appraisals - Only new appraisals created after this patch can use the new method. """ Appraisal = frappe.qb.DocType("Appraisal") ( frappe.qb.update(Appraisal) .set(Appraisal.rate_goals_manually, 1) .where(Appraisal.appraisal_cycle.isnull()) ).run()
2302_79757062/hrms
hrms/patches/post_install/update_performance_module_changes.py
Python
agpl-3.0
2,226
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt import frappe def execute(): frappe.reload_doc("setup", "doctype", "employee") if frappe.db.has_column("Employee", "reason_for_resignation"): frappe.db.sql( """ UPDATE `tabEmployee` SET reason_for_leaving = reason_for_resignation WHERE status = 'Left' and reason_for_leaving is null and reason_for_resignation is not null """ )
2302_79757062/hrms
hrms/patches/post_install/update_reason_for_resignation_in_employee.py
Python
agpl-3.0
474
# Copyright (c) 2019, Frappe and Contributors # License: GNU General Public License v3. See license.txt import frappe def execute(): frappe.reload_doc("hr", "doctype", "shift_assignment") if frappe.db.has_column("Shift Assignment", "date"): frappe.db.sql( """update `tabShift Assignment` set end_date=date, start_date=date where date IS NOT NULL and start_date IS NULL and end_date IS NULL;""" )
2302_79757062/hrms
hrms/patches/post_install/update_start_end_date_for_old_shift_assignment.py
Python
agpl-3.0
433
# Copyright (c) 2019, Frappe and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ from frappe.model.utils.rename_field import rename_field def execute(): frappe.reload_doc("payroll", "doctype", "Salary Component Account") if frappe.db.has_column("Salary Component Account", "default_account"): rename_field("Salary Component Account", "default_account", "account") doctype_list = [ {"module": "HR", "doctype": "Employee Advance"}, {"module": "HR", "doctype": "Leave Encashment"}, {"module": "Payroll", "doctype": "Additional Salary"}, {"module": "Payroll", "doctype": "Employee Benefit Application"}, {"module": "Payroll", "doctype": "Employee Benefit Claim"}, {"module": "Payroll", "doctype": "Employee Incentive"}, {"module": "Payroll", "doctype": "Employee Tax Exemption Declaration"}, {"module": "Payroll", "doctype": "Employee Tax Exemption Proof Submission"}, {"module": "Payroll", "doctype": "Income Tax Slab"}, {"module": "Payroll", "doctype": "Payroll Entry"}, {"module": "Payroll", "doctype": "Retention Bonus"}, {"module": "Payroll", "doctype": "Salary Structure"}, {"module": "Payroll", "doctype": "Salary Structure Assignment"}, {"module": "Payroll", "doctype": "Salary Slip"}, ] for item in doctype_list: frappe.reload_doc(item["module"], "doctype", item["doctype"]) # update company in employee advance based on employee company for dt in [ "Employee Incentive", "Leave Encashment", "Employee Benefit Application", "Employee Benefit Claim", ]: frappe.db.sql( f""" update `tab{dt}` set company = (select company from tabEmployee where name=`tab{dt}`.employee) where company IS NULL """ ) # update exchange rate for employee advance frappe.db.sql("update `tabEmployee Advance` set exchange_rate=1 where exchange_rate is NULL") # get all companies and it's currency all_companies = frappe.db.get_all( "Company", fields=["name", "default_currency", "default_payroll_payable_account"] ) for d in all_companies: company = d.name company_currency = d.default_currency default_payroll_payable_account = d.default_payroll_payable_account if not default_payroll_payable_account: default_payroll_payable_account = frappe.db.get_value( "Account", { "account_name": _("Payroll Payable"), "company": company, "account_currency": company_currency, "is_group": 0, }, ) # update currency in following doctypes based on company currency doctypes_for_currency = [ "Employee Advance", "Leave Encashment", "Employee Benefit Application", "Employee Benefit Claim", "Employee Incentive", "Additional Salary", "Employee Tax Exemption Declaration", "Employee Tax Exemption Proof Submission", "Income Tax Slab", "Retention Bonus", "Salary Structure", ] for dt in doctypes_for_currency: frappe.db.sql( f"""update `tab{dt}` set currency = %s where company=%s and currency IS NULL""", (company_currency, company), ) # update fields in payroll entry frappe.db.sql( """ update `tabPayroll Entry` set currency = %s, exchange_rate = 1, payroll_payable_account=%s where company=%s and currency IS NULL """, (company_currency, default_payroll_payable_account, company), ) # update fields in Salary Structure Assignment frappe.db.sql( """ update `tabSalary Structure Assignment` set currency = %s, payroll_payable_account=%s where company=%s and currency IS NULL """, (company_currency, default_payroll_payable_account, company), ) # update fields in Salary Slip frappe.db.sql( """ update `tabSalary Slip` set currency = %s, exchange_rate = 1, base_hour_rate = hour_rate, base_gross_pay = gross_pay, base_total_deduction = total_deduction, base_net_pay = net_pay, base_rounded_total = rounded_total, base_total_in_words = total_in_words where company=%s and currency IS NULL """, (company_currency, company), )
2302_79757062/hrms
hrms/patches/post_install/updates_for_multi_currency_payroll.py
Python
agpl-3.0
4,054
import frappe def execute(): """ Add `Expense Claim` to Repost settings """ allowed_types = ["Expense Claim"] repost_settings = frappe.get_doc("Repost Accounting Ledger Settings") for x in allowed_types: repost_settings.append("allowed_types", {"document_type": x, "allowed": True}) repost_settings.save()
2302_79757062/hrms
hrms/patches/v14_0/add_expense_claim_to_repost_settings.py
Python
agpl-3.0
317
from frappe.custom.doctype.custom_field.custom_field import create_custom_field def execute(): create_custom_field( "Designation", { "fieldname": "appraisal_template", "fieldtype": "Link", "label": "Appraisal Template", "options": "Appraisal Template", "insert_after": "description", "allow_in_quick_entry": 1, }, )
2302_79757062/hrms
hrms/patches/v14_0/create_custom_field_for_appraisal_template.py
Python
agpl-3.0
344
from frappe.custom.doctype.custom_field.custom_field import create_custom_field from hrms.payroll.doctype.salary_slip.salary_slip_loan_utils import if_lending_app_installed @if_lending_app_installed def execute(): create_custom_field( "Loan Repayment", { "default": "0", "depends_on": 'eval:doc.applicant_type=="Employee"', "fieldname": "process_payroll_accounting_entry_based_on_employee", "hidden": 1, "fieldtype": "Check", "label": "Process Payroll Accounting Entry based on Employee", "insert_after": "repay_from_salary", }, )
2302_79757062/hrms
hrms/patches/v14_0/create_custom_field_in_loan.py
Python
agpl-3.0
563
import frappe def execute(): service_items = [ "Brake Oil", "Brake Pad", "Clutch Plate", "Engine Oil", "Oil Change", "Wheels", ] for item in service_items: doc = frappe.new_doc("Vehicle Service Item") doc.service_item = item doc.insert(ignore_permissions=True, ignore_if_duplicate=True)
2302_79757062/hrms
hrms/patches/v14_0/create_vehicle_service_item.py
Python
agpl-3.0
310
from hrms.setup import add_non_standard_user_types def execute(): add_non_standard_user_types()
2302_79757062/hrms
hrms/patches/v14_0/update_ess_user_access.py
Python
agpl-3.0
99
import frappe def execute(): if frappe.db.exists("Custom Field", "Loan Repayment-repay_from_salary"): frappe.db.set_value( "Custom Field", "Loan Repayment-repay_from_salary", {"fetch_from": None, "fetch_if_empty": 0}, )
2302_79757062/hrms
hrms/patches/v14_0/update_loan_repayment_repay_from_salary.py
Python
agpl-3.0
236
import frappe def execute(): salary_structure = frappe.qb.DocType("Salary Structure") frappe.qb.update(salary_structure).set(salary_structure.payroll_frequency, "").where( salary_structure.salary_slip_based_on_timesheet == 1 ).run()
2302_79757062/hrms
hrms/patches/v14_0/update_payroll_frequency_to_none_if_salary_slip_is_based_on_timesheet.py
Python
agpl-3.0
240
import frappe def execute(): if frappe.db.exists("Custom Field", {"name": "Loan Repayment-repay_from_salary"}): frappe.db.set_value("Custom Field", {"name": "Loan Repayment-repay_from_salary"}, "fetch_if_empty", 1) if frappe.db.exists("Custom Field", {"name": "Loan Repayment-payroll_payable_account"}): frappe.db.set_value( "Custom Field", {"name": "Loan Repayment-payroll_payable_account"}, "insert_after", "payment_account", )
2302_79757062/hrms
hrms/patches/v14_0/update_repay_from_salary_and_payroll_payable_account_fields.py
Python
agpl-3.0
453
import frappe def execute(): onboarding_template = frappe.qb.DocType("Employee Onboarding Template") ( frappe.qb.update(onboarding_template) .set(onboarding_template.title, onboarding_template.designation) .where(onboarding_template.title.isnull()) ).run() separation_template = frappe.qb.DocType("Employee Separation Template") ( frappe.qb.update(separation_template) .set(separation_template.title, separation_template.designation) .where(separation_template.title.isnull()) ).run()
2302_79757062/hrms
hrms/patches/v14_0/update_title_in_employee_onboarding_and_separation_templates.py
Python
agpl-3.0
506
import frappe from hrms.setup import add_lending_docperms_to_ess, update_user_type_doctype_limit def execute(): if "lending" in frappe.get_installed_apps(): update_user_type_doctype_limit() add_lending_docperms_to_ess()
2302_79757062/hrms
hrms/patches/v15_0/add_loan_docperms_to_ess.py
Python
agpl-3.0
228
import click import frappe def execute(): frappe_v = frappe.get_attr("frappe" + ".__version__") hrms_v = frappe.get_attr("hrms" + ".__version__") WIKI_URL = "https://github.com/frappe/hrms/wiki/Changes-to-branching-and-versioning" if frappe_v.startswith("14") and hrms_v.startswith("15"): message = f""" The `develop` branch of Frappe HR is no longer compatible with Frappe & ERPNext's `version-14`. Since you are using ERPNext/Frappe `version-14` please switch Frappe HR's branch to `version-14` and then proceed with the update.\n\t You can switch the branch by following the steps mentioned here: {WIKI_URL} """ click.secho(message, fg="red") frappe.throw(message) # nosemgrep
2302_79757062/hrms
hrms/patches/v15_0/check_version_compatibility_with_frappe.py
Python
agpl-3.0
708
import frappe def execute(): settings = frappe.get_single("HR Settings") settings.allow_employee_checkin_from_mobile_app = 1 settings.flags.ignore_mandatory = True settings.flags.ignore_permissions = True settings.save()
2302_79757062/hrms
hrms/patches/v15_0/enable_allow_checkin_setting.py
Python
agpl-3.0
228
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields def execute(): custom_fields = { "Company": [ { "fieldname": "hr_and_payroll_tab", "fieldtype": "Tab Break", "label": "HR & Payroll", "insert_after": "credit_limit", }, { "fieldname": "hr_settings_section", "fieldtype": "Section Break", "label": "HR & Payroll Settings", "insert_after": "hr_and_payroll_tab", }, ], } create_custom_fields(custom_fields)
2302_79757062/hrms
hrms/patches/v15_0/make_hr_settings_tab_in_company_master.py
Python
agpl-3.0
488
from frappe.model.utils.rename_field import rename_field def execute(): try: rename_field("Salary Slip Loan", "loan_type", "loan_product") except Exception as e: if e.args[0] != 1054: raise
2302_79757062/hrms
hrms/patches/v15_0/migrate_loan_type_to_loan_product.py
Python
agpl-3.0
202
import frappe from frappe import _ from frappe.desk.doctype.notification_log.notification_log import make_notification_logs from frappe.utils.user import get_system_managers def execute(): if "lending" in frappe.get_installed_apps(): return if frappe.db.a_row_exists("Salary Slip Loan"): notify_existing_users() def notify_existing_users(): subject = _("WARNING: Loan Management module has been separated from ERPNext.") + "<br>" subject += _( "If you are using loans in salary slips, please install the {0} app from Frappe Cloud Marketplace or GitHub to continue using loan integration with payroll." ).format(frappe.bold("Lending")) notification = { "subject": subject, "type": "Alert", } make_notification_logs(notification, get_system_managers(only_name=True))
2302_79757062/hrms
hrms/patches/v15_0/notify_about_loan_app_separation.py
Python
agpl-3.0
789
import frappe from frappe.model.utils.rename_field import rename_field def execute(): try: rename_field("Leave Type", "encashment_threshold_days", "non_encashable_leaves") except Exception as e: if e.args[0] != 1054: raise if not frappe.db.has_column("Leave Encashment", "encashable_days"): return # set new field values LeaveEncashment = frappe.qb.DocType("Leave Encashment") ( frappe.qb.update(LeaveEncashment) .set(LeaveEncashment.encashment_days, LeaveEncashment.encashable_days) .where(LeaveEncashment.encashment_days.isnull()) ).run() ( frappe.qb.update(LeaveEncashment) .set(LeaveEncashment.actual_encashable_days, LeaveEncashment.encashable_days) .where(LeaveEncashment.actual_encashable_days.isnull()) ).run()
2302_79757062/hrms
hrms/patches/v15_0/rename_and_update_leave_encashment_fields.py
Python
agpl-3.0
755
from frappe.model.utils.rename_field import rename_field def execute(): try: rename_field("Shift Type", "enable_entry_grace_period", "enable_late_entry_marking") rename_field("Shift Type", "enable_exit_grace_period", "enable_early_exit_marking") except Exception as e: if e.args[0] != 1054: raise
2302_79757062/hrms
hrms/patches/v15_0/rename_enable_late_entry_early_exit_grace_period.py
Python
agpl-3.0
311
import frappe def execute(): FnF = frappe.qb.DocType("Full and Final Asset") frappe.qb.update(FnF).set(FnF.action, "Return").where((FnF.action.isnull()) | (FnF.action == "")).run()
2302_79757062/hrms
hrms/patches/v15_0/set_default_asset_action_in_fnf.py
Python
agpl-3.0
185
import frappe from frappe.custom.doctype.custom_field.custom_field import create_custom_fields def execute(): custom_fields = { "Employee": [ { "fieldname": "employment_type", "fieldtype": "Link", "ignore_user_permissions": 1, "label": "Employment Type", "oldfieldname": "employment_type", "oldfieldtype": "Link", "options": "Employment Type", "insert_after": "department", }, { "fieldname": "job_applicant", "fieldtype": "Link", "label": "Job Applicant", "options": "Job Applicant", "insert_after": "employment_details", }, { "fieldname": "grade", "fieldtype": "Link", "label": "Grade", "options": "Employee Grade", "insert_after": "branch", }, { "fieldname": "default_shift", "fieldtype": "Link", "label": "Default Shift", "options": "Shift Type", "insert_after": "holiday_list", }, { "collapsible": 1, "fieldname": "health_insurance_section", "fieldtype": "Section Break", "label": "Health Insurance", "insert_after": "health_details", }, { "fieldname": "health_insurance_provider", "fieldtype": "Link", "label": "Health Insurance Provider", "options": "Employee Health Insurance", "insert_after": "health_insurance_section", }, { "depends_on": "eval:doc.health_insurance_provider", "fieldname": "health_insurance_no", "fieldtype": "Data", "label": "Health Insurance No", "insert_after": "health_insurance_provider", }, { "fieldname": "approvers_section", "fieldtype": "Section Break", "label": "Approvers", "insert_after": "default_shift", }, { "fieldname": "expense_approver", "fieldtype": "Link", "label": "Expense Approver", "options": "User", "insert_after": "approvers_section", }, { "fieldname": "leave_approver", "fieldtype": "Link", "label": "Leave Approver", "options": "User", "insert_after": "expense_approver", }, { "fieldname": "column_break_45", "fieldtype": "Column Break", "insert_after": "leave_approver", }, { "fieldname": "shift_request_approver", "fieldtype": "Link", "label": "Shift Request Approver", "options": "User", "insert_after": "column_break_45", }, { "fieldname": "salary_cb", "fieldtype": "Column Break", "insert_after": "salary_mode", }, { "fetch_from": "department.payroll_cost_center", "fetch_if_empty": 1, "fieldname": "payroll_cost_center", "fieldtype": "Link", "label": "Payroll Cost Center", "options": "Cost Center", "insert_after": "salary_cb", }, ], } if frappe.db.exists("Company", {"country": "India"}): custom_fields["Employee"].extend( [ { "fieldname": "bank_cb", "fieldtype": "Column Break", "insert_after": "bank_ac_no", }, { "fieldname": "ifsc_code", "label": "IFSC Code", "fieldtype": "Data", "insert_after": "bank_cb", "print_hide": 1, "depends_on": 'eval:doc.salary_mode == "Bank"', "translatable": 0, }, { "fieldname": "pan_number", "label": "PAN Number", "fieldtype": "Data", "insert_after": "payroll_cost_center", "print_hide": 1, "translatable": 0, }, { "fieldname": "micr_code", "label": "MICR Code", "fieldtype": "Data", "insert_after": "ifsc_code", "print_hide": 1, "depends_on": 'eval:doc.salary_mode == "Bank"', "translatable": 0, }, { "fieldname": "provident_fund_account", "label": "Provident Fund Account", "fieldtype": "Data", "insert_after": "pan_number", "translatable": 0, }, ] ) create_custom_fields(custom_fields)
2302_79757062/hrms
hrms/patches/v1_0/rearrange_employee_fields.py
Python
agpl-3.0
3,754
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Additional Salary", { setup: function (frm) { frm.add_fetch( "salary_component", "deduct_full_tax_on_selected_payroll_date", "deduct_full_tax_on_selected_payroll_date", ); frm.set_query("employee", function () { return { filters: { company: frm.doc.company, status: ["!=", "Inactive"], }, }; }); }, onload: function (frm) { if (frm.doc.type) { frm.trigger("set_component_query"); } }, employee: function (frm) { if (frm.doc.employee) { frappe.run_serially([ () => frm.trigger("get_employee_currency"), () => frm.trigger("set_company"), ]); } else { frm.set_value("company", null); } }, set_company: function (frm) { frappe.call({ method: "frappe.client.get_value", args: { doctype: "Employee", fieldname: "company", filters: { name: frm.doc.employee, }, }, callback: function (data) { if (data.message) { frm.set_value("company", data.message.company); } }, }); }, company: function (frm) { frm.set_value("type", ""); frm.trigger("set_component_query"); }, set_component_query: function (frm) { if (!frm.doc.company) return; let filters = { company: frm.doc.company }; if (frm.doc.type) { filters.type = frm.doc.type; } frm.set_query("salary_component", function () { return { filters: filters, }; }); }, 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/payroll/doctype/additional_salary/additional_salary.js
JavaScript
agpl-3.0
1,882
# 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 comma_and, date_diff, formatdate, get_link_to_form, getdate from hrms.hr.utils import validate_active_employee class AdditionalSalary(Document): def on_submit(self): self.update_return_amount_in_employee_advance() self.update_employee_referral() def on_cancel(self): self.update_return_amount_in_employee_advance() self.update_employee_referral(cancel=True) def validate(self): validate_active_employee(self.employee) self.validate_dates() self.validate_salary_structure() self.validate_recurring_additional_salary_overlap() self.validate_employee_referral() self.validate_duplicate_additional_salary() self.validate_tax_component_overwrite() if self.amount < 0: frappe.throw(_("Amount should not be less than zero")) def validate_salary_structure(self): if not frappe.db.exists("Salary Structure Assignment", {"employee": self.employee}): frappe.throw( _("There is no Salary Structure assigned to {0}. First assign a Salary Stucture.").format( self.employee ) ) def validate_recurring_additional_salary_overlap(self): if self.is_recurring: AdditionalSalary = frappe.qb.DocType("Additional Salary") additional_salaries = ( frappe.qb.from_(AdditionalSalary) .select(AdditionalSalary.name) .where( (AdditionalSalary.employee == self.employee) & (AdditionalSalary.name != self.name) & (AdditionalSalary.docstatus == 1) & (AdditionalSalary.is_recurring == 1) & (AdditionalSalary.salary_component == self.salary_component) & (AdditionalSalary.to_date >= self.from_date) & (AdditionalSalary.from_date <= self.to_date) & (AdditionalSalary.disabled == 0) ) ).run(pluck=True) if additional_salaries and len(additional_salaries): frappe.throw( _( "Additional Salary: {0} already exist for Salary Component: {1} for period {2} and {3}" ).format( bold(comma_and(additional_salaries)), bold(self.salary_component), bold(formatdate(self.from_date)), bold(formatdate(self.to_date)), ) ) def validate_dates(self): date_of_joining, relieving_date = frappe.db.get_value( "Employee", self.employee, ["date_of_joining", "relieving_date"] ) self.validate_from_to_dates("from_date", "to_date") if date_of_joining: if self.payroll_date and getdate(self.payroll_date) < getdate(date_of_joining): frappe.throw(_("Payroll date can not be less than employee's joining date.")) elif self.from_date and getdate(self.from_date) < getdate(date_of_joining): frappe.throw(_("From date can not be less than employee's joining date.")) if relieving_date: if self.to_date and getdate(self.to_date) > getdate(relieving_date): frappe.throw(_("To date can not be greater than employee's relieving date.")) if self.payroll_date and getdate(self.payroll_date) > getdate(relieving_date): frappe.throw(_("Payroll date can not be greater than employee's relieving date.")) def validate_employee_referral(self): if self.ref_doctype == "Employee Referral": referral_details = frappe.db.get_value( "Employee Referral", self.ref_docname, ["is_applicable_for_referral_bonus", "status"], as_dict=1, ) if not referral_details.is_applicable_for_referral_bonus: frappe.throw( _("Employee Referral {0} is not applicable for referral bonus.").format(self.ref_docname) ) if self.type == "Deduction": frappe.throw(_("Earning Salary Component is required for Employee Referral Bonus.")) if referral_details.status != "Accepted": frappe.throw( _( "Additional Salary for referral bonus can only be created against Employee Referral with status {0}" ).format(frappe.bold(_("Accepted"))) ) def validate_duplicate_additional_salary(self): if not self.overwrite_salary_structure_amount: return existing_additional_salary = frappe.db.exists( "Additional Salary", { "name": ["!=", self.name], "salary_component": self.salary_component, "payroll_date": self.payroll_date, "overwrite_salary_structure_amount": 1, "employee": self.employee, "docstatus": 1, }, ) if existing_additional_salary: msg = _( "Additional Salary for this salary component with {0} enabled already exists for this date" ).format(frappe.bold(_("Overwrite Salary Structure Amount"))) msg += "<br><br>" msg += _("Reference: {0}").format( get_link_to_form("Additional Salary", existing_additional_salary) ) frappe.throw(msg, title=_("Duplicate Overwritten Salary")) def validate_tax_component_overwrite(self): if not frappe.db.get_value( "Salary Component", self.salary_component, "variable_based_on_taxable_salary" ): return if self.overwrite_salary_structure_amount: frappe.msgprint( _( "This will overwrite the tax component {0} in the salary slip and tax won't be calculated based on the Income Tax Slabs" ).format(frappe.bold(self.salary_component)), title=_("Warning"), indicator="orange", ) else: msg = _("{0} has {1} enabled").format( get_link_to_form("Salary Component", self.salary_component), frappe.bold(_("Variable Based On Taxable Salary")), ) msg += "<br><br>" + _( "To overwrite the salary component amount for a tax component, please enable {0}" ).format(frappe.bold(_("Overwrite Salary Structure Amount"))) frappe.throw(msg, title=_("Invalid Additional Salary")) def update_return_amount_in_employee_advance(self): if self.ref_doctype == "Employee Advance" and self.ref_docname: return_amount = frappe.db.get_value("Employee Advance", self.ref_docname, "return_amount") if self.docstatus == 2: return_amount -= self.amount else: return_amount += self.amount frappe.db.set_value("Employee Advance", self.ref_docname, "return_amount", return_amount) advance = frappe.get_doc("Employee Advance", self.ref_docname) advance.set_status(update=True) def update_employee_referral(self, cancel=False): if self.ref_doctype == "Employee Referral": status = "Unpaid" if cancel else "Paid" frappe.db.set_value("Employee Referral", self.ref_docname, "referral_payment_status", status) def get_amount(self, sal_start_date, sal_end_date): start_date = getdate(sal_start_date) end_date = getdate(sal_end_date) total_days = date_diff(getdate(self.to_date), getdate(self.from_date)) + 1 amount_per_day = self.amount / total_days if getdate(sal_start_date) <= getdate(self.from_date): start_date = getdate(self.from_date) if getdate(sal_end_date) > getdate(self.to_date): end_date = getdate(self.to_date) no_of_days = date_diff(getdate(end_date), getdate(start_date)) + 1 return amount_per_day * no_of_days def validate_update_after_submit(self): if not self.disabled: self.validate_recurring_additional_salary_overlap() def get_additional_salaries(employee, start_date, end_date, component_type): from frappe.query_builder import Criterion comp_type = "Earning" if component_type == "earnings" else "Deduction" additional_sal = frappe.qb.DocType("Additional Salary") component_field = additional_sal.salary_component.as_("component") overwrite_field = additional_sal.overwrite_salary_structure_amount.as_("overwrite") additional_salary_list = ( frappe.qb.from_(additional_sal) .select( additional_sal.name, component_field, additional_sal.type, additional_sal.amount, additional_sal.is_recurring, overwrite_field, additional_sal.deduct_full_tax_on_selected_payroll_date, ) .where( (additional_sal.employee == employee) & (additional_sal.docstatus == 1) & (additional_sal.type == comp_type) & (additional_sal.disabled == 0) ) .where( Criterion.any( [ Criterion.all( [ # is recurring and additional salary dates fall within the payroll period additional_sal.is_recurring == 1, additional_sal.from_date <= end_date, additional_sal.to_date >= end_date, ] ), Criterion.all( [ # is not recurring and additional salary's payroll date falls within the payroll period additional_sal.is_recurring == 0, additional_sal.payroll_date[start_date:end_date], ] ), ] ) ) .run(as_dict=True) ) additional_salaries = [] components_to_overwrite = [] for d in additional_salary_list: if d.overwrite: if d.component in components_to_overwrite: frappe.throw( _( "Multiple Additional Salaries with overwrite property exist for Salary Component {0} between {1} and {2}." ).format(frappe.bold(d.component), start_date, end_date), title=_("Error"), ) components_to_overwrite.append(d.component) additional_salaries.append(d) return additional_salaries
2302_79757062/hrms
hrms/payroll/doctype/additional_salary/additional_salary.py
Python
agpl-3.0
8,987
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Bulk Salary Structure Assignment", { setup(frm) { frm.trigger("set_queries"); hrms.setup_employee_filter_group(frm); }, async refresh(frm) { frm.page.clear_indicator(); frm.disable_save(); frm.trigger("set_primary_action"); await frm.trigger("set_payroll_payable_account"); frm.trigger("get_employees"); hrms.handle_realtime_bulk_action_notification( frm, "completed_bulk_salary_structure_assignment", "Salary Structure Assignment", ); }, from_date(frm) { frm.trigger("get_employees"); }, async company(frm) { await frm.trigger("set_payroll_payable_account"); frm.trigger("get_employees"); }, branch(frm) { frm.trigger("get_employees"); }, department(frm) { frm.trigger("get_employees"); }, employment_type(frm) { frm.trigger("get_employees"); }, designation(frm) { frm.trigger("get_employees"); }, grade(frm) { frm.trigger("get_employees"); }, set_primary_action(frm) { frm.page.set_primary_action(__("Assign Structure"), () => { frm.trigger("assign_structure"); }); }, set_queries(frm) { frm.set_query("salary_structure", function () { return { filters: { company: frm.doc.company, is_active: "Yes", docstatus: 1, }, }; }); frm.set_query("income_tax_slab", function () { return { filters: { company: frm.doc.company, disabled: 0, docstatus: 1, currency: frm.doc.currency, }, }; }); frm.set_query("payroll_payable_account", function () { const company_currency = erpnext.get_currency(frm.doc.company); return { filters: { company: frm.doc.company, root_type: "Liability", is_group: 0, account_currency: ["in", [frm.doc.currency, company_currency]], }, }; }); }, set_payroll_payable_account(frm) { frappe.db.get_value("Company", frm.doc.company, "default_payroll_payable_account", (r) => { frm.set_value("payroll_payable_account", r.default_payroll_payable_account); }); }, get_employees(frm) { if (!frm.doc.from_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) { frm.checked_rows_indexes = []; const columns = frm.events.get_employees_datatable_columns(); const no_data_message = __( frm.doc.from_date ? "There are no employees without a Salary Structure Assignment on this date based on the given filters." : "Please select From Date.", ); const get_editor = (colIndex, rowIndex, value, parent, column) => { if (!["base", "variable"].includes(column.name)) return; const $input = document.createElement("input"); $input.className = "dt-input h-100"; $input.type = "number"; $input.min = 0; parent.appendChild($input); return { initValue(value) { $input.focus(); $input.value = value; }, setValue(value) { $input.value = value; }, getValue() { return Number($input.value); }, }; }; const events = { onCheckRow() { frm.trigger("handle_row_check"); }, }; hrms.render_employees_datatable( frm, columns, employees, no_data_message, get_editor, events, ); }, get_employees_datatable_columns() { return [ { name: "employee", id: "employee", content: __("Employee"), editable: false, focusable: false, }, { name: "employee_name", id: "employee_name", content: __("Name"), editable: false, focusable: false, }, { name: "grade", id: "grade", content: __("Grade"), editable: false, focusable: false, }, { name: "base", id: "base", content: __("Base"), }, { name: "variable", id: "variable", content: __("Variable"), }, ].map((x) => ({ ...x, dropdown: false, align: "left", })); }, render_update_button(frm) { ["Base", "Variable"].forEach((d) => frm.add_custom_button( __(d), function () { const dialog = new frappe.ui.Dialog({ title: __("Set {0} for selected employees", [__(d)]), fields: [ { label: __(d), fieldname: d, fieldtype: "Currency", }, ], primary_action_label: __("Update"), primary_action(values) { const col_idx = frm.employees_datatable.datamanager.columns.find( (col) => col.content === d, ).colIndex; frm.checked_rows_indexes.forEach((row_idx) => { frm.employees_datatable.cellmanager.updateCell( col_idx, row_idx, values[d], true, ); }); dialog.hide(); }, }); dialog.show(); }, __("Update"), ), ); frm.update_button_rendered = true; }, handle_row_check(frm) { frm.checked_rows_indexes = frm.employees_datatable.rowmanager.getCheckedRows(); if (!frm.checked_rows_indexes.length && frm.update_button_rendered) { ["Base", "Variable"].forEach((d) => frm.remove_custom_button(__(d), __("Update"))); frm.update_button_rendered = false; } else if (frm.checked_rows_indexes.length && !frm.update_button_rendered) frm.trigger("render_update_button"); }, assign_structure(frm) { const rows = frm.employees_datatable.getRows(); const checked_rows_content = []; const employees_with_base_zero = []; frm.checked_rows_indexes.forEach((idx) => { const row_content = {}; rows[idx].forEach((cell) => { if (["employee", "base", "variable"].includes(cell.column.name)) row_content[cell.column.name] = cell.content; }); checked_rows_content.push(row_content); if (!row_content["base"]) employees_with_base_zero.push(`<b>${row_content["employee"]}</b>`); }); hrms.validate_mandatory_fields(frm, checked_rows_content); if (employees_with_base_zero.length) return frm.events.validate_base_zero( frm, employees_with_base_zero, checked_rows_content, ); return frm.events.show_confirm_dialog(frm, checked_rows_content); }, validate_base_zero(frm, employees_with_base_zero, checked_rows_content) { frappe.warn( __("Are you sure you want to proceed?"), __("<b>Base</b> amount has not been set for the following employee(s): {0}", [ employees_with_base_zero.join(", "), ]), () => { frm.events.show_confirm_dialog(frm, checked_rows_content); }, __("Continue"), ); }, show_confirm_dialog(frm, checked_rows_content) { frappe.confirm( __("Assign Salary Structure to {0} employee(s)?", [checked_rows_content.length]), () => { frm.events.bulk_assign_structure(frm, checked_rows_content); }, ); }, bulk_assign_structure(frm, employees) { frm.call({ method: "bulk_assign_structure", doc: frm.doc, args: { employees: employees, }, freeze: true, freeze_message: __("Assigning Salary Structure"), }); }, });
2302_79757062/hrms
hrms/payroll/doctype/bulk_salary_structure_assignment/bulk_salary_structure_assignment.js
JavaScript
agpl-3.0
7,130
# Copyright (c) 2024, 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.custom import ConstantColumn from frappe.query_builder.functions import Coalesce from frappe.query_builder.terms import SubQuery from frappe.utils import get_link_to_form from hrms.hr.utils import validate_bulk_tool_fields from hrms.payroll.doctype.salary_structure.salary_structure import ( create_salary_structure_assignment, ) class BulkSalaryStructureAssignment(Document): @frappe.whitelist() def get_employees(self, advanced_filters: list) -> list: quick_filter_fields = [ "company", "employment_type", "branch", "department", "designation", "grade", ] filters = [[d, "=", self.get(d)] for d in quick_filter_fields if self.get(d)] filters += advanced_filters Assignment = frappe.qb.DocType("Salary Structure Assignment") employees_with_assignments = SubQuery( frappe.qb.from_(Assignment) .select(Assignment.employee) .distinct() .where((Assignment.from_date == self.from_date) & (Assignment.docstatus == 1)) ) Employee = frappe.qb.DocType("Employee") Grade = frappe.qb.DocType("Employee Grade") query = ( frappe.qb.get_query( Employee, fields=[Employee.employee, Employee.employee_name, Employee.grade], filters=filters, ) .where( (Employee.status == "Active") & (Employee.date_of_joining <= self.from_date) & ((Employee.relieving_date > self.from_date) | (Employee.relieving_date.isnull())) & (Employee.employee.notin(employees_with_assignments)) ) .left_join(Grade) .on(Employee.grade == Grade.name) .select( Coalesce(Grade.default_base_pay, 0).as_("base"), ConstantColumn(0).as_("variable"), ) ) return query.run(as_dict=True) @frappe.whitelist() def bulk_assign_structure(self, employees: list) -> None: mandatory_fields = ["salary_structure", "from_date", "company"] validate_bulk_tool_fields(self, mandatory_fields, employees) if len(employees) <= 30: return self._bulk_assign_structure(employees) frappe.enqueue(self._bulk_assign_structure, timeout=3000, employees=employees) frappe.msgprint( _("Creation of Salary Structure Assignments has been queued. It may take a few minutes."), alert=True, indicator="blue", ) def _bulk_assign_structure(self, employees: list) -> None: success, failure = [], [] count = 0 savepoint = "before_salary_assignment" for d in employees: try: frappe.db.savepoint(savepoint) assignment = create_salary_structure_assignment( employee=d["employee"], salary_structure=self.salary_structure, company=self.company, currency=self.currency, payroll_payable_account=self.payroll_payable_account, from_date=self.from_date, base=d["base"], variable=d["variable"], income_tax_slab=self.income_tax_slab, ) except Exception: frappe.db.rollback(save_point=savepoint) frappe.log_error( f"Bulk Assignment - Salary Structure Assignment failed for employee {d['employee']}.", reference_doctype="Salary Structure Assignment", ) failure.append(d["employee"]) else: success.append( { "doc": get_link_to_form("Salary Structure Assignment", assignment), "employee": d["employee"], } ) count += 1 frappe.publish_progress(count * 100 / len(employees), title=_("Assigning Structure...")) frappe.publish_realtime( "completed_bulk_salary_structure_assignment", message={"success": success, "failure": failure}, doctype="Bulk Salary Structure Assignment", after_commit=True, )
2302_79757062/hrms
hrms/payroll/doctype/bulk_salary_structure_assignment/bulk_salary_structure_assignment.py
Python
agpl-3.0
3,723
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Benefit Application", { employee: function (frm) { if (frm.doc.employee) { frappe.run_serially([ () => frm.trigger("get_employee_currency"), () => frm.trigger("set_earning_component"), ]); } var method, args; if (frm.doc.employee && frm.doc.date && frm.doc.payroll_period) { method = "hrms.payroll.doctype.employee_benefit_application.employee_benefit_application.get_max_benefits_remaining"; args = { employee: frm.doc.employee, on_date: frm.doc.date, payroll_period: frm.doc.payroll_period, }; get_max_benefits(frm, method, args); } else if (frm.doc.employee && frm.doc.date) { method = "hrms.payroll.doctype.employee_benefit_application.employee_benefit_application.get_max_benefits"; args = { employee: frm.doc.employee, on_date: frm.doc.date, }; get_max_benefits(frm, method, args); } }, date: function (frm) { frm.trigger("set_earning_component"); }, set_earning_component: function (frm) { if (!frm.doc.employee && !frm.doc.date) return; frm.set_query("earning_component", "employee_benefits", function () { return { query: "hrms.payroll.doctype.employee_benefit_application.employee_benefit_application.get_earning_components", filters: { date: frm.doc.date, employee: frm.doc.employee }, }; }); }, get_employee_currency: function (frm) { if (frm.doc.employee) { 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(); } }, }); } }, payroll_period: function (frm) { var method, args; if (frm.doc.employee && frm.doc.date && frm.doc.payroll_period) { method = "hrms.payroll.doctype.employee_benefit_application.employee_benefit_application.get_max_benefits_remaining"; args = { employee: frm.doc.employee, on_date: frm.doc.date, payroll_period: frm.doc.payroll_period, }; get_max_benefits(frm, method, args); } }, max_benefits: function (frm) { calculate_all(frm.doc); }, }); var get_max_benefits = function (frm, method, args) { frappe.call({ method: method, args: args, callback: function (data) { if (!data.exc) { if (data.message) { frm.set_value("max_benefits", data.message); } else { frm.set_value("max_benefits", 0); } } frm.refresh_fields(); }, }); }; frappe.ui.form.on("Employee Benefit Application Detail", { amount: function (frm) { calculate_all(frm.doc); }, employee_benefits_remove: function (frm) { calculate_all(frm.doc); }, }); var calculate_all = function (doc) { var tbl = doc.employee_benefits || []; var pro_rata_dispensed_amount = 0; var total_amount = 0; if (doc.max_benefits === 0) { doc.employee_benefits = []; } else { for (var i = 0; i < tbl.length; i++) { if (cint(tbl[i].amount) > 0) { total_amount += flt(tbl[i].amount); } if (tbl[i].pay_against_benefit_claim != 1) { pro_rata_dispensed_amount += flt(tbl[i].amount); } } } doc.total_amount = total_amount; doc.remaining_benefit = doc.max_benefits - total_amount; doc.pro_rata_dispensed_amount = pro_rata_dispensed_amount; refresh_many(["pro_rata_dispensed_amount", "total_amount", "remaining_benefit"]); };
2302_79757062/hrms
hrms/payroll/doctype/employee_benefit_application/employee_benefit_application.js
JavaScript
agpl-3.0
3,552
# 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 add_days, cstr, date_diff, flt, getdate, rounded from hrms.hr.utils import ( get_holiday_dates_for_employee, get_previous_claimed_amount, get_sal_slip_total_benefit_given, validate_active_employee, ) from hrms.payroll.doctype.payroll_period.payroll_period import ( get_payroll_period_days, get_period_factor, ) from hrms.payroll.doctype.salary_structure_assignment.salary_structure_assignment import ( get_assigned_salary_structure, ) class EmployeeBenefitApplication(Document): def validate(self): validate_active_employee(self.employee) self.validate_duplicate_on_payroll_period() if not self.max_benefits: self.max_benefits = flt( get_max_benefits_remaining(self.employee, self.date, self.payroll_period), self.precision("max_benefits"), ) if self.max_benefits and self.max_benefits > 0: self.validate_max_benefit_for_component() self.validate_prev_benefit_claim() if self.remaining_benefit and self.remaining_benefit > 0: self.validate_remaining_benefit_amount() else: frappe.throw( _("As per your assigned Salary Structure you cannot apply for benefits").format(self.employee) ) def validate_prev_benefit_claim(self): if self.employee_benefits: for benefit in self.employee_benefits: if benefit.pay_against_benefit_claim == 1: payroll_period = frappe.get_doc("Payroll Period", self.payroll_period) benefit_claimed = get_previous_claimed_amount( self.employee, payroll_period, component=benefit.earning_component ) benefit_given = get_sal_slip_total_benefit_given( self.employee, payroll_period, component=benefit.earning_component ) benefit_claim_remining = benefit_claimed - benefit_given if benefit_claimed > 0 and benefit_claim_remining > benefit.amount: frappe.throw( _( "An amount of {0} already claimed for the component {1}, set the amount equal or greater than {2}" ).format(benefit_claimed, benefit.earning_component, benefit_claim_remining) ) def validate_remaining_benefit_amount(self): # check salary structure earnings have flexi component (sum of max_benefit_amount) # without pro-rata which satisfy the remaining_benefit # else pro-rata component for the amount # again comes the same validation and satisfy or throw benefit_components = [] if self.employee_benefits: for employee_benefit in self.employee_benefits: benefit_components.append(employee_benefit.earning_component) salary_struct_name = get_assigned_salary_structure(self.employee, self.date) if salary_struct_name: non_pro_rata_amount = 0 pro_rata_amount = 0 salary_structure = frappe.get_doc("Salary Structure", salary_struct_name) if salary_structure.earnings: for earnings in salary_structure.earnings: if ( earnings.is_flexible_benefit == 1 and earnings.salary_component not in benefit_components ): pay_against_benefit_claim, max_benefit_amount = frappe.db.get_value( "Salary Component", earnings.salary_component, ["pay_against_benefit_claim", "max_benefit_amount"], ) if pay_against_benefit_claim != 1: pro_rata_amount += max_benefit_amount else: non_pro_rata_amount += max_benefit_amount if pro_rata_amount == 0 and non_pro_rata_amount == 0: frappe.throw( _("Please add the remaining benefits {0} to any of the existing component").format( self.remaining_benefit ) ) elif non_pro_rata_amount > 0 and non_pro_rata_amount < rounded(self.remaining_benefit): frappe.throw( _( "You can claim only an amount of {0}, the rest amount {1} should be in the application as pro-rata component" ).format(non_pro_rata_amount, self.remaining_benefit - non_pro_rata_amount) ) elif non_pro_rata_amount == 0: frappe.throw( _( "Please add the remaining benefits {0} to the application as pro-rata component" ).format(self.remaining_benefit) ) def validate_max_benefit_for_component(self): if self.employee_benefits: max_benefit_amount = 0 for employee_benefit in self.employee_benefits: self.validate_max_benefit(employee_benefit.earning_component) max_benefit_amount += flt(employee_benefit.amount) if max_benefit_amount > self.max_benefits: frappe.throw( _("Maximum benefit amount of employee {0} exceeds {1}").format( self.employee, self.max_benefits ) ) def validate_max_benefit(self, earning_component_name): max_benefit_amount = frappe.db.get_value( "Salary Component", earning_component_name, "max_benefit_amount" ) benefit_amount = 0 for employee_benefit in self.employee_benefits: if employee_benefit.earning_component == earning_component_name: benefit_amount += flt(employee_benefit.amount) prev_sal_slip_flexi_amount = get_sal_slip_total_benefit_given( self.employee, frappe.get_doc("Payroll Period", self.payroll_period), earning_component_name ) benefit_amount += prev_sal_slip_flexi_amount if rounded(benefit_amount, 2) > max_benefit_amount: frappe.throw( _("Maximum benefit amount of component {0} exceeds {1}").format( earning_component_name, max_benefit_amount ) ) def validate_duplicate_on_payroll_period(self): application = frappe.db.exists( "Employee Benefit Application", {"employee": self.employee, "payroll_period": self.payroll_period, "docstatus": 1}, ) if application: frappe.throw( _("Employee {0} already submitted an application {1} for the payroll period {2}").format( self.employee, application, self.payroll_period ) ) @frappe.whitelist() def get_max_benefits(employee, on_date): sal_struct = get_assigned_salary_structure(employee, on_date) if sal_struct: max_benefits = frappe.db.get_value("Salary Structure", sal_struct, "max_benefits", cache=True) if max_benefits > 0: return max_benefits return 0 @frappe.whitelist() def get_max_benefits_remaining(employee, on_date, payroll_period): max_benefits = get_max_benefits(employee, on_date) if max_benefits and max_benefits > 0: have_depends_on_payment_days = False per_day_amount_total = 0 payroll_period_days = get_payroll_period_days(on_date, on_date, employee)[1] payroll_period_obj = frappe.get_doc("Payroll Period", payroll_period) # Get all salary slip flexi amount in the payroll period prev_sal_slip_flexi_total = get_sal_slip_total_benefit_given(employee, payroll_period_obj) if prev_sal_slip_flexi_total > 0: # Check salary structure hold depends_on_payment_days component # If yes then find the amount per day of each component and find the sum sal_struct_name = get_assigned_salary_structure(employee, on_date) if sal_struct_name: sal_struct = frappe.get_doc("Salary Structure", sal_struct_name) for sal_struct_row in sal_struct.get("earnings"): salary_component = frappe.get_doc("Salary Component", sal_struct_row.salary_component) if ( salary_component.depends_on_payment_days == 1 and salary_component.pay_against_benefit_claim != 1 ): have_depends_on_payment_days = True benefit_amount = get_benefit_amount_based_on_pro_rata( sal_struct, salary_component.max_benefit_amount ) amount_per_day = benefit_amount / payroll_period_days per_day_amount_total += amount_per_day # Then the sum multiply with the no of lwp in that period # Include that amount to the prev_sal_slip_flexi_total to get the actual if have_depends_on_payment_days and per_day_amount_total > 0: holidays = get_holiday_dates_for_employee(employee, payroll_period_obj.start_date, on_date) working_days = date_diff(on_date, payroll_period_obj.start_date) + 1 leave_days = calculate_lwp(employee, payroll_period_obj.start_date, holidays, working_days) leave_days_amount = leave_days * per_day_amount_total prev_sal_slip_flexi_total += leave_days_amount return max_benefits - prev_sal_slip_flexi_total return max_benefits def calculate_lwp(employee, start_date, holidays, working_days): lwp = 0 holidays = "','".join(holidays) for d in range(working_days): date = add_days(cstr(getdate(start_date)), d) LeaveApplication = frappe.qb.DocType("Leave Application") LeaveType = frappe.qb.DocType("Leave Type") is_half_day = ( frappe.qb.terms.Case() .when( ( (LeaveApplication.half_day_date == date) | (LeaveApplication.from_date == LeaveApplication.to_date) ), LeaveApplication.half_day, ) .else_(0) ).as_("is_half_day") query = ( frappe.qb.from_(LeaveApplication) .inner_join(LeaveType) .on(LeaveType.name == LeaveApplication.leave_type) .select(LeaveApplication.name, is_half_day) .where( (LeaveType.is_lwp == 1) & (LeaveApplication.docstatus == 1) & (LeaveApplication.status == "Approved") & (LeaveApplication.employee == employee) & ((LeaveApplication.from_date <= date) & (date <= LeaveApplication.to_date)) ) ) # if it's a holiday only include if leave type has "include holiday" enabled if date in holidays: query = query.where(LeaveType.include_holiday == "1") leaves = query.run(as_dict=True) if leaves: lwp += 0.5 if leaves[0].is_half_day else 1 return lwp def get_benefit_component_amount( employee, start_date, end_date, salary_component, sal_struct, payroll_frequency, payroll_period ): if not payroll_period: frappe.msgprint( _("Start and end dates not in a valid Payroll Period, cannot calculate {0}").format( salary_component ) ) return False # Considering there is only one application for a year benefit_application = frappe.db.sql( """ select name from `tabEmployee Benefit Application` where payroll_period=%(payroll_period)s and employee=%(employee)s and docstatus = 1 """, {"employee": employee, "payroll_period": payroll_period.name}, ) current_benefit_amount = 0.0 component_max_benefit, depends_on_payment_days = frappe.db.get_value( "Salary Component", salary_component, ["max_benefit_amount", "depends_on_payment_days"] ) benefit_amount = 0 if benefit_application: benefit_amount = frappe.db.get_value( "Employee Benefit Application Detail", {"parent": benefit_application[0][0], "earning_component": salary_component}, "amount", ) elif component_max_benefit: benefit_amount = get_benefit_amount_based_on_pro_rata(sal_struct, component_max_benefit) current_benefit_amount = 0 if benefit_amount: total_sub_periods = get_period_factor( employee, start_date, end_date, payroll_frequency, payroll_period, depends_on_payment_days )[0] current_benefit_amount = benefit_amount / total_sub_periods return current_benefit_amount def get_benefit_amount_based_on_pro_rata(sal_struct, component_max_benefit): max_benefits_total = 0 benefit_amount = 0 for d in sal_struct.get("earnings"): if d.is_flexible_benefit == 1: component = frappe.db.get_value( "Salary Component", d.salary_component, ["max_benefit_amount", "pay_against_benefit_claim"], as_dict=1, ) if not component.pay_against_benefit_claim: max_benefits_total += component.max_benefit_amount if max_benefits_total > 0: benefit_amount = sal_struct.max_benefits * component.max_benefit_amount / max_benefits_total if benefit_amount > component_max_benefit: benefit_amount = component_max_benefit return benefit_amount @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def get_earning_components(doctype, txt, searchfield, start, page_len, filters): if len(filters) < 2: return {} salary_structure = get_assigned_salary_structure(filters["employee"], filters["date"]) if salary_structure: return frappe.db.sql( """ select salary_component from `tabSalary Detail` where parent = %s and is_flexible_benefit = 1 order by name """, salary_structure, ) else: frappe.throw( _("Salary Structure not found for employee {0} and date {1}").format( filters["employee"], filters["date"] ) ) @frappe.whitelist() def get_earning_components_max_benefits(employee, date, earning_component): salary_structure = get_assigned_salary_structure(employee, date) amount = frappe.db.sql( """ select amount from `tabSalary Detail` where parent = %s and is_flexible_benefit = 1 and salary_component = %s order by name """, salary_structure, earning_component, ) return amount if amount else 0
2302_79757062/hrms
hrms/payroll/doctype/employee_benefit_application/employee_benefit_application.py
Python
agpl-3.0
12,662
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class EmployeeBenefitApplicationDetail(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/employee_benefit_application_detail/employee_benefit_application_detail.py
Python
agpl-3.0
238
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Benefit Claim", { setup: function (frm) { frm.set_query("earning_component", function () { return { query: "hrms.payroll.doctype.employee_benefit_application.employee_benefit_application.get_earning_components", filters: { date: frm.doc.claim_date, employee: frm.doc.employee }, }; }); }, employee: function (frm) { frm.set_value("earning_component", null); if (frm.doc.employee) { 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); } }, }); } if (!frm.doc.earning_component) { frm.doc.max_amount_eligible = null; frm.doc.claimed_amount = null; } frm.refresh_fields(); }, });
2302_79757062/hrms
hrms/payroll/doctype/employee_benefit_claim/employee_benefit_claim.js
JavaScript
agpl-3.0
1,005
# 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 flt from hrms.hr.utils import get_previous_claimed_amount, validate_active_employee from hrms.payroll.doctype.employee_benefit_application.employee_benefit_application import ( get_max_benefits, ) from hrms.payroll.doctype.payroll_period.payroll_period import get_payroll_period from hrms.payroll.doctype.salary_structure_assignment.salary_structure_assignment import ( get_assigned_salary_structure, ) class EmployeeBenefitClaim(Document): def validate(self): validate_active_employee(self.employee) max_benefits = get_max_benefits(self.employee, self.claim_date) if not max_benefits or max_benefits <= 0: frappe.throw(_("Employee {0} has no maximum benefit amount").format(self.employee)) payroll_period = get_payroll_period( self.claim_date, self.claim_date, frappe.db.get_value("Employee", self.employee, "company") ) if not payroll_period: frappe.throw( _("{0} is not in a valid Payroll Period").format( frappe.format(self.claim_date, dict(fieldtype="Date")) ) ) self.validate_max_benefit_for_component(payroll_period) self.validate_max_benefit_for_sal_struct(max_benefits) self.validate_benefit_claim_amount(max_benefits, payroll_period) if self.pay_against_benefit_claim: self.validate_non_pro_rata_benefit_claim(max_benefits, payroll_period) def validate_benefit_claim_amount(self, max_benefits, payroll_period): claimed_amount = self.claimed_amount claimed_amount += get_previous_claimed_amount(self.employee, payroll_period) if max_benefits < claimed_amount: frappe.throw( _( "Maximum benefit of employee {0} exceeds {1} by the sum {2} of previous claimed amount" ).format(self.employee, max_benefits, claimed_amount - max_benefits) ) def validate_max_benefit_for_sal_struct(self, max_benefits): if self.claimed_amount > max_benefits: frappe.throw( _("Maximum benefit amount of employee {0} exceeds {1}").format(self.employee, max_benefits) ) def validate_max_benefit_for_component(self, payroll_period): if self.max_amount_eligible: claimed_amount = self.claimed_amount claimed_amount += get_previous_claimed_amount( self.employee, payroll_period, component=self.earning_component ) if claimed_amount > self.max_amount_eligible: frappe.throw( _("Maximum amount eligible for the component {0} exceeds {1}").format( self.earning_component, self.max_amount_eligible ) ) def validate_non_pro_rata_benefit_claim(self, max_benefits, payroll_period): claimed_amount = self.claimed_amount pro_rata_amount = self.get_pro_rata_amount_in_application(payroll_period.name) if not pro_rata_amount: pro_rata_amount = 0 # Get pro_rata_amount if there is no application, # get salary structure for the date and calculate pro-rata amount sal_struct_name = get_assigned_salary_structure(self.employee, self.claim_date) if sal_struct_name: sal_struct = frappe.get_doc("Salary Structure", sal_struct_name) pro_rata_amount = get_benefit_pro_rata_ratio_amount( self.employee, self.claim_date, sal_struct ) claimed_amount += get_previous_claimed_amount(self.employee, payroll_period, non_pro_rata=True) if max_benefits < pro_rata_amount + claimed_amount: frappe.throw( _( "Maximum benefit of employee {0} exceeds {1} by the sum {2} of benefit application pro-rata component amount and previous claimed amount" ).format(self.employee, max_benefits, pro_rata_amount + claimed_amount - max_benefits) ) def get_pro_rata_amount_in_application(self, payroll_period): application = frappe.db.exists( "Employee Benefit Application", {"employee": self.employee, "payroll_period": payroll_period, "docstatus": 1}, ) if application: return frappe.db.get_value( "Employee Benefit Application", application, "pro_rata_dispensed_amount" ) return False def get_benefit_pro_rata_ratio_amount(employee, on_date, sal_struct): total_pro_rata_max = 0 benefit_amount_total = 0 for sal_struct_row in sal_struct.get("earnings"): try: pay_against_benefit_claim, max_benefit_amount = frappe.get_cached_value( "Salary Component", sal_struct_row.salary_component, ["pay_against_benefit_claim", "max_benefit_amount"], ) except TypeError: # show the error in tests? frappe.throw(_("Unable to find Salary Component {0}").format(sal_struct_row.salary_component)) if sal_struct_row.is_flexible_benefit == 1 and pay_against_benefit_claim != 1: total_pro_rata_max += max_benefit_amount if total_pro_rata_max > 0: for sal_struct_row in sal_struct.get("earnings"): pay_against_benefit_claim, max_benefit_amount = frappe.get_cached_value( "Salary Component", sal_struct_row.salary_component, ["pay_against_benefit_claim", "max_benefit_amount"], ) if sal_struct_row.is_flexible_benefit == 1 and pay_against_benefit_claim != 1: component_max = max_benefit_amount benefit_amount = component_max * sal_struct.max_benefits / total_pro_rata_max if benefit_amount > component_max: benefit_amount = component_max benefit_amount_total += benefit_amount return benefit_amount_total def get_benefit_claim_amount(employee, start_date, end_date, salary_component=None): query = """ select sum(claimed_amount) from `tabEmployee Benefit Claim` where employee=%(employee)s and docstatus = 1 and pay_against_benefit_claim = 1 and claim_date between %(start_date)s and %(end_date)s """ if salary_component: query += " and earning_component = %(earning_component)s" claimed_amount = flt( frappe.db.sql( query, { "employee": employee, "start_date": start_date, "end_date": end_date, "earning_component": salary_component, }, )[0][0] ) return claimed_amount def get_total_benefit_dispensed(employee, sal_struct, sal_slip_start_date, payroll_period): pro_rata_amount = 0 claimed_amount = 0 application = frappe.db.exists( "Employee Benefit Application", {"employee": employee, "payroll_period": payroll_period.name, "docstatus": 1}, ) if application: application_obj = frappe.get_cached_value( "Employee Benefit Application", application, ["pro_rata_dispensed_amount", "max_benefits", "remaining_benefit"], as_dict=True, ) pro_rata_amount = ( application_obj.pro_rata_dispensed_amount + application_obj.max_benefits - application_obj.remaining_benefit ) else: pro_rata_amount = get_benefit_pro_rata_ratio_amount(employee, sal_slip_start_date, sal_struct) claimed_amount += get_benefit_claim_amount(employee, payroll_period.start_date, payroll_period.end_date) return claimed_amount + pro_rata_amount def get_last_payroll_period_benefits( employee, sal_slip_start_date, sal_slip_end_date, payroll_period, sal_struct ): if sal_struct: max_benefits = sal_struct.max_benefits else: max_benefits = get_max_benefits(employee, payroll_period.end_date) remaining_benefit = max_benefits - get_total_benefit_dispensed( employee, sal_struct, sal_slip_start_date, payroll_period ) if remaining_benefit > 0: have_remaining = True # Set the remaining benefits to flexi non pro-rata component in the salary structure salary_components_array = [] for d in sal_struct.get("earnings"): if d.is_flexible_benefit == 1: salary_component = frappe.get_cached_doc("Salary Component", d.salary_component) if salary_component.pay_against_benefit_claim == 1: claimed_amount = get_benefit_claim_amount( employee, payroll_period.start_date, sal_slip_end_date, d.salary_component ) amount_fit_to_component = salary_component.max_benefit_amount - claimed_amount if amount_fit_to_component > 0: if remaining_benefit > amount_fit_to_component: amount = amount_fit_to_component remaining_benefit -= amount_fit_to_component else: amount = remaining_benefit have_remaining = False current_claimed_amount = get_benefit_claim_amount( employee, sal_slip_start_date, sal_slip_end_date, d.salary_component ) amount += current_claimed_amount struct_row = {} salary_components_dict = {} struct_row["depends_on_payment_days"] = salary_component.depends_on_payment_days struct_row["salary_component"] = salary_component.name struct_row["abbr"] = salary_component.salary_component_abbr struct_row["do_not_include_in_total"] = salary_component.do_not_include_in_total struct_row["is_tax_applicable"] = (salary_component.is_tax_applicable,) struct_row["is_flexible_benefit"] = (salary_component.is_flexible_benefit,) struct_row["variable_based_on_taxable_salary"] = ( salary_component.variable_based_on_taxable_salary ) salary_components_dict["amount"] = amount salary_components_dict["struct_row"] = struct_row salary_components_array.append(salary_components_dict) if not have_remaining: break if len(salary_components_array) > 0: return salary_components_array return False
2302_79757062/hrms
hrms/payroll/doctype/employee_benefit_claim/employee_benefit_claim.py
Python
agpl-3.0
9,231
# 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 EmployeeCostCenter(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/employee_cost_center/employee_cost_center.py
Python
agpl-3.0
223
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Incentive", { setup: function (frm) { frm.set_query("employee", function () { return { filters: { status: "Active", }, }; }); frm.trigger("set_earning_component"); }, employee: function (frm) { if (frm.doc.employee) { frappe.run_serially([ () => frm.trigger("get_employee_currency"), () => frm.trigger("set_company"), ]); } else { frm.set_value("company", null); } }, set_company: function (frm) { frappe.call({ method: "frappe.client.get_value", args: { doctype: "Employee", fieldname: "company", filters: { name: frm.doc.employee, }, }, callback: function (data) { if (data.message) { frm.set_value("company", data.message.company); frm.trigger("set_earning_component"); } }, }); }, set_earning_component: function (frm) { if (!frm.doc.company) return; frm.set_query("salary_component", function () { return { filters: { type: "earning", company: frm.doc.company }, }; }); }, 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/payroll/doctype/employee_incentive/employee_incentive.js
JavaScript
agpl-3.0
1,526
# 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 hrms.hr.utils import validate_active_employee class EmployeeIncentive(Document): def validate(self): validate_active_employee(self.employee) self.validate_salary_structure() def validate_salary_structure(self): if not frappe.db.exists("Salary Structure Assignment", {"employee": self.employee}): frappe.throw( _("There is no Salary Structure assigned to {0}. First assign a Salary Stucture.").format( self.employee ) ) def on_submit(self): company = frappe.db.get_value("Employee", self.employee, "company") additional_salary = frappe.new_doc("Additional Salary") additional_salary.employee = self.employee additional_salary.currency = self.currency additional_salary.salary_component = self.salary_component additional_salary.overwrite_salary_structure_amount = 0 additional_salary.amount = self.incentive_amount additional_salary.payroll_date = self.payroll_date additional_salary.company = company additional_salary.ref_doctype = self.doctype additional_salary.ref_docname = self.name additional_salary.submit()
2302_79757062/hrms
hrms/payroll/doctype/employee_incentive/employee_incentive.py
Python
agpl-3.0
1,277
// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Other Income", { // refresh: function(frm) { // } });
2302_79757062/hrms
hrms/payroll/doctype/employee_other_income/employee_other_income.js
JavaScript
agpl-3.0
206
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class EmployeeOtherIncome(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/employee_other_income/employee_other_income.py
Python
agpl-3.0
225
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Tax Exemption Category", { refresh: function (frm) {}, });
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_category/employee_tax_exemption_category.js
JavaScript
agpl-3.0
210
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from frappe.model.document import Document class EmployeeTaxExemptionCategory(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_category/employee_tax_exemption_category.py
Python
agpl-3.0
218
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Tax Exemption Declaration", { setup: function (frm) { frm.set_query("employee", function () { return { filters: { status: "Active", }, }; }); frm.set_query("payroll_period", function () { const fields = { employee: "Employee", company: "Company" }; for (let [field, label] of Object.entries(fields)) { if (!frm.doc[field]) { frappe.msgprint(__("Please select {0}", [label])); } } if (frm.doc.employee && frm.doc.company) { return { filters: { company: frm.doc.company, }, }; } }); frm.set_query("exemption_sub_category", "declarations", function () { return { filters: { is_active: 1, }, }; }); }, refresh: function (frm) { if (frm.doc.docstatus == 1) { frm.add_custom_button(__("Submit Proof"), function () { frappe.model.open_mapped_doc({ method: "hrms.payroll.doctype.employee_tax_exemption_declaration.employee_tax_exemption_declaration.make_proof_submission", frm: frm, }); }).addClass("btn-primary"); } }, employee: function (frm) { if (frm.doc.employee) { frm.trigger("get_employee_currency"); } }, 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/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.js
JavaScript
agpl-3.0
1,670
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from frappe.utils import flt from hrms.hr.utils import ( calculate_annual_eligible_hra_exemption, get_total_exemption_amount, validate_active_employee, validate_duplicate_exemption_for_payroll_period, validate_tax_declaration, ) class EmployeeTaxExemptionDeclaration(Document): def validate(self): validate_active_employee(self.employee) validate_tax_declaration(self.declarations) validate_duplicate_exemption_for_payroll_period( self.doctype, self.name, self.payroll_period, self.employee ) self.set_total_declared_amount() self.set_total_exemption_amount() self.calculate_hra_exemption() def set_total_declared_amount(self): self.total_declared_amount = 0.0 for d in self.declarations: self.total_declared_amount += flt(d.amount) def set_total_exemption_amount(self): self.total_exemption_amount = flt( get_total_exemption_amount(self.declarations), self.precision("total_exemption_amount") ) def calculate_hra_exemption(self): self.salary_structure_hra, self.annual_hra_exemption, self.monthly_hra_exemption = 0, 0, 0 if self.get("monthly_house_rent"): hra_exemption = calculate_annual_eligible_hra_exemption(self) if hra_exemption: self.total_exemption_amount += hra_exemption["annual_exemption"] self.total_exemption_amount = flt( self.total_exemption_amount, self.precision("total_exemption_amount") ) self.salary_structure_hra = flt( hra_exemption["hra_amount"], self.precision("salary_structure_hra") ) self.annual_hra_exemption = flt( hra_exemption["annual_exemption"], self.precision("annual_hra_exemption") ) self.monthly_hra_exemption = flt( hra_exemption["monthly_exemption"], self.precision("monthly_hra_exemption") ) @frappe.whitelist() def make_proof_submission(source_name, target_doc=None): doclist = get_mapped_doc( "Employee Tax Exemption Declaration", source_name, { "Employee Tax Exemption Declaration": { "doctype": "Employee Tax Exemption Proof Submission", "field_no_map": ["monthly_house_rent", "monthly_hra_exemption"], }, "Employee Tax Exemption Declaration Category": { "doctype": "Employee Tax Exemption Proof Submission Detail", "add_if_empty": True, }, }, target_doc, ) return doclist
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.py
Python
agpl-3.0
2,499