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) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class EmployeeTaxExemptionDeclarationCategory(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_declaration_category/employee_tax_exemption_declaration_category.py
Python
agpl-3.0
245
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Tax Exemption Proof Submission", { setup: function (frm) { frm.set_query("employee", function () { return { filters: { status: "Active", }, }; }); frm.set_query("payroll_period", function () { if (frm.doc.employee && frm.doc.company) { return { filters: { company: frm.doc.company, }, }; } else { frappe.msgprint(__("Please select Employee")); } }); frm.set_query("exemption_sub_category", "tax_exemption_proofs", function () { return { filters: { is_active: 1, }, }; }); }, refresh: function (frm) { // hide attachments section in new forms in favor of the Attach Proof button against each proof frm.toggle_display("attachments", frm.doc.attachments ? 1 : 0); if (frm.doc.docstatus === 0) { let filters = { docstatus: 1, company: frm.doc.company, }; if (frm.doc.employee) filters["employee"] = frm.doc.employee; if (frm.doc.payroll_period) filters["payroll_period"] = frm.doc.payroll_period; frm.add_custom_button(__("Get Details From Declaration"), function () { erpnext.utils.map_current_doc({ method: "hrms.payroll.doctype.employee_tax_exemption_declaration.employee_tax_exemption_declaration.make_proof_submission", source_doctype: "Employee Tax Exemption Declaration", target: frm, date_field: "creation", setters: { employee: frm.doc.employee || undefined, }, get_query_filters: filters, }); }); } }, currency: function (frm) { frm.refresh_fields(); }, 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_proof_submission/employee_tax_exemption_proof_submission.js
JavaScript
agpl-3.0
2,163
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from frappe.model.document import Document from frappe.utils import flt from hrms.hr.utils import ( calculate_hra_exemption_for_period, get_total_exemption_amount, validate_active_employee, validate_duplicate_exemption_for_payroll_period, validate_tax_declaration, ) class EmployeeTaxExemptionProofSubmission(Document): def validate(self): validate_active_employee(self.employee) validate_tax_declaration(self.tax_exemption_proofs) self.set_total_actual_amount() self.set_total_exemption_amount() self.calculate_hra_exemption() validate_duplicate_exemption_for_payroll_period( self.doctype, self.name, self.payroll_period, self.employee ) def set_total_actual_amount(self): self.total_actual_amount = flt(self.get("house_rent_payment_amount")) for d in self.tax_exemption_proofs: self.total_actual_amount += flt(d.amount) def set_total_exemption_amount(self): self.exemption_amount = flt( get_total_exemption_amount(self.tax_exemption_proofs), self.precision("exemption_amount") ) def calculate_hra_exemption(self): self.monthly_hra_exemption, self.monthly_house_rent, self.total_eligible_hra_exemption = 0, 0, 0 if self.get("house_rent_payment_amount"): hra_exemption = calculate_hra_exemption_for_period(self) if hra_exemption: self.exemption_amount += hra_exemption["total_eligible_hra_exemption"] self.exemption_amount = flt(self.exemption_amount, self.precision("exemption_amount")) self.monthly_hra_exemption = flt( hra_exemption["monthly_exemption"], self.precision("monthly_hra_exemption") ) self.monthly_house_rent = flt( hra_exemption["monthly_house_rent"], self.precision("monthly_house_rent") ) self.total_eligible_hra_exemption = flt( hra_exemption["total_eligible_hra_exemption"], self.precision("total_eligible_hra_exemption"), )
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.py
Python
agpl-3.0
1,974
# 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 EmployeeTaxExemptionProofSubmissionDetail(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_proof_submission_detail/employee_tax_exemption_proof_submission_detail.py
Python
agpl-3.0
247
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee Tax Exemption Sub Category", { refresh: function (frm) {}, });
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_sub_category/employee_tax_exemption_sub_category.js
JavaScript
agpl-3.0
214
# 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 class EmployeeTaxExemptionSubCategory(Document): def validate(self): category_max_amount = frappe.db.get_value( "Employee Tax Exemption Category", self.exemption_category, "max_amount" ) if flt(self.max_amount) > flt(category_max_amount): frappe.throw( _( "Max Exemption Amount cannot be greater than maximum exemption amount {0} of Tax Exemption Category {1}" ).format(category_max_amount, self.exemption_category) )
2302_79757062/hrms
hrms/payroll/doctype/employee_tax_exemption_sub_category/employee_tax_exemption_sub_category.py
Python
agpl-3.0
677
// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Gratuity", { setup: function (frm) { frm.set_query("salary_component", function () { return { filters: { type: "Earning", }, }; }); frm.set_query("expense_account", function () { return { filters: { root_type: "Expense", is_group: 0, company: frm.doc.company, }, }; }); frm.set_query("payable_account", function () { return { filters: { root_type: "Liability", is_group: 0, company: frm.doc.company, }, }; }); }, refresh: function (frm) { if (frm.doc.docstatus == 1 && !frm.doc.pay_via_salary_slip && frm.doc.status == "Unpaid") { frm.add_custom_button(__("Create Payment Entry"), function () { return frappe.call({ method: "hrms.overrides.employee_payment_entry.get_payment_entry_for_employee", args: { dt: frm.doc.doctype, dn: frm.doc.name, }, callback: function (r) { var doclist = frappe.model.sync(r.message); frappe.set_route("Form", doclist[0].doctype, doclist[0].name); }, }); }); } }, employee: function (frm) { frm.events.calculate_work_experience_and_amount(frm); }, gratuity_rule: function (frm) { frm.events.calculate_work_experience_and_amount(frm); }, calculate_work_experience_and_amount: function (frm) { if (frm.doc.employee && frm.doc.gratuity_rule) { frm.call("calculate_work_experience_and_amount").then((r) => { frm.set_value("current_work_experience", r.message["current_work_experience"]); frm.set_value("amount", r.message["amount"]); }); } }, });
2302_79757062/hrms
hrms/payroll/doctype/gratuity/gratuity.js
JavaScript
agpl-3.0
1,707
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from math import floor import frappe from frappe import _, bold from frappe.query_builder.functions import Sum from frappe.utils import cstr, flt, get_datetime, get_link_to_form from erpnext.accounts.general_ledger import make_gl_entries from erpnext.controllers.accounts_controller import AccountsController class Gratuity(AccountsController): def validate(self): data = self.calculate_work_experience_and_amount() self.current_work_experience = data["current_work_experience"] self.amount = data["amount"] self.set_status() @property def gratuity_settings(self): if not hasattr(self, "_gratuity_settings"): self._gratuity_settings = frappe.db.get_value( "Gratuity Rule", self.gratuity_rule, [ "work_experience_calculation_function as method", "total_working_days_per_year", "minimum_year_for_gratuity", "calculate_gratuity_amount_based_on", ], as_dict=True, ) return self._gratuity_settings def set_status(self, update=False): status = {"0": "Draft", "1": "Submitted", "2": "Cancelled"}[cstr(self.docstatus or 0)] if self.docstatus == 1: precision = self.precision("paid_amount") if flt(self.paid_amount) > 0 and flt(self.amount, precision) == flt(self.paid_amount, precision): status = "Paid" else: status = "Unpaid" if update: self.db_set("status", status) else: self.status = status def on_submit(self): if self.pay_via_salary_slip: self.create_additional_salary() else: self.create_gl_entries() def on_cancel(self): self.ignore_linked_doctypes = ["GL Entry"] self.create_gl_entries(cancel=True) self.set_status(update=True) def create_gl_entries(self, cancel=False): gl_entries = self.get_gl_entries() make_gl_entries(gl_entries, cancel) def get_gl_entries(self): gl_entry = [] # payable entry if self.amount: gl_entry.append( self.get_gl_dict( { "account": self.payable_account, "credit": self.amount, "credit_in_account_currency": self.amount, "against": self.expense_account, "party_type": "Employee", "party": self.employee, "against_voucher_type": self.doctype, "against_voucher": self.name, "cost_center": self.cost_center, }, item=self, ) ) # expense entries gl_entry.append( self.get_gl_dict( { "account": self.expense_account, "debit": self.amount, "debit_in_account_currency": self.amount, "against": self.payable_account, "cost_center": self.cost_center, }, item=self, ) ) else: frappe.throw(_("Total Amount cannot be zero")) return gl_entry def create_additional_salary(self): if self.pay_via_salary_slip: additional_salary = frappe.new_doc("Additional Salary") additional_salary.employee = self.employee additional_salary.salary_component = self.salary_component additional_salary.overwrite_salary_structure_amount = 0 additional_salary.amount = self.amount additional_salary.payroll_date = self.payroll_date additional_salary.company = self.company additional_salary.ref_doctype = self.doctype additional_salary.ref_docname = self.name additional_salary.submit() def set_total_advance_paid(self): gle = frappe.qb.DocType("GL Entry") paid_amount = ( frappe.qb.from_(gle) .select(Sum(gle.debit_in_account_currency).as_("paid_amount")) .where( (gle.against_voucher_type == "Gratuity") & (gle.against_voucher == self.name) & (gle.party_type == "Employee") & (gle.party == self.employee) & (gle.docstatus == 1) & (gle.is_cancelled == 0) ) ).run(as_dict=True)[0].paid_amount or 0 if flt(paid_amount) > self.amount: frappe.throw(_("Row {0}# Paid Amount cannot be greater than Total amount")) self.db_set("paid_amount", paid_amount) self.set_status(update=True) @frappe.whitelist() def calculate_work_experience_and_amount(self) -> dict: if self.gratuity_settings.method == "Manual": current_work_experience = flt(self.current_work_experience) else: current_work_experience = self.get_work_experience() gratuity_amount = self.get_gratuity_amount(current_work_experience) return {"current_work_experience": current_work_experience, "amount": gratuity_amount} def get_work_experience(self) -> float: total_working_days = self.get_total_working_days() rule = self.gratuity_settings work_experience = total_working_days / (rule.total_working_days_per_year or 1) if rule.method == "Round off Work Experience": work_experience = round(work_experience) else: work_experience = floor(work_experience) if work_experience < rule.minimum_year_for_gratuity: frappe.throw( _("Employee: {0} have to complete minimum {1} years for gratuity").format( bold(self.employee), rule.minimum_year_for_gratuity ) ) return work_experience or 0 def get_total_working_days(self) -> float: date_of_joining, relieving_date = frappe.db.get_value( "Employee", self.employee, ["date_of_joining", "relieving_date"] ) if not relieving_date: frappe.throw( _("Please set Relieving Date for employee: {0}").format( bold(get_link_to_form("Employee", self.employee)) ) ) total_working_days = (get_datetime(relieving_date) - get_datetime(date_of_joining)).days payroll_based_on = frappe.db.get_single_value("Payroll Settings", "payroll_based_on") or "Leave" if payroll_based_on == "Leave": total_lwp = self.get_non_working_days(relieving_date, "On Leave") total_working_days -= total_lwp elif payroll_based_on == "Attendance": total_absent = self.get_non_working_days(relieving_date, "Absent") total_working_days -= total_absent return total_working_days def get_non_working_days(self, relieving_date: str, status: str) -> float: filters = { "docstatus": 1, "status": status, "employee": self.employee, "attendance_date": ("<=", get_datetime(relieving_date)), } if status == "On Leave": lwp_leave_types = frappe.get_all("Leave Type", filters={"is_lwp": 1}, pluck="name") filters["leave_type"] = ("IN", lwp_leave_types) record = frappe.get_all("Attendance", filters=filters, fields=["COUNT(*) as total_lwp"]) return record[0].total_lwp if len(record) else 0 def get_gratuity_amount(self, experience: float) -> float: total_component_amount = self.get_total_component_amount() calculate_amount_based_on = self.gratuity_settings.calculate_gratuity_amount_based_on gratuity_amount = 0 slabs = self.get_gratuity_rule_slabs() slab_found = False years_left = experience for slab in slabs: if calculate_amount_based_on == "Current Slab": if self._is_experience_within_slab(slab, experience): gratuity_amount = ( total_component_amount * experience * slab.fraction_of_applicable_earnings ) if slab.fraction_of_applicable_earnings: slab_found = True if slab_found: break elif calculate_amount_based_on == "Sum of all previous slabs": # no slabs, fraction applicable for all years if slab.to_year == 0 and slab.from_year == 0: gratuity_amount += ( years_left * total_component_amount * slab.fraction_of_applicable_earnings ) slab_found = True break # completed more years than the current slab, so consider fraction for current slab too if self._is_experience_beyond_slab(slab, experience): gratuity_amount += ( (slab.to_year - slab.from_year) * total_component_amount * slab.fraction_of_applicable_earnings ) years_left -= slab.to_year - slab.from_year slab_found = True elif self._is_experience_within_slab(slab, experience): gratuity_amount += ( years_left * total_component_amount * slab.fraction_of_applicable_earnings ) slab_found = True if not slab_found: frappe.throw( _( "No applicable slab found for the calculation of gratuity amount as per the Gratuity Rule: {0}" ).format(bold(self.gratuity_rule)) ) return flt(gratuity_amount, self.precision("amount")) def get_total_component_amount(self) -> float: applicable_earning_components = self.get_applicable_components() salary_slip = get_last_salary_slip(self.employee) if not salary_slip: frappe.throw(_("No Salary Slip found for Employee: {0}").format(bold(self.employee))) # consider full payment days for calculation as last month's salary slip # might have less payment days as per attendance, making it non-deterministic salary_slip.payment_days = salary_slip.total_working_days salary_slip.calculate_net_pay() total_amount = 0 component_found = False for row in salary_slip.earnings: if row.salary_component in applicable_earning_components: total_amount += flt(row.amount) component_found = True if not component_found: frappe.throw( _("No applicable Earning component found in last salary slip for Gratuity Rule: {0}").format( bold(get_link_to_form("Gratuity Rule", self.gratuity_rule)) ) ) return total_amount def get_applicable_components(self) -> list[str]: applicable_earning_components = frappe.get_all( "Gratuity Applicable Component", filters={"parent": self.gratuity_rule}, pluck="salary_component" ) if not applicable_earning_components: frappe.throw( _("No applicable Earning components found for Gratuity Rule: {0}").format( bold(get_link_to_form("Gratuity Rule", self.gratuity_rule)) ) ) return applicable_earning_components def get_gratuity_rule_slabs(self) -> list[dict]: return frappe.get_all( "Gratuity Rule Slab", filters={"parent": self.gratuity_rule}, fields=["from_year", "to_year", "fraction_of_applicable_earnings"], order_by="idx", ) def _is_experience_within_slab(self, slab: dict, experience: float) -> bool: return bool(slab.from_year <= experience and (experience < slab.to_year or slab.to_year == 0)) def _is_experience_beyond_slab(self, slab: dict, experience: float) -> bool: return bool(slab.from_year < experience and (slab.to_year < experience and slab.to_year != 0)) def get_last_salary_slip(employee: str) -> dict | None: salary_slip = frappe.db.get_value( "Salary Slip", {"employee": employee, "docstatus": 1}, order_by="start_date desc" ) if salary_slip: return frappe.get_doc("Salary Slip", salary_slip)
2302_79757062/hrms
hrms/payroll/doctype/gratuity/gratuity.py
Python
agpl-3.0
10,449
from frappe import _ def get_data(): return { "fieldname": "reference_name", "non_standard_fieldnames": { "Additional Salary": "ref_docname", }, "transactions": [{"label": _("Payment"), "items": ["Payment Entry", "Additional Salary"]}], }
2302_79757062/hrms
hrms/payroll/doctype/gratuity/gratuity_dashboard.py
Python
agpl-3.0
254
frappe.listview_settings["Gratuity"] = { get_indicator: function (doc) { let status_color = { Draft: "red", Submitted: "blue", Cancelled: "red", Paid: "green", Unpaid: "orange", }; return [__(doc.status), status_color[doc.status], "status,=," + doc.status]; }, };
2302_79757062/hrms
hrms/payroll/doctype/gratuity/gratuity_list.js
JavaScript
agpl-3.0
287
# 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 GratuityApplicableComponent(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/gratuity_applicable_component/gratuity_applicable_component.py
Python
agpl-3.0
233
// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Gratuity Rule", { // refresh: function(frm) { // } }); frappe.ui.form.on("Gratuity Rule Slab", { /* Slabs should be in order like from | to | fraction 0 | 4 | 0.5 4 | 6 | 0.7 So, on row addition setting current_row.from = previous row.to. On to_year insert we have to check that it is not less than from_year Wrong order may lead to Wrong Calculation */ gratuity_rule_slabs_add(frm, cdt, cdn) { let row = locals[cdt][cdn]; let array_idx = row.idx - 1; if (array_idx > 0) { row.from_year = cur_frm.doc.gratuity_rule_slabs[array_idx - 1].to_year; frm.refresh(); } }, to_year(frm, cdt, cdn) { let row = locals[cdt][cdn]; if (row.to_year <= row.from_year && row.to_year === 0) { frappe.throw(__("To(Year) year can not be less than From(year)")); } }, });
2302_79757062/hrms
hrms/payroll/doctype/gratuity_rule/gratuity_rule.js
JavaScript
agpl-3.0
951
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.model.document import Document class GratuityRule(Document): def validate(self): for current_slab in self.gratuity_rule_slabs: if (current_slab.from_year > current_slab.to_year) and current_slab.to_year != 0: frappe.throw( _("Row {0}: From (Year) can not be greater than To (Year)").format(current_slab.idx) ) if ( current_slab.to_year == 0 and current_slab.from_year == 0 and len(self.gratuity_rule_slabs) > 1 ): frappe.throw( _("You can not define multiple slabs if you have a slab with no lower and upper limits.") ) def get_gratuity_rule(name, slabs, **args): args = frappe._dict(args) rule = frappe.new_doc("Gratuity Rule") rule.name = name rule.calculate_gratuity_amount_based_on = args.calculate_gratuity_amount_based_on or "Current Slab" rule.work_experience_calculation_method = ( args.work_experience_calculation_method or "Take Exact Completed Years" ) rule.minimum_year_for_gratuity = 1 for slab in slabs: slab = frappe._dict(slab) rule.append("gratuity_rule_slabs", slab) return rule
2302_79757062/hrms
hrms/payroll/doctype/gratuity_rule/gratuity_rule.py
Python
agpl-3.0
1,237
from frappe import _ def get_data(): return { "fieldname": "gratuity_rule", "transactions": [{"label": _("Gratuity"), "items": ["Gratuity"]}], }
2302_79757062/hrms
hrms/payroll/doctype/gratuity_rule/gratuity_rule_dashboard.py
Python
agpl-3.0
153
# 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 GratuityRuleSlab(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/gratuity_rule_slab/gratuity_rule_slab.py
Python
agpl-3.0
222
// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Income Tax Slab", { refresh: function (frm) { if (frm.doc.docstatus != 1) return; frm.add_custom_button( __("Salary Structure Assignment"), () => { frappe.model.with_doctype("Salary Structure Assignment", () => { const doc = frappe.model.get_new_doc("Salary Structure Assignment"); doc.income_tax_slab = frm.doc.name; frappe.set_route("Form", "Salary Structure Assignment", doc.name); }); }, __("Create"), ); frm.page.set_inner_btn_group_as_primary(__("Create")); }, currency: function (frm) { frm.refresh_fields(); }, });
2302_79757062/hrms
hrms/payroll/doctype/income_tax_slab/income_tax_slab.js
JavaScript
agpl-3.0
714
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from frappe.model.document import Document # import frappe import erpnext class IncomeTaxSlab(Document): def validate(self): if self.company: self.currency = erpnext.get_company_currency(self.company)
2302_79757062/hrms
hrms/payroll/doctype/income_tax_slab/income_tax_slab.py
Python
agpl-3.0
331
# 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 IncomeTaxSlabOtherCharges(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/income_tax_slab_other_charges/income_tax_slab_other_charges.py
Python
agpl-3.0
231
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from frappe.model.document import Document class PayrollEmployeeDetail(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/payroll_employee_detail/payroll_employee_detail.py
Python
agpl-3.0
211
// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt var in_progress = false; frappe.provide("erpnext.accounts.dimensions"); frappe.ui.form.on("Payroll Entry", { onload: function (frm) { frm.ignore_doctypes_on_cancel_all = ["Salary Slip", "Journal Entry"]; if (!frm.doc.posting_date) { frm.doc.posting_date = frappe.datetime.nowdate(); } frm.toggle_reqd(["payroll_frequency"], !frm.doc.salary_slip_based_on_timesheet); erpnext.accounts.dimensions.setup_dimension_filters(frm, frm.doctype); frm.events.department_filters(frm); frm.events.payroll_payable_account_filters(frm); frappe.realtime.off("completed_salary_slip_creation"); frappe.realtime.on("completed_salary_slip_creation", function () { frm.reload_doc(); }); frappe.realtime.off("completed_salary_slip_submission"); frappe.realtime.on("completed_salary_slip_submission", function () { frm.reload_doc(); }); }, department_filters: function (frm) { frm.set_query("department", function () { return { filters: { company: frm.doc.company, }, }; }); }, payroll_payable_account_filters: function (frm) { frm.set_query("payroll_payable_account", function () { return { filters: { company: frm.doc.company, root_type: "Liability", is_group: 0, }, }; }); }, refresh: function (frm) { if (frm.doc.status === "Queued") frm.page.btn_secondary.hide(); if (frm.doc.docstatus === 0 && !frm.is_new()) { frm.page.clear_primary_action(); frm.add_custom_button(__("Get Employees"), function () { frm.events.get_employee_details(frm); }).toggleClass("btn-primary", !(frm.doc.employees || []).length); } if ( (frm.doc.employees || []).length && !frappe.model.has_workflow(frm.doctype) && !cint(frm.doc.salary_slips_created) && frm.doc.docstatus != 2 ) { if (frm.doc.docstatus == 0 && !frm.is_new()) { frm.page.clear_primary_action(); frm.page.set_primary_action(__("Create Salary Slips"), () => { frm.save("Submit").then(() => { frm.page.clear_primary_action(); frm.refresh(); }); }); } else if (frm.doc.docstatus == 1 && frm.doc.status == "Failed") { frm.add_custom_button(__("Create Salary Slips"), function () { frm.call("create_salary_slips"); }).addClass("btn-primary"); } } if (frm.doc.docstatus == 1) { if (frm.custom_buttons) frm.clear_custom_buttons(); frm.events.add_context_buttons(frm); } if (frm.doc.status == "Failed" && frm.doc.error_message) { const issue = `<a id="jump_to_error" style="text-decoration: underline;">issue</a>`; let process = cint(frm.doc.salary_slips_created) ? "submission" : "creation"; frm.dashboard.set_headline( __("Salary Slip {0} failed. You can resolve the {1} and retry {0}.", [ process, issue, ]), ); $("#jump_to_error").on("click", (e) => { e.preventDefault(); frm.scroll_to_field("error_message"); }); } }, get_employee_details: function (frm) { return frappe .call({ doc: frm.doc, method: "fill_employee_details", freeze: true, freeze_message: __("Fetching Employees"), }) .then((r) => { if (r.docs?.[0]?.employees) { frm.dirty(); frm.save(); } frm.refresh(); if (r.docs?.[0]?.validate_attendance) { render_employee_attendance(frm, r.message); } frm.scroll_to_field("employees"); }); }, create_salary_slips: function (frm) { frm.call({ doc: frm.doc, method: "run_doc_method", args: { method: "create_salary_slips", dt: "Payroll Entry", dn: frm.doc.name, }, }); }, add_context_buttons: function (frm) { if ( frm.doc.salary_slips_submitted || (frm.doc.__onload && frm.doc.__onload.submitted_ss) ) { frm.events.add_bank_entry_button(frm); } else if (frm.doc.salary_slips_created && frm.doc.status !== "Queued") { frm.add_custom_button(__("Submit Salary Slip"), function () { submit_salary_slip(frm); }).addClass("btn-primary"); } else if (!frm.doc.salary_slips_created && frm.doc.status === "Failed") { frm.add_custom_button(__("Create Salary Slips"), function () { frm.trigger("create_salary_slips"); }).addClass("btn-primary"); } }, add_bank_entry_button: function (frm) { frm.call("has_bank_entries").then((r) => { if (!r.message.has_bank_entries) { frm.add_custom_button(__("Make Bank Entry"), function () { make_bank_entry(frm); }).addClass("btn-primary"); } else if (!r.message.has_bank_entries_for_withheld_salaries) { frm.add_custom_button(__("Release Withheld Salaries"), function () { make_bank_entry(frm, (for_withheld_salaries = 1)); }).addClass("btn-primary"); } }); }, setup: function (frm) { frm.add_fetch("company", "cost_center", "cost_center"); frm.set_query("payment_account", function () { var account_types = ["Bank", "Cash"]; return { filters: { account_type: ["in", account_types], is_group: 0, company: frm.doc.company, }, }; }); frm.set_query("employee", "employees", () => { let error_fields = []; let mandatory_fields = ["company", "payroll_frequency", "start_date", "end_date"]; let message = __("Mandatory fields required in {0}", [__(frm.doc.doctype)]); mandatory_fields.forEach((field) => { if (!frm.doc[field]) { error_fields.push(frappe.unscrub(field)); } }); if (error_fields && error_fields.length) { message = message + "<br><br><ul><li>" + error_fields.join("</li><li>") + "</ul>"; frappe.throw({ message: message, indicator: "red", title: __("Missing Fields"), }); } return { query: "hrms.payroll.doctype.payroll_entry.payroll_entry.employee_query", filters: frm.events.get_employee_filters(frm), }; }); }, get_employee_filters: function (frm) { let filters = {}; let fields = [ "company", "start_date", "end_date", "payroll_frequency", "payroll_payable_account", "currency", "department", "branch", "designation", "salary_slip_based_on_timesheet", "grade", ]; fields.forEach((field) => { if (frm.doc[field] || frm.doc[field] === 0) { filters[field] = frm.doc[field]; } }); if (frm.doc.employees) { let employees = frm.doc.employees.filter((d) => d.employee).map((d) => d.employee); if (employees && employees.length) { filters["employees"] = employees; } } return filters; }, payroll_frequency: function (frm) { frm.trigger("set_start_end_dates").then(() => { frm.events.clear_employee_table(frm); }); }, company: function (frm) { frm.events.clear_employee_table(frm); erpnext.accounts.dimensions.update_dimension(frm, frm.doctype); frm.trigger("set_payable_account_and_currency"); }, set_payable_account_and_currency: function (frm) { frappe.db.get_value("Company", { name: frm.doc.company }, "default_currency", (r) => { frm.set_value("currency", r.default_currency); }); frappe.db.get_value( "Company", { name: frm.doc.company }, "default_payroll_payable_account", (r) => { frm.set_value("payroll_payable_account", r.default_payroll_payable_account); }, ); }, currency: function (frm) { var company_currency; if (!frm.doc.company) { company_currency = erpnext.get_currency(frappe.defaults.get_default("Company")); } else { company_currency = erpnext.get_currency(frm.doc.company); } if (frm.doc.currency) { if (company_currency != frm.doc.currency) { frappe.call({ method: "erpnext.setup.utils.get_exchange_rate", args: { from_currency: frm.doc.currency, to_currency: company_currency, }, callback: function (r) { frm.set_value("exchange_rate", flt(r.message)); frm.set_df_property("exchange_rate", "hidden", 0); frm.set_df_property( "exchange_rate", "description", "1 " + frm.doc.currency + " = [?] " + company_currency, ); }, }); } else { frm.set_value("exchange_rate", 1.0); frm.set_df_property("exchange_rate", "hidden", 1); frm.set_df_property("exchange_rate", "description", ""); } } }, department: function (frm) { frm.events.clear_employee_table(frm); }, grade: function (frm) { frm.events.clear_employee_table(frm); }, designation: function (frm) { frm.events.clear_employee_table(frm); }, branch: function (frm) { frm.events.clear_employee_table(frm); }, start_date: function (frm) { if (!in_progress && frm.doc.start_date) { frm.trigger("set_end_date"); } else { // reset flag in_progress = false; } frm.events.clear_employee_table(frm); }, project: function (frm) { frm.events.clear_employee_table(frm); }, salary_slip_based_on_timesheet: function (frm) { frm.toggle_reqd(["payroll_frequency"], !frm.doc.salary_slip_based_on_timesheet); hrms.set_payroll_frequency_to_null(frm); }, set_start_end_dates: function (frm) { if (!frm.doc.salary_slip_based_on_timesheet) { frappe.call({ method: "hrms.payroll.doctype.payroll_entry.payroll_entry.get_start_end_dates", args: { payroll_frequency: frm.doc.payroll_frequency, start_date: frm.doc.posting_date, }, callback: function (r) { if (r.message) { in_progress = true; frm.set_value("start_date", r.message.start_date); frm.set_value("end_date", r.message.end_date); } }, }); } }, set_end_date: function (frm) { frappe.call({ method: "hrms.payroll.doctype.payroll_entry.payroll_entry.get_end_date", args: { frequency: frm.doc.payroll_frequency, start_date: frm.doc.start_date, }, callback: function (r) { if (r.message) { frm.set_value("end_date", r.message.end_date); } }, }); }, validate_attendance: function (frm) { if (frm.doc.validate_attendance && frm.doc.employees?.length > 0) { frappe.call({ method: "get_employees_with_unmarked_attendance", args: {}, callback: function (r) { render_employee_attendance(frm, r.message); }, doc: frm.doc, freeze: true, freeze_message: __("Validating Employee Attendance..."), }); } else { frm.fields_dict.attendance_detail_html.html(""); } }, clear_employee_table: function (frm) { frm.clear_table("employees"); frm.refresh(); }, }); // Submit salary slips const submit_salary_slip = function (frm) { frappe.confirm( __( "This will submit Salary Slips and create accrual Journal Entry. Do you want to proceed?", ), function () { frappe.call({ method: "submit_salary_slips", args: {}, doc: frm.doc, freeze: true, freeze_message: __("Submitting Salary Slips and creating Journal Entry..."), }); }, function () { if (frappe.dom.freeze_count) { frappe.dom.unfreeze(); } }, ); }; let make_bank_entry = function (frm, for_withheld_salaries = 0) { const doc = frm.doc; if (doc.payment_account) { return frappe.call({ method: "run_doc_method", args: { method: "make_bank_entry", dt: "Payroll Entry", dn: frm.doc.name, args: { for_withheld_salaries: for_withheld_salaries }, }, callback: function () { frappe.set_route("List", "Journal Entry", { "Journal Entry Account.reference_name": frm.doc.name, }); }, freeze: true, freeze_message: __("Creating Payment Entries......"), }); } else { frappe.msgprint(__("Payment Account is mandatory")); frm.scroll_to_field("payment_account"); } }; let render_employee_attendance = function (frm, data) { frm.fields_dict.attendance_detail_html.html( frappe.render_template("employees_with_unmarked_attendance", { data: data, }), ); };
2302_79757062/hrms
hrms/payroll/doctype/payroll_entry/payroll_entry.js
JavaScript
agpl-3.0
11,747
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import json from dateutil.relativedelta import relativedelta import frappe from frappe import _ from frappe.desk.reportview import get_match_cond from frappe.model.document import Document from frappe.query_builder.functions import Coalesce, Count from frappe.utils import ( DATE_FORMAT, add_days, add_to_date, cint, comma_and, date_diff, flt, get_link_to_form, getdate, ) import erpnext from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import ( get_accounting_dimensions, ) from erpnext.accounts.utils import get_fiscal_year from hrms.payroll.doctype.salary_withholding.salary_withholding import link_bank_entry_in_salary_withholdings class PayrollEntry(Document): def onload(self): if not self.docstatus == 1 or self.salary_slips_submitted: return # check if salary slips were manually submitted entries = frappe.db.count("Salary Slip", {"payroll_entry": self.name, "docstatus": 1}, ["name"]) if cint(entries) == len(self.employees): self.set_onload("submitted_ss", True) def validate(self): self.number_of_employees = len(self.employees) self.set_status() def set_status(self, status=None, update=False): if not status: status = {0: "Draft", 1: "Submitted", 2: "Cancelled"}[self.docstatus or 0] if update: self.db_set("status", status) else: self.status = status def before_submit(self): self.validate_existing_salary_slips() self.validate_payroll_payable_account() if self.get_employees_with_unmarked_attendance(): frappe.throw(_("Cannot submit. Attendance is not marked for some employees.")) def on_submit(self): self.set_status(update=True, status="Submitted") self.create_salary_slips() def validate_existing_salary_slips(self): if not self.employees: return existing_salary_slips = [] SalarySlip = frappe.qb.DocType("Salary Slip") existing_salary_slips = ( frappe.qb.from_(SalarySlip) .select(SalarySlip.employee, SalarySlip.name) .where( (SalarySlip.employee.isin([emp.employee for emp in self.employees])) & (SalarySlip.start_date == self.start_date) & (SalarySlip.end_date == self.end_date) & (SalarySlip.docstatus != 2) ) ).run(as_dict=True) if len(existing_salary_slips): msg = _("Salary Slip already exists for {0} for the given dates").format( comma_and([frappe.bold(d.employee) for d in existing_salary_slips]) ) msg += "<br><br>" msg += _("Reference: {0}").format( comma_and([get_link_to_form("Salary Slip", d.name) for d in existing_salary_slips]) ) frappe.throw( msg, title=_("Duplicate Entry"), ) def validate_payroll_payable_account(self): if frappe.db.get_value("Account", self.payroll_payable_account, "account_type"): frappe.throw( _( "Account type cannot be set for payroll payable account {0}, please remove and try again" ).format(frappe.bold(get_link_to_form("Account", self.payroll_payable_account))) ) def on_cancel(self): self.ignore_linked_doctypes = ("GL Entry", "Salary Slip", "Journal Entry") self.delete_linked_salary_slips() self.cancel_linked_journal_entries() # reset flags & update status self.db_set("salary_slips_created", 0) self.db_set("salary_slips_submitted", 0) self.set_status(update=True, status="Cancelled") self.db_set("error_message", "") def cancel(self): if len(self.get_linked_salary_slips()) > 50: msg = _("Payroll Entry cancellation is queued. It may take a few minutes") msg += "<br>" msg += _( "In case of any error during this background process, the system will add a comment about the error on this Payroll Entry and revert to the Submitted status" ) frappe.msgprint( msg, indicator="blue", title=_("Cancellation Queued"), ) self.queue_action("cancel", timeout=3000) else: self._cancel() def delete_linked_salary_slips(self): salary_slips = self.get_linked_salary_slips() # cancel & delete salary slips for salary_slip in salary_slips: if salary_slip.docstatus == 1: frappe.get_doc("Salary Slip", salary_slip.name).cancel() frappe.delete_doc("Salary Slip", salary_slip.name) def cancel_linked_journal_entries(self): journal_entries = frappe.get_all( "Journal Entry Account", {"reference_type": self.doctype, "reference_name": self.name, "docstatus": 1}, pluck="parent", distinct=True, ) # cancel Journal Entries for je in journal_entries: frappe.get_doc("Journal Entry", je).cancel() def get_linked_salary_slips(self): return frappe.get_all("Salary Slip", {"payroll_entry": self.name}, ["name", "docstatus"]) def make_filters(self): filters = frappe._dict( company=self.company, branch=self.branch, department=self.department, designation=self.designation, grade=self.grade, currency=self.currency, start_date=self.start_date, end_date=self.end_date, payroll_payable_account=self.payroll_payable_account, salary_slip_based_on_timesheet=self.salary_slip_based_on_timesheet, ) if not self.salary_slip_based_on_timesheet: filters.update(dict(payroll_frequency=self.payroll_frequency)) return filters @frappe.whitelist() def fill_employee_details(self): filters = self.make_filters() employees = get_employee_list(filters=filters, as_dict=True, ignore_match_conditions=True) self.set("employees", []) if not employees: error_msg = _( "No employees found for the mentioned criteria:<br>Company: {0}<br> Currency: {1}<br>Payroll Payable Account: {2}" ).format( frappe.bold(self.company), frappe.bold(self.currency), frappe.bold(self.payroll_payable_account), ) if self.branch: error_msg += "<br>" + _("Branch: {0}").format(frappe.bold(self.branch)) if self.department: error_msg += "<br>" + _("Department: {0}").format(frappe.bold(self.department)) if self.designation: error_msg += "<br>" + _("Designation: {0}").format(frappe.bold(self.designation)) if self.start_date: error_msg += "<br>" + _("Start date: {0}").format(frappe.bold(self.start_date)) if self.end_date: error_msg += "<br>" + _("End date: {0}").format(frappe.bold(self.end_date)) frappe.throw(error_msg, title=_("No employees found")) self.set("employees", employees) self.number_of_employees = len(self.employees) self.update_employees_with_withheld_salaries() return self.get_employees_with_unmarked_attendance() def update_employees_with_withheld_salaries(self): withheld_salaries = get_salary_withholdings(self.start_date, self.end_date, pluck="employee") for employee in self.employees: if employee.employee in withheld_salaries: employee.is_salary_withheld = 1 @frappe.whitelist() def create_salary_slips(self): """ Creates salary slip for selected employees if already not created """ self.check_permission("write") employees = [emp.employee for emp in self.employees] if employees: args = frappe._dict( { "salary_slip_based_on_timesheet": self.salary_slip_based_on_timesheet, "payroll_frequency": self.payroll_frequency, "start_date": self.start_date, "end_date": self.end_date, "company": self.company, "posting_date": self.posting_date, "deduct_tax_for_unclaimed_employee_benefits": self.deduct_tax_for_unclaimed_employee_benefits, "deduct_tax_for_unsubmitted_tax_exemption_proof": self.deduct_tax_for_unsubmitted_tax_exemption_proof, "payroll_entry": self.name, "exchange_rate": self.exchange_rate, "currency": self.currency, } ) if len(employees) > 30 or frappe.flags.enqueue_payroll_entry: self.db_set("status", "Queued") frappe.enqueue( create_salary_slips_for_employees, timeout=3000, employees=employees, args=args, publish_progress=False, ) frappe.msgprint( _("Salary Slip creation is queued. It may take a few minutes"), alert=True, indicator="blue", ) else: create_salary_slips_for_employees(employees, args, publish_progress=False) # since this method is called via frm.call this doc needs to be updated manually self.reload() def get_sal_slip_list(self, ss_status, as_dict=False): """ Returns list of salary slips based on selected criteria """ ss = frappe.qb.DocType("Salary Slip") ss_list = ( frappe.qb.from_(ss) .select(ss.name, ss.salary_structure) .where( (ss.docstatus == ss_status) & (ss.start_date >= self.start_date) & (ss.end_date <= self.end_date) & (ss.payroll_entry == self.name) & ((ss.journal_entry.isnull()) | (ss.journal_entry == "")) & (Coalesce(ss.salary_slip_based_on_timesheet, 0) == self.salary_slip_based_on_timesheet) ) ).run(as_dict=as_dict) return ss_list @frappe.whitelist() def submit_salary_slips(self): self.check_permission("write") salary_slips = self.get_sal_slip_list(ss_status=0) if len(salary_slips) > 30 or frappe.flags.enqueue_payroll_entry: self.db_set("status", "Queued") frappe.enqueue( submit_salary_slips_for_employees, timeout=3000, payroll_entry=self, salary_slips=salary_slips, publish_progress=False, ) frappe.msgprint( _("Salary Slip submission is queued. It may take a few minutes"), alert=True, indicator="blue", ) else: submit_salary_slips_for_employees(self, salary_slips, publish_progress=False) def email_salary_slip(self, submitted_ss): if frappe.db.get_single_value("Payroll Settings", "email_salary_slip_to_employee"): for ss in submitted_ss: ss.email_salary_slip() def get_salary_component_account(self, salary_component): account = frappe.db.get_value( "Salary Component Account", {"parent": salary_component, "company": self.company}, "account", cache=True, ) if not account: frappe.throw( _("Please set account in Salary Component {0}").format( get_link_to_form("Salary Component", salary_component) ) ) return account def get_salary_components(self, component_type): salary_slips = self.get_sal_slip_list(ss_status=1, as_dict=True) if salary_slips: ss = frappe.qb.DocType("Salary Slip") ssd = frappe.qb.DocType("Salary Detail") salary_components = ( frappe.qb.from_(ss) .join(ssd) .on(ss.name == ssd.parent) .select( ssd.salary_component, ssd.amount, ssd.parentfield, ssd.additional_salary, ss.salary_structure, ss.employee, ) .where((ssd.parentfield == component_type) & (ss.name.isin([d.name for d in salary_slips]))) ).run(as_dict=True) return salary_components def get_salary_component_total( self, component_type=None, employee_wise_accounting_enabled=False, ): salary_components = self.get_salary_components(component_type) if salary_components: component_dict = {} for item in salary_components: if not self.should_add_component_to_accrual_jv(component_type, item): continue employee_cost_centers = self.get_payroll_cost_centers_for_employee( item.employee, item.salary_structure ) employee_advance = self.get_advance_deduction(component_type, item) for cost_center, percentage in employee_cost_centers.items(): amount_against_cost_center = flt(item.amount) * percentage / 100 if employee_advance: self.add_advance_deduction_entry( item, amount_against_cost_center, cost_center, employee_advance ) else: key = (item.salary_component, cost_center) component_dict[key] = component_dict.get(key, 0) + amount_against_cost_center if employee_wise_accounting_enabled: self.set_employee_based_payroll_payable_entries( component_type, item.employee, amount_against_cost_center ) account_details = self.get_account(component_dict=component_dict) return account_details def should_add_component_to_accrual_jv(self, component_type: str, item: dict) -> bool: add_component_to_accrual_jv = True if component_type == "earnings": is_flexible_benefit, only_tax_impact = frappe.get_cached_value( "Salary Component", item["salary_component"], ["is_flexible_benefit", "only_tax_impact"] ) if cint(is_flexible_benefit) and cint(only_tax_impact): add_component_to_accrual_jv = False return add_component_to_accrual_jv def get_advance_deduction(self, component_type: str, item: dict) -> str | None: if component_type == "deductions" and item.additional_salary: ref_doctype, ref_docname = frappe.db.get_value( "Additional Salary", item.additional_salary, ["ref_doctype", "ref_docname"], ) if ref_doctype == "Employee Advance": return ref_docname return def add_advance_deduction_entry( self, item: dict, amount: float, cost_center: str, employee_advance: str, ) -> None: self._advance_deduction_entries.append( { "employee": item.employee, "account": self.get_salary_component_account(item.salary_component), "amount": amount, "cost_center": cost_center, "reference_type": "Employee Advance", "reference_name": employee_advance, } ) def set_accounting_entries_for_advance_deductions( self, accounts: list, currencies: list, company_currency: str, accounting_dimensions: list, precision: int, payable_amount: float, ): for entry in self._advance_deduction_entries: payable_amount = self.get_accounting_entries_and_payable_amount( entry.get("account"), entry.get("cost_center"), entry.get("amount"), currencies, company_currency, payable_amount, accounting_dimensions, precision, entry_type="credit", accounts=accounts, party=entry.get("employee"), reference_type="Employee Advance", reference_name=entry.get("reference_name"), is_advance="Yes", ) return payable_amount def set_employee_based_payroll_payable_entries( self, component_type, employee, amount, salary_structure=None ): employee_details = self.employee_based_payroll_payable_entries.setdefault(employee, {}) employee_details.setdefault(component_type, 0) employee_details[component_type] += amount if salary_structure and "salary_structure" not in employee_details: employee_details["salary_structure"] = salary_structure def get_payroll_cost_centers_for_employee(self, employee, salary_structure): if not hasattr(self, "employee_cost_centers"): self.employee_cost_centers = {} if not self.employee_cost_centers.get(employee): SalaryStructureAssignment = frappe.qb.DocType("Salary Structure Assignment") EmployeeCostCenter = frappe.qb.DocType("Employee Cost Center") assignment_subquery = ( frappe.qb.from_(SalaryStructureAssignment) .select(SalaryStructureAssignment.name) .where( (SalaryStructureAssignment.employee == employee) & (SalaryStructureAssignment.salary_structure == salary_structure) & (SalaryStructureAssignment.docstatus == 1) & (SalaryStructureAssignment.from_date <= self.end_date) ) .orderby(SalaryStructureAssignment.from_date, order=frappe.qb.desc) .limit(1) ) cost_centers = dict( ( frappe.qb.from_(EmployeeCostCenter) .select(EmployeeCostCenter.cost_center, EmployeeCostCenter.percentage) .where(EmployeeCostCenter.parent == assignment_subquery) ).run(as_list=True) ) if not cost_centers: default_cost_center, department = frappe.get_cached_value( "Employee", employee, ["payroll_cost_center", "department"] ) if not default_cost_center and department: default_cost_center = frappe.get_cached_value( "Department", department, "payroll_cost_center" ) if not default_cost_center: default_cost_center = self.cost_center cost_centers = {default_cost_center: 100} self.employee_cost_centers.setdefault(employee, cost_centers) return self.employee_cost_centers.get(employee, {}) def get_account(self, component_dict=None): account_dict = {} for key, amount in component_dict.items(): component, cost_center = key account = self.get_salary_component_account(component) accounting_key = (account, cost_center) account_dict[accounting_key] = account_dict.get(accounting_key, 0) + amount return account_dict def make_accrual_jv_entry(self, submitted_salary_slips): self.check_permission("write") employee_wise_accounting_enabled = frappe.db.get_single_value( "Payroll Settings", "process_payroll_accounting_entry_based_on_employee" ) self.employee_based_payroll_payable_entries = {} self._advance_deduction_entries = [] earnings = ( self.get_salary_component_total( component_type="earnings", employee_wise_accounting_enabled=employee_wise_accounting_enabled, ) or {} ) deductions = ( self.get_salary_component_total( component_type="deductions", employee_wise_accounting_enabled=employee_wise_accounting_enabled, ) or {} ) precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency") if earnings or deductions: accounts = [] currencies = [] payable_amount = 0 accounting_dimensions = get_accounting_dimensions() or [] company_currency = erpnext.get_company_currency(self.company) payable_amount = self.get_payable_amount_for_earnings_and_deductions( accounts, earnings, deductions, currencies, company_currency, accounting_dimensions, precision, payable_amount, ) payable_amount = self.set_accounting_entries_for_advance_deductions( accounts, currencies, company_currency, accounting_dimensions, precision, payable_amount, ) self.set_payable_amount_against_payroll_payable_account( accounts, currencies, company_currency, accounting_dimensions, precision, payable_amount, self.payroll_payable_account, employee_wise_accounting_enabled, ) self.make_journal_entry( accounts, currencies, self.payroll_payable_account, voucher_type="Journal Entry", user_remark=_("Accrual Journal Entry for salaries from {0} to {1}").format( self.start_date, self.end_date ), submit_journal_entry=True, submitted_salary_slips=submitted_salary_slips, ) def make_journal_entry( self, accounts, currencies, payroll_payable_account=None, voucher_type="Journal Entry", user_remark="", submitted_salary_slips: list | None = None, submit_journal_entry=False, ) -> str: multi_currency = 0 if len(currencies) > 1: multi_currency = 1 journal_entry = frappe.new_doc("Journal Entry") journal_entry.voucher_type = voucher_type journal_entry.user_remark = user_remark journal_entry.company = self.company journal_entry.posting_date = self.posting_date journal_entry.set("accounts", accounts) journal_entry.multi_currency = multi_currency if voucher_type == "Journal Entry": journal_entry.title = payroll_payable_account journal_entry.save(ignore_permissions=True) try: if submit_journal_entry: journal_entry.submit() if submitted_salary_slips: self.set_journal_entry_in_salary_slips(submitted_salary_slips, jv_name=journal_entry.name) except Exception as e: if type(e) in (str, list, tuple): frappe.msgprint(e) self.log_error("Journal Entry creation against Salary Slip failed") raise return journal_entry def get_payable_amount_for_earnings_and_deductions( self, accounts, earnings, deductions, currencies, company_currency, accounting_dimensions, precision, payable_amount, ): # Earnings for acc_cc, amount in earnings.items(): payable_amount = self.get_accounting_entries_and_payable_amount( acc_cc[0], acc_cc[1] or self.cost_center, amount, currencies, company_currency, payable_amount, accounting_dimensions, precision, entry_type="debit", accounts=accounts, ) # Deductions for acc_cc, amount in deductions.items(): payable_amount = self.get_accounting_entries_and_payable_amount( acc_cc[0], acc_cc[1] or self.cost_center, amount, currencies, company_currency, payable_amount, accounting_dimensions, precision, entry_type="credit", accounts=accounts, ) return payable_amount def set_payable_amount_against_payroll_payable_account( self, accounts, currencies, company_currency, accounting_dimensions, precision, payable_amount, payroll_payable_account, employee_wise_accounting_enabled, ): # Payable amount if employee_wise_accounting_enabled: """ employee_based_payroll_payable_entries = { 'HREMP00004': { 'earnings': 83332.0, 'deductions': 2000.0 }, 'HREMP00005': { 'earnings': 50000.0, 'deductions': 2000.0 } } """ for employee, employee_details in self.employee_based_payroll_payable_entries.items(): payable_amount = employee_details.get("earnings", 0) - employee_details.get("deductions", 0) payable_amount = self.get_accounting_entries_and_payable_amount( payroll_payable_account, self.cost_center, payable_amount, currencies, company_currency, 0, accounting_dimensions, precision, entry_type="payable", party=employee, accounts=accounts, ) else: payable_amount = self.get_accounting_entries_and_payable_amount( payroll_payable_account, self.cost_center, payable_amount, currencies, company_currency, 0, accounting_dimensions, precision, entry_type="payable", accounts=accounts, ) def get_accounting_entries_and_payable_amount( self, account, cost_center, amount, currencies, company_currency, payable_amount, accounting_dimensions, precision, entry_type="credit", party=None, accounts=None, reference_type=None, reference_name=None, is_advance=None, ): exchange_rate, amt = self.get_amount_and_exchange_rate_for_journal_entry( account, amount, company_currency, currencies ) row = { "account": account, "exchange_rate": flt(exchange_rate), "cost_center": cost_center, "project": self.project, } if entry_type == "debit": payable_amount += flt(amount, precision) row.update( { "debit_in_account_currency": flt(amt, precision), } ) elif entry_type == "credit": payable_amount -= flt(amount, precision) row.update( { "credit_in_account_currency": flt(amt, precision), } ) else: row.update( { "credit_in_account_currency": flt(amt, precision), "reference_type": self.doctype, "reference_name": self.name, } ) if party: row.update( { "party_type": "Employee", "party": party, } ) if reference_type: row.update( { "reference_type": reference_type, "reference_name": reference_name, "is_advance": is_advance, } ) self.update_accounting_dimensions( row, accounting_dimensions, ) if amt: accounts.append(row) return payable_amount def update_accounting_dimensions(self, row, accounting_dimensions): for dimension in accounting_dimensions: row.update({dimension: self.get(dimension)}) return row def get_amount_and_exchange_rate_for_journal_entry(self, account, amount, company_currency, currencies): conversion_rate = 1 exchange_rate = self.exchange_rate account_currency = frappe.db.get_value("Account", account, "account_currency") if account_currency not in currencies: currencies.append(account_currency) if account_currency == company_currency: conversion_rate = self.exchange_rate exchange_rate = 1 amount = flt(amount) * flt(conversion_rate) return exchange_rate, amount @frappe.whitelist() def has_bank_entries(self) -> dict[str, bool]: je = frappe.qb.DocType("Journal Entry") jea = frappe.qb.DocType("Journal Entry Account") bank_entries = ( frappe.qb.from_(je) .inner_join(jea) .on(je.name == jea.parent) .select(je.name) .where( (je.voucher_type == "Bank Entry") & (jea.reference_name == self.name) & (jea.reference_type == "Payroll Entry") ) ).run(as_dict=True) return { "has_bank_entries": bool(bank_entries), "has_bank_entries_for_withheld_salaries": not any( employee.is_salary_withheld for employee in self.employees ), } @frappe.whitelist() def make_bank_entry(self, for_withheld_salaries=False): self.check_permission("write") self.employee_based_payroll_payable_entries = {} employee_wise_accounting_enabled = frappe.db.get_single_value( "Payroll Settings", "process_payroll_accounting_entry_based_on_employee" ) salary_slip_total = 0 salary_slips = self.get_salary_slip_details(for_withheld_salaries) for salary_detail in salary_slips: if salary_detail.parentfield == "earnings": ( is_flexible_benefit, only_tax_impact, create_separate_je, statistical_component, ) = frappe.db.get_value( "Salary Component", salary_detail.salary_component, ( "is_flexible_benefit", "only_tax_impact", "create_separate_payment_entry_against_benefit_claim", "statistical_component", ), cache=True, ) if only_tax_impact != 1 and statistical_component != 1: if is_flexible_benefit == 1 and create_separate_je == 1: self.set_accounting_entries_for_bank_entry( salary_detail.amount, salary_detail.salary_component ) else: if employee_wise_accounting_enabled: self.set_employee_based_payroll_payable_entries( "earnings", salary_detail.employee, salary_detail.amount, salary_detail.salary_structure, ) salary_slip_total += salary_detail.amount if salary_detail.parentfield == "deductions": statistical_component = frappe.db.get_value( "Salary Component", salary_detail.salary_component, "statistical_component", cache=True ) if not statistical_component: if employee_wise_accounting_enabled: self.set_employee_based_payroll_payable_entries( "deductions", salary_detail.employee, salary_detail.amount, salary_detail.salary_structure, ) salary_slip_total -= salary_detail.amount bank_entry = None if salary_slip_total > 0: remark = "withheld salaries" if for_withheld_salaries else "salaries" bank_entry = self.set_accounting_entries_for_bank_entry(salary_slip_total, remark) if for_withheld_salaries: link_bank_entry_in_salary_withholdings(salary_slips, bank_entry.name) return bank_entry def get_salary_slip_details(self, for_withheld_salaries=False): SalarySlip = frappe.qb.DocType("Salary Slip") SalaryDetail = frappe.qb.DocType("Salary Detail") query = ( frappe.qb.from_(SalarySlip) .join(SalaryDetail) .on(SalarySlip.name == SalaryDetail.parent) .select( SalarySlip.name, SalarySlip.employee, SalarySlip.salary_structure, SalarySlip.salary_withholding_cycle, SalaryDetail.salary_component, SalaryDetail.amount, SalaryDetail.parentfield, ) .where( (SalarySlip.docstatus == 1) & (SalarySlip.start_date >= self.start_date) & (SalarySlip.end_date <= self.end_date) & (SalarySlip.payroll_entry == self.name) ) ) if for_withheld_salaries: query = query.where(SalarySlip.status == "Withheld") else: query = query.where(SalarySlip.status != "Withheld") return query.run(as_dict=True) def set_accounting_entries_for_bank_entry(self, je_payment_amount, user_remark): payroll_payable_account = self.payroll_payable_account precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency") accounts = [] currencies = [] company_currency = erpnext.get_company_currency(self.company) accounting_dimensions = get_accounting_dimensions() or [] exchange_rate, amount = self.get_amount_and_exchange_rate_for_journal_entry( self.payment_account, je_payment_amount, company_currency, currencies ) accounts.append( self.update_accounting_dimensions( { "account": self.payment_account, "bank_account": self.bank_account, "credit_in_account_currency": flt(amount, precision), "exchange_rate": flt(exchange_rate), "cost_center": self.cost_center, }, accounting_dimensions, ) ) if self.employee_based_payroll_payable_entries: for employee, employee_details in self.employee_based_payroll_payable_entries.items(): je_payment_amount = employee_details.get("earnings", 0) - ( employee_details.get("deductions", 0) ) exchange_rate, amount = self.get_amount_and_exchange_rate_for_journal_entry( self.payment_account, je_payment_amount, company_currency, currencies ) cost_centers = self.get_payroll_cost_centers_for_employee( employee, employee_details.get("salary_structure") ) for cost_center, percentage in cost_centers.items(): amount_against_cost_center = flt(amount) * percentage / 100 accounts.append( self.update_accounting_dimensions( { "account": payroll_payable_account, "debit_in_account_currency": flt(amount_against_cost_center, precision), "exchange_rate": flt(exchange_rate), "reference_type": self.doctype, "reference_name": self.name, "party_type": "Employee", "party": employee, "cost_center": cost_center, }, accounting_dimensions, ) ) else: exchange_rate, amount = self.get_amount_and_exchange_rate_for_journal_entry( payroll_payable_account, je_payment_amount, company_currency, currencies ) accounts.append( self.update_accounting_dimensions( { "account": payroll_payable_account, "debit_in_account_currency": flt(amount, precision), "exchange_rate": flt(exchange_rate), "reference_type": self.doctype, "reference_name": self.name, "cost_center": self.cost_center, }, accounting_dimensions, ) ) return self.make_journal_entry( accounts, currencies, voucher_type="Bank Entry", user_remark=_("Payment of {0} from {1} to {2}").format( _(user_remark), self.start_date, self.end_date ), ) def set_journal_entry_in_salary_slips(self, submitted_salary_slips, jv_name=None): SalarySlip = frappe.qb.DocType("Salary Slip") ( frappe.qb.update(SalarySlip) .set(SalarySlip.journal_entry, jv_name) .where(SalarySlip.name.isin([salary_slip.name for salary_slip in submitted_salary_slips])) ).run() def set_start_end_dates(self): self.update( get_start_end_dates(self.payroll_frequency, self.start_date or self.posting_date, self.company) ) @frappe.whitelist() def get_employees_with_unmarked_attendance(self) -> list[dict] | None: if not self.validate_attendance: return unmarked_attendance = [] employee_details = self.get_employee_and_attendance_details() default_holiday_list = frappe.db.get_value( "Company", self.company, "default_holiday_list", cache=True ) for emp in self.employees: details = next((record for record in employee_details if record.name == emp.employee), None) if not details: continue start_date, end_date = self.get_payroll_dates_for_employee(details) holidays = self.get_holidays_count( details.holiday_list or default_holiday_list, start_date, end_date ) payroll_days = date_diff(end_date, start_date) + 1 unmarked_days = payroll_days - (holidays + details.attendance_count) if unmarked_days > 0: unmarked_attendance.append( { "employee": emp.employee, "employee_name": emp.employee_name, "unmarked_days": unmarked_days, } ) return unmarked_attendance def get_employee_and_attendance_details(self) -> list[dict]: """Returns a list of employee and attendance details like [ { "name": "HREMP00001", "date_of_joining": "2019-01-01", "relieving_date": "2022-01-01", "holiday_list": "Holiday List Company", "attendance_count": 22 } ] """ employees = [emp.employee for emp in self.employees] Employee = frappe.qb.DocType("Employee") Attendance = frappe.qb.DocType("Attendance") return ( frappe.qb.from_(Employee) .left_join(Attendance) .on( (Employee.name == Attendance.employee) & (Attendance.attendance_date.between(self.start_date, self.end_date)) & (Attendance.docstatus == 1) ) .select( Employee.name, Employee.date_of_joining, Employee.relieving_date, Employee.holiday_list, Count(Attendance.name).as_("attendance_count"), ) .where(Employee.name.isin(employees)) .groupby(Employee.name) ).run(as_dict=True) def get_payroll_dates_for_employee(self, employee_details: dict) -> tuple[str, str]: start_date = self.start_date if employee_details.date_of_joining > getdate(self.start_date): start_date = employee_details.date_of_joining end_date = self.end_date if employee_details.relieving_date and employee_details.relieving_date < getdate(self.end_date): end_date = employee_details.relieving_date return start_date, end_date def get_holidays_count(self, holiday_list: str, start_date: str, end_date: str) -> float: """Returns number of holidays between start and end dates in the holiday list""" if not hasattr(self, "_holidays_between_dates"): self._holidays_between_dates = {} key = f"{start_date}-{end_date}-{holiday_list}" if key in self._holidays_between_dates: return self._holidays_between_dates[key] holidays = frappe.db.get_all( "Holiday", filters={"parent": holiday_list, "holiday_date": ("between", [start_date, end_date])}, fields=["COUNT(*) as holidays_count"], )[0] if holidays: self._holidays_between_dates[key] = holidays.holidays_count return self._holidays_between_dates.get(key) or 0 def get_salary_structure( company: str, currency: str, salary_slip_based_on_timesheet: int, payroll_frequency: str ) -> list[str]: SalaryStructure = frappe.qb.DocType("Salary Structure") query = ( frappe.qb.from_(SalaryStructure) .select(SalaryStructure.name) .where( (SalaryStructure.docstatus == 1) & (SalaryStructure.is_active == "Yes") & (SalaryStructure.company == company) & (SalaryStructure.currency == currency) & (SalaryStructure.salary_slip_based_on_timesheet == salary_slip_based_on_timesheet) ) ) if not salary_slip_based_on_timesheet: query = query.where(SalaryStructure.payroll_frequency == payroll_frequency) return query.run(pluck=True) def get_filtered_employees( sal_struct, filters, searchfield=None, search_string=None, fields=None, as_dict=False, limit=None, offset=None, ignore_match_conditions=False, ) -> list: SalaryStructureAssignment = frappe.qb.DocType("Salary Structure Assignment") Employee = frappe.qb.DocType("Employee") query = ( frappe.qb.from_(Employee) .join(SalaryStructureAssignment) .on(Employee.name == SalaryStructureAssignment.employee) .where( (SalaryStructureAssignment.docstatus == 1) & (Employee.status != "Inactive") & (Employee.company == filters.company) & ((Employee.date_of_joining <= filters.end_date) | (Employee.date_of_joining.isnull())) & ((Employee.relieving_date >= filters.start_date) | (Employee.relieving_date.isnull())) & (SalaryStructureAssignment.salary_structure.isin(sal_struct)) & (SalaryStructureAssignment.payroll_payable_account == filters.payroll_payable_account) & (filters.end_date >= SalaryStructureAssignment.from_date) ) ) query = set_fields_to_select(query, fields) query = set_searchfield(query, searchfield, search_string, qb_object=Employee) query = set_filter_conditions(query, filters, qb_object=Employee) if not ignore_match_conditions: query = set_match_conditions(query=query, qb_object=Employee) if limit: query = query.limit(limit) if offset: query = query.offset(offset) return query.run(as_dict=as_dict) def set_fields_to_select(query, fields: list[str] | None = None): default_fields = ["employee", "employee_name", "department", "designation"] if fields: query = query.select(*fields).distinct() else: query = query.select(*default_fields).distinct() return query def set_searchfield(query, searchfield, search_string, qb_object): if searchfield: query = query.where( (qb_object[searchfield].like("%" + search_string + "%")) | (qb_object.employee_name.like("%" + search_string + "%")) ) return query def set_filter_conditions(query, filters, qb_object): """Append optional filters to employee query""" if filters.get("employees"): query = query.where(qb_object.name.notin(filters.get("employees"))) for fltr_key in ["branch", "department", "designation", "grade"]: if filters.get(fltr_key): query = query.where(qb_object[fltr_key] == filters[fltr_key]) return query def set_match_conditions(query, qb_object): match_conditions = get_match_cond("Employee", as_condition=False) for cond in match_conditions: if isinstance(cond, dict): for key, value in cond.items(): if isinstance(value, list): query = query.where(qb_object[key].isin(value)) else: query = query.where(qb_object[key] == value) return query def remove_payrolled_employees(emp_list, start_date, end_date): SalarySlip = frappe.qb.DocType("Salary Slip") employees_with_payroll = ( frappe.qb.from_(SalarySlip) .select(SalarySlip.employee) .where( (SalarySlip.docstatus == 1) & (SalarySlip.start_date == start_date) & (SalarySlip.end_date == end_date) ) ).run(pluck=True) return [emp_list[emp] for emp in emp_list if emp not in employees_with_payroll] @frappe.whitelist() def get_start_end_dates(payroll_frequency, start_date=None, company=None): """Returns dict of start and end dates for given payroll frequency based on start_date""" if payroll_frequency == "Monthly" or payroll_frequency == "Bimonthly" or payroll_frequency == "": fiscal_year = get_fiscal_year(start_date, company=company)[0] month = "%02d" % getdate(start_date).month m = get_month_details(fiscal_year, month) if payroll_frequency == "Bimonthly": if getdate(start_date).day <= 15: start_date = m["month_start_date"] end_date = m["month_mid_end_date"] else: start_date = m["month_mid_start_date"] end_date = m["month_end_date"] else: start_date = m["month_start_date"] end_date = m["month_end_date"] if payroll_frequency == "Weekly": end_date = add_days(start_date, 6) if payroll_frequency == "Fortnightly": end_date = add_days(start_date, 13) if payroll_frequency == "Daily": end_date = start_date return frappe._dict({"start_date": start_date, "end_date": end_date}) def get_frequency_kwargs(frequency_name): frequency_dict = { "monthly": {"months": 1}, "fortnightly": {"days": 14}, "weekly": {"days": 7}, "daily": {"days": 1}, } return frequency_dict.get(frequency_name) @frappe.whitelist() def get_end_date(start_date, frequency): start_date = getdate(start_date) frequency = frequency.lower() if frequency else "monthly" kwargs = get_frequency_kwargs(frequency) if frequency != "bimonthly" else get_frequency_kwargs("monthly") # weekly, fortnightly and daily intervals have fixed days so no problems end_date = add_to_date(start_date, **kwargs) - relativedelta(days=1) if frequency != "bimonthly": return dict(end_date=end_date.strftime(DATE_FORMAT)) else: return dict(end_date="") def get_month_details(year, month): ysd = frappe.db.get_value("Fiscal Year", year, "year_start_date") if ysd: import calendar import datetime diff_mnt = cint(month) - cint(ysd.month) if diff_mnt < 0: diff_mnt = 12 - int(ysd.month) + cint(month) msd = ysd + relativedelta(months=diff_mnt) # month start date month_days = cint(calendar.monthrange(cint(msd.year), cint(month))[1]) # days in month mid_start = datetime.date(msd.year, cint(month), 16) # month mid start date mid_end = datetime.date(msd.year, cint(month), 15) # month mid end date med = datetime.date(msd.year, cint(month), month_days) # month end date return frappe._dict( { "year": msd.year, "month_start_date": msd, "month_end_date": med, "month_mid_start_date": mid_start, "month_mid_end_date": mid_end, "month_days": month_days, } ) else: frappe.throw(_("Fiscal Year {0} not found").format(year)) def log_payroll_failure(process, payroll_entry, error): error_log = frappe.log_error( title=_("Salary Slip {0} failed for Payroll Entry {1}").format(process, payroll_entry.name) ) message_log = frappe.message_log.pop() if frappe.message_log else str(error) try: 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 error_message += "\n" + _("Check Error Log {0} for more details.").format( get_link_to_form("Error Log", error_log.name) ) payroll_entry.db_set({"error_message": error_message, "status": "Failed"}) def create_salary_slips_for_employees(employees, args, publish_progress=True): payroll_entry = frappe.get_cached_doc("Payroll Entry", args.payroll_entry) try: salary_slips_exist_for = get_existing_salary_slips(employees, args) count = 0 employees = list(set(employees) - set(salary_slips_exist_for)) for emp in employees: args.update({"doctype": "Salary Slip", "employee": emp}) frappe.get_doc(args).insert() count += 1 if publish_progress: frappe.publish_progress( count * 100 / len(employees), title=_("Creating Salary Slips..."), ) payroll_entry.db_set({"status": "Submitted", "salary_slips_created": 1, "error_message": ""}) if salary_slips_exist_for: frappe.msgprint( _( "Salary Slips already exist for employees {}, and will not be processed by this payroll." ).format(frappe.bold(", ".join(emp for emp in salary_slips_exist_for))), title=_("Message"), indicator="orange", ) except Exception as e: frappe.db.rollback() log_payroll_failure("creation", payroll_entry, e) finally: frappe.db.commit() # nosemgrep frappe.publish_realtime("completed_salary_slip_creation", user=frappe.session.user) def show_payroll_submission_status(submitted, unsubmitted, payroll_entry): if not submitted and not unsubmitted: frappe.msgprint( _( "No salary slip found to submit for the above selected criteria OR salary slip already submitted" ) ) elif submitted and not unsubmitted: frappe.msgprint( _("Salary Slips submitted for period from {0} to {1}").format( payroll_entry.start_date, payroll_entry.end_date ), title=_("Success"), indicator="green", ) elif unsubmitted: frappe.msgprint( _("Could not submit some Salary Slips: {}").format( ", ".join(get_link_to_form("Salary Slip", entry) for entry in unsubmitted) ), title=_("Failure"), indicator="red", ) def get_existing_salary_slips(employees, args): SalarySlip = frappe.qb.DocType("Salary Slip") return ( frappe.qb.from_(SalarySlip) .select(SalarySlip.employee) .distinct() .where( (SalarySlip.docstatus != 2) & (SalarySlip.company == args.company) & (SalarySlip.payroll_entry == args.payroll_entry) & (SalarySlip.start_date >= args.start_date) & (SalarySlip.end_date <= args.end_date) & (SalarySlip.employee.isin(employees)) ) ).run(pluck=True) def submit_salary_slips_for_employees(payroll_entry, salary_slips, publish_progress=True): try: submitted = [] unsubmitted = [] frappe.flags.via_payroll_entry = True count = 0 for entry in salary_slips: salary_slip = frappe.get_doc("Salary Slip", entry[0]) if salary_slip.net_pay < 0: unsubmitted.append(entry[0]) else: try: salary_slip.submit() submitted.append(salary_slip) except frappe.ValidationError: unsubmitted.append(entry[0]) count += 1 if publish_progress: frappe.publish_progress( count * 100 / len(salary_slips), title=_("Submitting Salary Slips...") ) if submitted: payroll_entry.make_accrual_jv_entry(submitted) payroll_entry.email_salary_slip(submitted) payroll_entry.db_set({"salary_slips_submitted": 1, "status": "Submitted", "error_message": ""}) show_payroll_submission_status(submitted, unsubmitted, payroll_entry) except Exception as e: frappe.db.rollback() log_payroll_failure("submission", payroll_entry, e) finally: frappe.db.commit() # nosemgrep frappe.publish_realtime("completed_salary_slip_submission", user=frappe.session.user) frappe.flags.via_payroll_entry = False @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def get_payroll_entries_for_jv(doctype, txt, searchfield, start, page_len, filters): # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql return frappe.db.sql( f""" select name from `tabPayroll Entry` where `{searchfield}` LIKE %(txt)s and name not in (select reference_name from `tabJournal Entry Account` where reference_type="Payroll Entry") order by name limit %(start)s, %(page_len)s""", {"txt": "%%%s%%" % txt, "start": start, "page_len": page_len}, ) def get_employee_list( filters: frappe._dict, searchfield=None, search_string=None, fields: list[str] | None = None, as_dict=True, limit=None, offset=None, ignore_match_conditions=False, ) -> list: sal_struct = get_salary_structure( filters.company, filters.currency, filters.salary_slip_based_on_timesheet, filters.payroll_frequency, ) if not sal_struct: return [] emp_list = get_filtered_employees( sal_struct, filters, searchfield, search_string, fields, as_dict=as_dict, limit=limit, offset=offset, ignore_match_conditions=ignore_match_conditions, ) if as_dict: employees_to_check = {emp.employee: emp for emp in emp_list} else: employees_to_check = {emp[0]: emp for emp in emp_list} return remove_payrolled_employees(employees_to_check, filters.start_date, filters.end_date) @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def employee_query(doctype, txt, searchfield, start, page_len, filters): filters = frappe._dict(filters) if not filters.payroll_frequency: frappe.throw(_("Select Payroll Frequency.")) employee_list = get_employee_list( filters, searchfield=searchfield, search_string=txt, fields=["name", "employee_name"], as_dict=False, limit=page_len, offset=start, ) return employee_list def get_salary_withholdings( start_date: str, end_date: str, employee: str | None = None, pluck: str | None = None, ) -> list[str] | list[dict]: Withholding = frappe.qb.DocType("Salary Withholding") WithholdingCycle = frappe.qb.DocType("Salary Withholding Cycle") withheld_salaries = ( frappe.qb.from_(Withholding) .join(WithholdingCycle) .on(WithholdingCycle.parent == Withholding.name) .select( Withholding.employee, Withholding.name.as_("salary_withholding"), WithholdingCycle.name.as_("salary_withholding_cycle"), ) .where( (WithholdingCycle.from_date == start_date) & (WithholdingCycle.to_date == end_date) & (WithholdingCycle.docstatus == 1) & (WithholdingCycle.is_salary_released != 1) ) ) if employee: withheld_salaries = withheld_salaries.where(Withholding.employee == employee) if pluck: return withheld_salaries.run(pluck=pluck) return withheld_salaries.run(as_dict=True)
2302_79757062/hrms
hrms/payroll/doctype/payroll_entry/payroll_entry.py
Python
agpl-3.0
47,672
def get_data(): return { "fieldname": "payroll_entry", "non_standard_fieldnames": { "Journal Entry": "reference_name", "Payment Entry": "reference_name", }, "transactions": [{"items": ["Salary Slip", "Journal Entry"]}], }
2302_79757062/hrms
hrms/payroll/doctype/payroll_entry/payroll_entry_dashboard.py
Python
agpl-3.0
238
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt // render frappe.listview_settings["Payroll Entry"] = { has_indicator_for_draft: 1, get_indicator: function (doc) { var status_color = { Draft: "red", Submitted: "blue", Queued: "orange", Failed: "red", Cancelled: "red", }; return [__(doc.status), status_color[doc.status], "status,=," + doc.status]; }, };
2302_79757062/hrms
hrms/payroll/doctype/payroll_entry/payroll_entry_list.js
JavaScript
agpl-3.0
461
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Payroll Period", { onload: function (frm) { frm.trigger("set_start_date"); }, set_start_date: function (frm) { if (!frm.doc.__islocal) return; frappe.db .get_list("Payroll Period", { fields: ["end_date"], order_by: "end_date desc", limit: 1, }) .then((result) => { // set start date based on end date of the last payroll period if found // else set it based on the current fiscal year's start date if (result.length) { const last_end_date = result[0].end_date; frm.set_value("start_date", frappe.datetime.add_days(last_end_date, 1)); } else { frm.set_value("start_date", frappe.defaults.get_default("year_start_date")); } }); }, start_date: function (frm) { frm.set_value( "end_date", frappe.datetime.add_days(frappe.datetime.add_months(frm.doc.start_date, 12), -1), ); }, });
2302_79757062/hrms
hrms/payroll/doctype/payroll_period/payroll_period.js
JavaScript
agpl-3.0
1,002
# 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_months, cint, date_diff, flt, formatdate, getdate from frappe.utils.caching import redis_cache from hrms.hr.utils import get_exact_month_diff, get_holiday_dates_for_employee class PayrollPeriod(Document): def validate(self): self.validate_from_to_dates("start_date", "end_date") self.validate_overlap() def clear_cache(self): get_payroll_period.clear_cache() return super().clear_cache() def validate_overlap(self): query = """ select name from `tab{0}` where name != %(name)s and company = %(company)s and (start_date between %(start_date)s and %(end_date)s \ or end_date between %(start_date)s and %(end_date)s \ or (start_date < %(start_date)s and end_date > %(end_date)s)) """ if not self.name: # hack! if name is null, it could cause problems with != self.name = "New " + self.doctype overlap_doc = frappe.db.sql( query.format(self.doctype), { "start_date": self.start_date, "end_date": self.end_date, "name": self.name, "company": self.company, }, as_dict=1, ) if overlap_doc: msg = ( _("A {0} exists between {1} and {2} (").format( self.doctype, formatdate(self.start_date), formatdate(self.end_date) ) + f""" <b><a href="/app/Form/{self.doctype}/{overlap_doc[0].name}">{overlap_doc[0].name}</a></b>""" + _(") for {0}").format(self.company) ) frappe.throw(msg) def get_payroll_period_days(start_date, end_date, employee, company=None): if not company: company = frappe.db.get_value("Employee", employee, "company") payroll_period = frappe.db.sql( """ select name, start_date, end_date from `tabPayroll Period` where company=%(company)s and %(start_date)s between start_date and end_date and %(end_date)s between start_date and end_date """, {"company": company, "start_date": start_date, "end_date": end_date}, ) if len(payroll_period) > 0: actual_no_of_days = date_diff(getdate(payroll_period[0][2]), getdate(payroll_period[0][1])) + 1 working_days = actual_no_of_days if not cint(frappe.db.get_single_value("Payroll Settings", "include_holidays_in_total_working_days")): holidays = get_holiday_dates_for_employee( employee, getdate(payroll_period[0][1]), getdate(payroll_period[0][2]) ) working_days -= len(holidays) return payroll_period[0][0], working_days, actual_no_of_days return False, False, False @redis_cache() def get_payroll_period(from_date, to_date, company): PayrollPeriod = frappe.qb.DocType("Payroll Period") payroll_period = ( frappe.qb.from_(PayrollPeriod) .select(PayrollPeriod.name, PayrollPeriod.start_date, PayrollPeriod.end_date) .where( (PayrollPeriod.start_date <= from_date) & (PayrollPeriod.end_date >= to_date) & (PayrollPeriod.company == company) ) ).run(as_dict=1) return payroll_period[0] if payroll_period else None def get_period_factor( employee, start_date, end_date, payroll_frequency, payroll_period, depends_on_payment_days=0, joining_date=None, relieving_date=None, ): # TODO if both deduct checked update the factor to make tax consistent period_start, period_end = payroll_period.start_date, payroll_period.end_date if not joining_date and not relieving_date: joining_date, relieving_date = frappe.get_cached_value( "Employee", employee, ["date_of_joining", "relieving_date"] ) if getdate(joining_date) > getdate(period_start): period_start = joining_date if relieving_date and getdate(relieving_date) < getdate(period_end): period_end = relieving_date total_sub_periods, remaining_sub_periods = 0.0, 0.0 if payroll_frequency == "Monthly" and not depends_on_payment_days: total_sub_periods = get_exact_month_diff(payroll_period.end_date, payroll_period.start_date) remaining_sub_periods = get_exact_month_diff(period_end, start_date) else: salary_days = date_diff(end_date, start_date) + 1 days_in_payroll_period = date_diff(payroll_period.end_date, payroll_period.start_date) + 1 total_sub_periods = flt(days_in_payroll_period) / flt(salary_days) remaining_days_in_payroll_period = date_diff(period_end, start_date) + 1 remaining_sub_periods = flt(remaining_days_in_payroll_period) / flt(salary_days) return total_sub_periods, remaining_sub_periods
2302_79757062/hrms
hrms/payroll/doctype/payroll_period/payroll_period.py
Python
agpl-3.0
4,471
def get_data(): return { "fieldname": "payroll_period", "transactions": [ {"items": ["Employee Tax Exemption Proof Submission", "Employee Tax Exemption Declaration"]}, ], }
2302_79757062/hrms
hrms/payroll/doctype/payroll_period/payroll_period_dashboard.py
Python
agpl-3.0
184
# 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 PayrollPeriodDate(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/payroll_period_date/payroll_period_date.py
Python
agpl-3.0
223
// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Payroll Settings", { refresh: function (frm) { frm.set_query("sender", () => { return { filters: { enable_outgoing: 1, }, }; }); }, encrypt_salary_slips_in_emails: function (frm) { let encrypt_state = frm.doc.encrypt_salary_slips_in_emails; frm.set_df_property("password_policy", "reqd", encrypt_state); }, validate: function (frm) { let policy = frm.doc.password_policy; if (policy) { if (policy.includes(" ") || policy.includes("--")) { frappe.msgprint( __( "Password policy cannot contain spaces or simultaneous hyphens. The format will be restructured automatically", ), ); } frm.set_value( "password_policy", policy .split(new RegExp(" |-", "g")) .filter((token) => token) .join("-"), ); } }, });
2302_79757062/hrms
hrms/payroll/doctype/payroll_settings/payroll_settings.js
JavaScript
agpl-3.0
943
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.custom.doctype.property_setter.property_setter import make_property_setter from frappe.model.document import Document from frappe.utils import cint class PayrollSettings(Document): def validate(self): self.validate_password_policy() if not self.daily_wages_fraction_for_half_day: self.daily_wages_fraction_for_half_day = 0.5 def validate_password_policy(self): if self.email_salary_slip_to_employee and self.encrypt_salary_slips_in_emails: if not self.password_policy: frappe.throw(_("Password policy for Salary Slips is not set")) def on_update(self): self.toggle_rounded_total() frappe.clear_cache() def toggle_rounded_total(self): self.disable_rounded_total = cint(self.disable_rounded_total) make_property_setter( "Salary Slip", "rounded_total", "hidden", self.disable_rounded_total, "Check", validate_fields_for_doctype=False, ) make_property_setter( "Salary Slip", "rounded_total", "print_hide", self.disable_rounded_total, "Check", validate_fields_for_doctype=False, )
2302_79757062/hrms
hrms/payroll/doctype/payroll_settings/payroll_settings.py
Python
agpl-3.0
1,220
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Retention Bonus", { setup: function (frm) { frm.set_query("employee", function () { if (!frm.doc.company) { frappe.msgprint(__("Please Select Company First")); } return { filters: { status: "Active", company: frm.doc.company, }, }; }); frm.set_query("salary_component", function () { return { filters: { type: "Earning", }, }; }); }, employee: 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(); } }, }); } }, });
2302_79757062/hrms
hrms/payroll/doctype/retention_bonus/retention_bonus.js
JavaScript
agpl-3.0
933
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import getdate from hrms.hr.utils import validate_active_employee class RetentionBonus(Document): def validate(self): validate_active_employee(self.employee) if getdate(self.bonus_payment_date) < getdate(): frappe.throw(_("Bonus Payment Date cannot be a past date")) def on_submit(self): company = frappe.db.get_value("Employee", self.employee, "company") additional_salary = self.get_additional_salary() if not additional_salary: additional_salary = frappe.new_doc("Additional Salary") additional_salary.employee = self.employee additional_salary.salary_component = self.salary_component additional_salary.amount = self.bonus_amount additional_salary.payroll_date = self.bonus_payment_date additional_salary.company = company additional_salary.overwrite_salary_structure_amount = 0 additional_salary.ref_doctype = self.doctype additional_salary.ref_docname = self.name additional_salary.submit() # self.db_set('additional_salary', additional_salary.name) else: bonus_added = ( frappe.db.get_value("Additional Salary", additional_salary, "amount") + self.bonus_amount ) frappe.db.set_value("Additional Salary", additional_salary, "amount", bonus_added) self.db_set("additional_salary", additional_salary) def on_cancel(self): additional_salary = self.get_additional_salary() if additional_salary: bonus_removed = ( frappe.db.get_value("Additional Salary", additional_salary, "amount") - self.bonus_amount ) if bonus_removed == 0: frappe.get_doc("Additional Salary", additional_salary).cancel() else: frappe.db.set_value("Additional Salary", additional_salary, "amount", bonus_removed) # self.db_set('additional_salary', '') def get_additional_salary(self): return frappe.db.exists( "Additional Salary", { "employee": self.employee, "salary_component": self.salary_component, "payroll_date": self.bonus_payment_date, "company": self.company, "docstatus": 1, "ref_doctype": self.doctype, "ref_docname": self.name, "disabled": 0, }, )
2302_79757062/hrms
hrms/payroll/doctype/retention_bonus/retention_bonus.py
Python
agpl-3.0
2,302
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Salary Component", { setup: function (frm) { frm.set_query("account", "accounts", function (doc, cdt, cdn) { var d = locals[cdt][cdn]; return { filters: { is_group: 0, company: d.company, }, }; }); frm.set_query("earning_component_group", function () { return { filters: { is_group: 1, is_flexible_benefit: 1, }, }; }); }, refresh: function (frm) { hrms.payroll_utils.set_autocompletions_for_condition_and_formula(frm); if (!frm.doc.__islocal) { frm.trigger("add_update_structure_button"); frm.add_custom_button( __("Salary Structure"), () => { frm.trigger("create_salary_structure"); }, __("Create"), ); } }, is_flexible_benefit: function (frm) { if (frm.doc.is_flexible_benefit) { set_value_for_condition_and_formula(frm); frm.set_value("formula", ""); frm.set_value("amount", 0); } }, type: function (frm) { if (frm.doc.type == "Earning") { frm.set_value("is_tax_applicable", 1); frm.set_value("variable_based_on_taxable_salary", 0); } if (frm.doc.type == "Deduction") { frm.set_value("is_tax_applicable", 0); frm.set_value("is_flexible_benefit", 0); } }, variable_based_on_taxable_salary: function (frm) { if (frm.doc.variable_based_on_taxable_salary) { set_value_for_condition_and_formula(frm); } }, create_separate_payment_entry_against_benefit_claim: function (frm) { if (frm.doc.create_separate_payment_entry_against_benefit_claim) { frm.set_df_property("accounts", "reqd", 1); frm.set_value("only_tax_impact", 0); } else { frm.set_df_property("accounts", "reqd", 0); } }, only_tax_impact: function (frm) { if (frm.only_tax_impact) { frm.set_value("create_separate_payment_entry_against_benefit_claim", 0); } }, add_update_structure_button: function (frm) { for (const df of ["Condition", "Formula"]) { frm.add_custom_button( __("Sync {0}", [df]), function () { frappe .call({ method: "get_structures_to_be_updated", doc: frm.doc, }) .then((r) => { if (r.message.length) frm.events.update_salary_structures(frm, df, r.message); else frappe.msgprint({ message: __( "Salary Component {0} is currently not used in any Salary Structure.", [frm.doc.name.bold()], ), title: __("No Salary Structures"), indicator: "orange", }); }); }, __("Update Salary Structures"), ); } }, update_salary_structures: function (frm, df, structures) { let msg = __("{0} will be updated for the following Salary Structures: {1}.", [ df, frappe.utils.comma_and( structures.map((d) => frappe.utils.get_form_link("Salary Structure", d, true).bold(), ), ), ]); msg += "<br>"; msg += __("Are you sure you want to proceed?"); frappe.confirm(msg, () => { frappe .call({ method: "update_salary_structures", doc: frm.doc, args: { structures: structures, field: df.toLowerCase(), value: frm.get_field(df.toLowerCase()).value || "", }, }) .then((r) => { if (!r.exc) { frappe.show_alert({ message: __("Salary Structures updated successfully"), indicator: "green", }); } }); }); }, create_salary_structure: function (frm) { frappe.model.with_doctype("Salary Structure", () => { const salary_structure = frappe.model.get_new_doc("Salary Structure"); const salary_detail = frappe.model.add_child( salary_structure, frm.doc.type === "Earning" ? "earnings" : "deductions", ); salary_detail.salary_component = frm.doc.name; frappe.set_route("Form", "Salary Structure", salary_structure.name); }); }, }); var set_value_for_condition_and_formula = function (frm) { frm.set_value("formula", null); frm.set_value("condition", null); frm.set_value("amount_based_on_formula", 0); frm.set_value("statistical_component", 0); frm.set_value("do_not_include_in_total", 0); frm.set_value("depends_on_payment_days", 0); };
2302_79757062/hrms
hrms/payroll/doctype/salary_component/salary_component.js
JavaScript
agpl-3.0
4,226
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import copy import frappe from frappe import _ from frappe.model.document import Document from frappe.model.naming import append_number_if_name_exists from hrms.payroll.utils import sanitize_expression class SalaryComponent(Document): def before_validate(self): self._condition, self.condition = self.condition, sanitize_expression(self.condition) self._formula, self.formula = self.formula, sanitize_expression(self.formula) def validate(self): self.validate_abbr() self.validate_accounts() def on_update(self): # set old values (allowing multiline strings for better readability in the doctype form) if self._condition != self.condition: self.db_set("condition", self._condition) if self._formula != self.formula: self.db_set("formula", self._formula) def clear_cache(self): from hrms.payroll.doctype.salary_slip.salary_slip import ( SALARY_COMPONENT_VALUES, TAX_COMPONENTS_BY_COMPANY, ) frappe.cache().delete_value(SALARY_COMPONENT_VALUES) frappe.cache().delete_value(TAX_COMPONENTS_BY_COMPANY) return super().clear_cache() def validate_abbr(self): if not self.salary_component_abbr: self.salary_component_abbr = "".join([c[0] for c in self.salary_component.split()]).upper() self.salary_component_abbr = self.salary_component_abbr.strip() self.salary_component_abbr = append_number_if_name_exists( "Salary Component", self.salary_component_abbr, "salary_component_abbr", separator="_", filters={"name": ["!=", self.name]}, ) def validate_accounts(self): if not (self.statistical_component or (self.accounts and all(d.account for d in self.accounts))): frappe.msgprint( title=_("Warning"), msg=_("Accounts not set for Salary Component {0}").format(self.name), indicator="orange", ) @frappe.whitelist() def get_structures_to_be_updated(self): SalaryStructure = frappe.qb.DocType("Salary Structure") SalaryDetail = frappe.qb.DocType("Salary Detail") return ( frappe.qb.from_(SalaryStructure) .inner_join(SalaryDetail) .on(SalaryStructure.name == SalaryDetail.parent) .select(SalaryStructure.name) .where((SalaryDetail.salary_component == self.name) & (SalaryStructure.docstatus != 2)) .run(pluck=True) ) @frappe.whitelist() def update_salary_structures(self, field, value, structures=None): if not structures: structures = self.get_structures_to_be_updated() for structure in structures: salary_structure = frappe.get_doc("Salary Structure", structure) # this is only used for versioning and we do not want # to make separate db calls by using load_doc_before_save # which proves to be expensive while doing bulk replace salary_structure._doc_before_save = copy.deepcopy(salary_structure) salary_detail_row = next( (d for d in salary_structure.get(f"{self.type.lower()}s") if d.salary_component == self.name), None, ) salary_detail_row.set(field, value) salary_structure.db_update_all() salary_structure.flags.updater_reference = { "doctype": self.doctype, "docname": self.name, "label": _("via Salary Component sync"), } salary_structure.save_version()
2302_79757062/hrms
hrms/payroll/doctype/salary_component/salary_component.py
Python
agpl-3.0
3,271
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from frappe.model.document import Document class SalaryComponentAccount(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/salary_component_account/salary_component_account.py
Python
agpl-3.0
212
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from frappe.model.document import Document class SalaryDetail(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/salary_detail/salary_detail.py
Python
agpl-3.0
202
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.ui.form.on("Salary Slip", { setup: function (frm) { $.each(["earnings", "deductions"], function (i, table_fieldname) { frm.get_field(table_fieldname).grid.editable_fields = [ { fieldname: "salary_component", columns: 6 }, { fieldname: "amount", columns: 4 }, ]; }); frm.fields_dict["timesheets"].grid.get_field("time_sheet").get_query = function () { return { filters: { employee: frm.doc.employee, }, }; }; frm.set_query("salary_component", "earnings", function () { return { filters: { type: "earning", }, }; }); frm.set_query("salary_component", "deductions", function () { return { filters: { type: "deduction", }, }; }); frm.set_query("employee", function () { return { query: "erpnext.controllers.queries.employee_query", }; }); frm.trigger("set_payment_days_description"); }, validate: function (frm) { frm.trigger("set_payment_days_description"); }, start_date: function (frm) { if (frm.doc.start_date) { frm.trigger("set_end_date"); } }, end_date: function (frm) { frm.events.get_emp_and_working_day_details(frm); }, set_end_date: function (frm) { frappe.call({ method: "hrms.payroll.doctype.payroll_entry.payroll_entry.get_end_date", args: { frequency: frm.doc.payroll_frequency, start_date: frm.doc.start_date, }, callback: function (r) { if (r.message) { frm.set_value("end_date", r.message.end_date); } }, }); }, company: function (frm) { var company = locals[":Company"][frm.doc.company]; if (!frm.doc.letter_head && company.default_letter_head) { frm.set_value("letter_head", company.default_letter_head); } }, currency: function (frm) { frm.trigger("update_currency_changes"); }, update_currency_changes: function (frm) { frm.trigger("set_exchange_rate"); frm.trigger("set_dynamic_labels"); }, set_dynamic_labels: function (frm) { if (frm.doc.employee && frm.doc.currency) { frappe.run_serially([ () => frm.events.change_form_labels(frm), () => frm.events.change_grid_labels(frm), () => frm.refresh_fields(), ]); } }, set_exchange_rate: function (frm) { const company_currency = erpnext.get_currency(frm.doc.company); if (frm.doc.docstatus === 0) { if (frm.doc.currency) { var from_currency = frm.doc.currency; if (from_currency != company_currency) { frm.events.hide_loan_section(frm); frappe.call({ method: "erpnext.setup.utils.get_exchange_rate", args: { from_currency: from_currency, to_currency: company_currency, }, callback: function (r) { if (r.message) { frm.set_value("exchange_rate", flt(r.message)); frm.set_df_property("exchange_rate", "hidden", 0); frm.set_df_property( "exchange_rate", "description", "1 " + frm.doc.currency + " = [?] " + company_currency, ); } }, }); } else { frm.set_value("exchange_rate", 1.0); frm.set_df_property("exchange_rate", "hidden", 1); frm.set_df_property("exchange_rate", "description", ""); } } } }, exchange_rate: function (frm) { set_totals(frm); }, hide_loan_section: function (frm) { frm.set_df_property("section_break_43", "hidden", 1); }, change_form_labels: function (frm) { const company_currency = erpnext.get_currency(frm.doc.company); frm.set_currency_labels( [ "base_hour_rate", "base_gross_pay", "base_total_deduction", "base_net_pay", "base_rounded_total", "base_total_in_words", "base_year_to_date", "base_month_to_date", "base_gross_year_to_date", ], company_currency, ); frm.set_currency_labels( [ "hour_rate", "gross_pay", "total_deduction", "net_pay", "rounded_total", "total_in_words", "year_to_date", "month_to_date", "gross_year_to_date", ], frm.doc.currency, ); // toggle fields frm.toggle_display( [ "exchange_rate", "base_hour_rate", "base_gross_pay", "base_total_deduction", "base_net_pay", "base_rounded_total", "base_total_in_words", "base_year_to_date", "base_month_to_date", "base_gross_year_to_date", ], frm.doc.currency != company_currency, ); }, change_grid_labels: function (frm) { let fields = [ "amount", "year_to_date", "default_amount", "additional_amount", "tax_on_flexible_benefit", "tax_on_additional_salary", ]; frm.set_currency_labels(fields, frm.doc.currency, "earnings"); frm.set_currency_labels(fields, frm.doc.currency, "deductions"); }, refresh: function (frm) { frm.trigger("toggle_fields"); var salary_detail_fields = [ "formula", "abbr", "statistical_component", "variable_based_on_taxable_salary", ]; frm.fields_dict["earnings"].grid.set_column_disp(salary_detail_fields, false); frm.fields_dict["deductions"].grid.set_column_disp(salary_detail_fields, false); frm.trigger("set_dynamic_labels"); }, salary_slip_based_on_timesheet: function (frm) { frm.trigger("toggle_fields"); frm.events.get_emp_and_working_day_details(frm); }, payroll_frequency: function (frm) { frm.trigger("toggle_fields"); frm.set_value("end_date", ""); }, employee: function (frm) { frm.events.get_emp_and_working_day_details(frm); }, leave_without_pay: function (frm) { if (frm.doc.employee && frm.doc.start_date && frm.doc.end_date) { return frappe.call({ method: "process_salary_based_on_working_days", doc: frm.doc, callback: function () { frm.refresh(); }, }); } }, toggle_fields: function (frm) { frm.toggle_display( ["hourly_wages", "timesheets"], cint(frm.doc.salary_slip_based_on_timesheet) === 1, ); frm.toggle_display( ["payment_days", "total_working_days", "leave_without_pay"], frm.doc.payroll_frequency != "", ); }, get_emp_and_working_day_details: function (frm) { if (frm.doc.employee) { return frappe.call({ method: "get_emp_and_working_day_details", doc: frm.doc, callback: function (r) { frm.refresh(); // triggering events explicitly because structure is set on the server-side // and currency is fetched from the structure frm.trigger("update_currency_changes"); }, }); } }, set_payment_days_description: function (frm) { if (frm.doc.docstatus !== 0) return; frappe.call("hrms.payroll.utils.get_payroll_settings_for_payment_days").then((r) => { const { payroll_based_on, consider_unmarked_attendance_as, include_holidays_in_total_working_days, consider_marked_attendance_on_holidays, } = r.message; const message = ` <div class="small text-muted pb-3"> ${__("Note").bold()}: ${__("Payment Days calculations are based on these Payroll Settings")}: <br><br>${__("Payroll Based On")}: ${payroll_based_on.bold()} <br>${__("Consider Unmarked Attendance As")}: ${consider_unmarked_attendance_as.bold()} <br>${__("Consider Marked Attendance on Holidays")}: ${ cint(include_holidays_in_total_working_days) && cint(consider_marked_attendance_on_holidays) ? __("Enabled").bold() : __("Disabled").bold() } <br><br> ${__("Click {0} to change the configuration and then resave salary slip", [ frappe.utils.get_form_link( "Payroll Settings", "Payroll Settings", true, "<u>" + __("here") + "</u>", ), ])} </div> `; set_field_options("payment_days_calculation_help", message); }); }, }); frappe.ui.form.on("Salary Slip Timesheet", { time_sheet: function (frm) { set_totals(frm); }, timesheets_remove: function (frm) { set_totals(frm); }, }); var set_totals = function (frm) { if (frm.doc.docstatus === 0 && frm.doc.doctype === "Salary Slip") { if (frm.doc.earnings || frm.doc.deductions) { frappe.call({ method: "set_totals", doc: frm.doc, callback: function () { frm.refresh_fields(); }, }); } } }; frappe.ui.form.on("Salary Detail", { amount: function (frm) { set_totals(frm); }, earnings_remove: function (frm) { set_totals(frm); }, deductions_remove: function (frm) { set_totals(frm); }, salary_component: function (frm, cdt, cdn) { var child = locals[cdt][cdn]; if (child.salary_component) { frappe.call({ method: "frappe.client.get", args: { doctype: "Salary Component", name: child.salary_component, }, callback: function (data) { if (data.message) { var result = data.message; frappe.model.set_value(cdt, cdn, "condition", result.condition); frappe.model.set_value( cdt, cdn, "amount_based_on_formula", result.amount_based_on_formula, ); if (result.amount_based_on_formula === 1) { frappe.model.set_value(cdt, cdn, "formula", result.formula); } else { frappe.model.set_value(cdt, cdn, "amount", result.amount); } frappe.model.set_value( cdt, cdn, "statistical_component", result.statistical_component, ); frappe.model.set_value( cdt, cdn, "depends_on_payment_days", result.depends_on_payment_days, ); frappe.model.set_value( cdt, cdn, "do_not_include_in_total", result.do_not_include_in_total, ); frappe.model.set_value( cdt, cdn, "variable_based_on_taxable_salary", result.variable_based_on_taxable_salary, ); frappe.model.set_value( cdt, cdn, "is_tax_applicable", result.is_tax_applicable, ); frappe.model.set_value( cdt, cdn, "is_flexible_benefit", result.is_flexible_benefit, ); refresh_field("earnings"); refresh_field("deductions"); } }, }); } }, amount_based_on_formula: function (frm, cdt, cdn) { var child = locals[cdt][cdn]; if (child.amount_based_on_formula === 1) { frappe.model.set_value(cdt, cdn, "amount", null); } else { frappe.model.set_value(cdt, cdn, "formula", null); } }, });
2302_79757062/hrms
hrms/payroll/doctype/salary_slip/salary_slip.js
JavaScript
agpl-3.0
10,320
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import unicodedata from datetime import date import frappe from frappe import _, msgprint from frappe.model.naming import make_autoname from frappe.query_builder import Order from frappe.query_builder.functions import Count, Sum from frappe.utils import ( add_days, ceil, cint, cstr, date_diff, floor, flt, formatdate, get_first_day, get_link_to_form, getdate, money_in_words, rounded, ) from frappe.utils.background_jobs import enqueue import erpnext from erpnext.accounts.utils import get_fiscal_year from erpnext.setup.doctype.employee.employee import get_holiday_list_for_employee from erpnext.utilities.transaction_base import TransactionBase from hrms.hr.utils import validate_active_employee from hrms.payroll.doctype.additional_salary.additional_salary import get_additional_salaries from hrms.payroll.doctype.employee_benefit_application.employee_benefit_application import ( get_benefit_component_amount, ) from hrms.payroll.doctype.employee_benefit_claim.employee_benefit_claim import ( get_benefit_claim_amount, get_last_payroll_period_benefits, ) from hrms.payroll.doctype.payroll_entry.payroll_entry import get_salary_withholdings, get_start_end_dates from hrms.payroll.doctype.payroll_period.payroll_period import ( get_payroll_period, get_period_factor, ) from hrms.payroll.doctype.salary_slip.salary_slip_loan_utils import ( cancel_loan_repayment_entry, make_loan_repayment_entry, set_loan_repayment, ) from hrms.payroll.utils import sanitize_expression from hrms.utils.holiday_list import get_holiday_dates_between # cache keys HOLIDAYS_BETWEEN_DATES = "holidays_between_dates" LEAVE_TYPE_MAP = "leave_type_map" SALARY_COMPONENT_VALUES = "salary_component_values" TAX_COMPONENTS_BY_COMPANY = "tax_components_by_company" class SalarySlip(TransactionBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.series = f"Sal Slip/{self.employee}/.#####" self.whitelisted_globals = { "int": int, "float": float, "long": int, "round": round, "rounded": rounded, "date": date, "getdate": getdate, "ceil": ceil, "floor": floor, } def autoname(self): self.name = make_autoname(self.series) @property def joining_date(self): if not hasattr(self, "__joining_date"): self.__joining_date = frappe.get_cached_value( "Employee", self.employee, "date_of_joining", ) return self.__joining_date @property def relieving_date(self): if not hasattr(self, "__relieving_date"): self.__relieving_date = frappe.get_cached_value( "Employee", self.employee, "relieving_date", ) return self.__relieving_date @property def payroll_period(self): if not hasattr(self, "__payroll_period"): self.__payroll_period = get_payroll_period(self.start_date, self.end_date, self.company) return self.__payroll_period @property def actual_start_date(self): if not hasattr(self, "__actual_start_date"): self.__actual_start_date = self.start_date if self.joining_date and getdate(self.start_date) < self.joining_date <= getdate(self.end_date): self.__actual_start_date = self.joining_date return self.__actual_start_date @property def actual_end_date(self): if not hasattr(self, "__actual_end_date"): self.__actual_end_date = self.end_date if self.relieving_date and getdate(self.start_date) <= self.relieving_date < getdate( self.end_date ): self.__actual_end_date = self.relieving_date return self.__actual_end_date def validate(self): self.check_salary_withholding() self.status = self.get_status() validate_active_employee(self.employee) self.validate_dates() self.check_existing() if not self.salary_slip_based_on_timesheet: self.get_date_details() if not (len(self.get("earnings")) or len(self.get("deductions"))): # get details from salary structure self.get_emp_and_working_day_details() else: self.get_working_days_details(lwp=self.leave_without_pay) self.set_salary_structure_assignment() self.calculate_net_pay() self.compute_year_to_date() self.compute_month_to_date() self.compute_component_wise_year_to_date() self.add_leave_balances() max_working_hours = frappe.db.get_single_value( "Payroll Settings", "max_working_hours_against_timesheet" ) if max_working_hours: if self.salary_slip_based_on_timesheet and (self.total_working_hours > int(max_working_hours)): frappe.msgprint( _("Total working hours should not be greater than max working hours {0}").format( max_working_hours ), alert=True, ) def check_salary_withholding(self): withholding = get_salary_withholdings(self.start_date, self.end_date, self.employee) if withholding: self.salary_withholding = withholding[0].salary_withholding self.salary_withholding_cycle = withholding[0].salary_withholding_cycle else: self.salary_withholding = None def set_net_total_in_words(self): doc_currency = self.currency company_currency = erpnext.get_company_currency(self.company) total = self.net_pay if self.is_rounding_total_disabled() else self.rounded_total base_total = self.base_net_pay if self.is_rounding_total_disabled() else self.base_rounded_total self.total_in_words = money_in_words(total, doc_currency) self.base_total_in_words = money_in_words(base_total, company_currency) def on_update(self): self.publish_update() def on_submit(self): if self.net_pay < 0: frappe.throw(_("Net Pay cannot be less than 0")) else: self.set_status() self.update_status(self.name) make_loan_repayment_entry(self) if not frappe.flags.via_payroll_entry and not frappe.flags.in_patch: email_salary_slip = cint( frappe.db.get_single_value("Payroll Settings", "email_salary_slip_to_employee") ) if email_salary_slip: self.email_salary_slip() self.update_payment_status_for_gratuity() def update_payment_status_for_gratuity(self): additional_salary = frappe.db.get_all( "Additional Salary", filters={ "payroll_date": ("between", [self.start_date, self.end_date]), "employee": self.employee, "ref_doctype": "Gratuity", "docstatus": 1, }, fields=["ref_docname", "name"], limit=1, ) if additional_salary: status = "Paid" if self.docstatus == 1 else "Unpaid" if additional_salary[0].name in [entry.additional_salary for entry in self.earnings]: frappe.db.set_value("Gratuity", additional_salary[0].ref_docname, "status", status) def on_cancel(self): self.set_status() self.update_status() self.update_payment_status_for_gratuity() cancel_loan_repayment_entry(self) self.publish_update() def publish_update(self): employee_user = frappe.db.get_value("Employee", self.employee, "user_id", cache=True) frappe.publish_realtime( event="hrms:update_salary_slips", message={"employee": self.employee}, user=employee_user, after_commit=True, ) def on_trash(self): from frappe.model.naming import revert_series_if_last revert_series_if_last(self.series, self.name) def get_status(self): if self.docstatus == 2: return "Cancelled" else: if self.salary_withholding: return "Withheld" elif self.docstatus == 0: return "Draft" elif self.docstatus == 1: return "Submitted" def validate_dates(self): self.validate_from_to_dates("start_date", "end_date") if not self.joining_date: frappe.throw( _("Please set the Date Of Joining for employee {0}").format(frappe.bold(self.employee_name)) ) if date_diff(self.end_date, self.joining_date) < 0: frappe.throw(_("Cannot create Salary Slip for Employee joining after Payroll Period")) if self.relieving_date and date_diff(self.relieving_date, self.start_date) < 0: frappe.throw(_("Cannot create Salary Slip for Employee who has left before Payroll Period")) def is_rounding_total_disabled(self): return cint(frappe.db.get_single_value("Payroll Settings", "disable_rounded_total")) def check_existing(self): if not self.salary_slip_based_on_timesheet: ss = frappe.qb.DocType("Salary Slip") query = ( frappe.qb.from_(ss) .select(ss.name) .where( (ss.start_date == self.start_date) & (ss.end_date == self.end_date) & (ss.docstatus != 2) & (ss.employee == self.employee) & (ss.name != self.name) ) ) if self.payroll_entry: query = query.where(ss.payroll_entry == self.payroll_entry) ret_exist = query.run() if ret_exist: frappe.throw( _("Salary Slip of employee {0} already created for this period").format(self.employee) ) else: for data in self.timesheets: if frappe.db.get_value("Timesheet", data.time_sheet, "status") == "Payrolled": frappe.throw( _("Salary Slip of employee {0} already created for time sheet {1}").format( self.employee, data.time_sheet ) ) def get_date_details(self): if not self.end_date: date_details = get_start_end_dates(self.payroll_frequency, self.start_date or self.posting_date) self.start_date = date_details.start_date self.end_date = date_details.end_date @frappe.whitelist() def get_emp_and_working_day_details(self): """First time, load all the components from salary structure""" if self.employee: self.set("earnings", []) self.set("deductions", []) if not self.salary_slip_based_on_timesheet: self.get_date_details() self.validate_dates() # getin leave details self.get_working_days_details() struct = self.check_sal_struct() if struct: self.set_salary_structure_doc() self.salary_slip_based_on_timesheet = ( self._salary_structure_doc.salary_slip_based_on_timesheet or 0 ) self.set_time_sheet() self.pull_sal_struct() def set_time_sheet(self): if self.salary_slip_based_on_timesheet: self.set("timesheets", []) Timesheet = frappe.qb.DocType("Timesheet") timesheets = ( frappe.qb.from_(Timesheet) .select(Timesheet.star) .where( (Timesheet.employee == self.employee) & (Timesheet.start_date.between(self.start_date, self.end_date)) & ((Timesheet.status == "Submitted") | (Timesheet.status == "Billed")) ) ).run(as_dict=1) for data in timesheets: self.append("timesheets", {"time_sheet": data.name, "working_hours": data.total_hours}) def check_sal_struct(self): ss = frappe.qb.DocType("Salary Structure") ssa = frappe.qb.DocType("Salary Structure Assignment") query = ( frappe.qb.from_(ssa) .join(ss) .on(ssa.salary_structure == ss.name) .select(ssa.salary_structure) .where( (ssa.docstatus == 1) & (ss.docstatus == 1) & (ss.is_active == "Yes") & (ssa.employee == self.employee) & ( (ssa.from_date <= self.start_date) | (ssa.from_date <= self.end_date) | (ssa.from_date <= self.joining_date) ) ) .orderby(ssa.from_date, order=Order.desc) .limit(1) ) if not self.salary_slip_based_on_timesheet and self.payroll_frequency: query = query.where(ss.payroll_frequency == self.payroll_frequency) st_name = query.run() if st_name: self.salary_structure = st_name[0][0] return self.salary_structure else: self.salary_structure = None frappe.msgprint( _("No active or default Salary Structure found for employee {0} for the given dates").format( self.employee ), title=_("Salary Structure Missing"), ) def pull_sal_struct(self): from hrms.payroll.doctype.salary_structure.salary_structure import make_salary_slip if self.salary_slip_based_on_timesheet: self.salary_structure = self._salary_structure_doc.name self.hour_rate = self._salary_structure_doc.hour_rate self.base_hour_rate = flt(self.hour_rate) * flt(self.exchange_rate) self.total_working_hours = sum([d.working_hours or 0.0 for d in self.timesheets]) or 0.0 wages_amount = self.hour_rate * self.total_working_hours self.add_earning_for_hourly_wages(self, self._salary_structure_doc.salary_component, wages_amount) make_salary_slip(self._salary_structure_doc.name, self) def get_working_days_details(self, lwp=None, for_preview=0): payroll_settings = frappe.get_cached_value( "Payroll Settings", None, ( "payroll_based_on", "include_holidays_in_total_working_days", "consider_marked_attendance_on_holidays", "daily_wages_fraction_for_half_day", "consider_unmarked_attendance_as", ), as_dict=1, ) consider_marked_attendance_on_holidays = ( payroll_settings.include_holidays_in_total_working_days and payroll_settings.consider_marked_attendance_on_holidays ) daily_wages_fraction_for_half_day = flt(payroll_settings.daily_wages_fraction_for_half_day) or 0.5 working_days = date_diff(self.end_date, self.start_date) + 1 if for_preview: self.total_working_days = working_days self.payment_days = working_days return holidays = self.get_holidays_for_employee(self.start_date, self.end_date) working_days_list = [add_days(getdate(self.start_date), days=day) for day in range(0, working_days)] if not cint(payroll_settings.include_holidays_in_total_working_days): working_days_list = [i for i in working_days_list if i not in holidays] working_days -= len(holidays) if working_days < 0: frappe.throw(_("There are more holidays than working days this month.")) if not payroll_settings.payroll_based_on: frappe.throw(_("Please set Payroll based on in Payroll settings")) if payroll_settings.payroll_based_on == "Attendance": actual_lwp, absent = self.calculate_lwp_ppl_and_absent_days_based_on_attendance( holidays, daily_wages_fraction_for_half_day, consider_marked_attendance_on_holidays ) self.absent_days = absent else: actual_lwp = self.calculate_lwp_or_ppl_based_on_leave_application( holidays, working_days_list, daily_wages_fraction_for_half_day ) if not lwp: lwp = actual_lwp elif lwp != actual_lwp: frappe.msgprint( _("Leave Without Pay does not match with approved {} records").format( payroll_settings.payroll_based_on ) ) self.leave_without_pay = lwp self.total_working_days = working_days payment_days = self.get_payment_days(payroll_settings.include_holidays_in_total_working_days) if flt(payment_days) > flt(lwp): self.payment_days = flt(payment_days) - flt(lwp) if payroll_settings.payroll_based_on == "Attendance": self.payment_days -= flt(absent) consider_unmarked_attendance_as = payroll_settings.consider_unmarked_attendance_as or "Present" if ( payroll_settings.payroll_based_on == "Attendance" and consider_unmarked_attendance_as == "Absent" ): unmarked_days = self.get_unmarked_days( payroll_settings.include_holidays_in_total_working_days, holidays ) self.absent_days += unmarked_days # will be treated as absent self.payment_days -= unmarked_days else: self.payment_days = 0 def get_unmarked_days( self, include_holidays_in_total_working_days: bool, holidays: list | None = None ) -> float: """Calculates the number of unmarked days for an employee within a date range""" unmarked_days = ( self.total_working_days - self._get_days_outside_period(include_holidays_in_total_working_days, holidays) - self._get_marked_attendance_days(holidays) ) if include_holidays_in_total_working_days and holidays: unmarked_days -= self._get_number_of_holidays(holidays) return unmarked_days def _get_days_outside_period( self, include_holidays_in_total_working_days: bool, holidays: list | None = None ): """Returns days before DOJ or after relieving date""" def _get_days(start_date, end_date): no_of_days = date_diff(end_date, start_date) + 1 if include_holidays_in_total_working_days: return no_of_days else: days = 0 end_date = getdate(end_date) for day in range(no_of_days): date = add_days(end_date, -day) if date not in holidays: days += 1 return days days = 0 if self.actual_start_date != self.start_date: days += _get_days(self.start_date, add_days(self.joining_date, -1)) if self.actual_end_date != self.end_date: days += _get_days(add_days(self.relieving_date, 1), self.end_date) return days def _get_number_of_holidays(self, holidays: list | None = None) -> float: no_of_holidays = 0 actual_end_date = getdate(self.actual_end_date) for days in range(date_diff(self.actual_end_date, self.actual_start_date) + 1): date = add_days(actual_end_date, -days) if date in holidays: no_of_holidays += 1 return no_of_holidays def _get_marked_attendance_days(self, holidays: list | None = None) -> float: Attendance = frappe.qb.DocType("Attendance") query = ( frappe.qb.from_(Attendance) .select(Count("*")) .where( (Attendance.attendance_date.between(self.actual_start_date, self.actual_end_date)) & (Attendance.employee == self.employee) & (Attendance.docstatus == 1) ) ) if holidays: query = query.where(Attendance.attendance_date.notin(holidays)) return query.run()[0][0] def get_payment_days(self, include_holidays_in_total_working_days): if self.joining_date and self.joining_date > getdate(self.end_date): # employee joined after payroll date return 0 if self.relieving_date: employee_status = frappe.db.get_value("Employee", self.employee, "status") if self.relieving_date < getdate(self.start_date) and employee_status != "Left": frappe.throw( _("Employee {0} relieved on {1} must be set as 'Left'").format( get_link_to_form("Employee", self.employee), formatdate(self.relieving_date) ) ) payment_days = date_diff(self.actual_end_date, self.actual_start_date) + 1 if not cint(include_holidays_in_total_working_days): holidays = self.get_holidays_for_employee(self.actual_start_date, self.actual_end_date) payment_days -= len(holidays) return payment_days def get_holidays_for_employee(self, start_date, end_date): holiday_list = get_holiday_list_for_employee(self.employee) key = f"{holiday_list}:{start_date}:{end_date}" holiday_dates = frappe.cache().hget(HOLIDAYS_BETWEEN_DATES, key) if not holiday_dates: holiday_dates = get_holiday_dates_between(holiday_list, start_date, end_date) frappe.cache().hset(HOLIDAYS_BETWEEN_DATES, key, holiday_dates) return holiday_dates def calculate_lwp_or_ppl_based_on_leave_application( self, holidays, working_days_list, daily_wages_fraction_for_half_day ): lwp = 0 leaves = get_lwp_or_ppl_for_date_range( self.employee, self.start_date, self.end_date, ) for d in working_days_list: if self.relieving_date and d > self.relieving_date: continue leave = leaves.get(d) if not leave: continue if not leave.include_holiday and getdate(d) in holidays: continue equivalent_lwp_count = 0 fraction_of_daily_salary_per_leave = flt(leave.fraction_of_daily_salary_per_leave) is_half_day_leave = False if cint(leave.half_day) and (leave.half_day_date == d or leave.from_date == leave.to_date): is_half_day_leave = True equivalent_lwp_count = (1 - daily_wages_fraction_for_half_day) if is_half_day_leave else 1 if cint(leave.is_ppl): equivalent_lwp_count *= ( fraction_of_daily_salary_per_leave if fraction_of_daily_salary_per_leave else 1 ) lwp += equivalent_lwp_count return lwp def get_leave_type_map(self) -> dict: """Returns (partially paid leaves/leave without pay) leave types by name""" def _get_leave_type_map(): leave_types = frappe.get_all( "Leave Type", or_filters={"is_ppl": 1, "is_lwp": 1}, fields=["name", "is_lwp", "is_ppl", "fraction_of_daily_salary_per_leave", "include_holiday"], ) return {leave_type.name: leave_type for leave_type in leave_types} return frappe.cache().get_value(LEAVE_TYPE_MAP, _get_leave_type_map) def get_employee_attendance(self, start_date, end_date): attendance = frappe.qb.DocType("Attendance") attendance_details = ( frappe.qb.from_(attendance) .select(attendance.attendance_date, attendance.status, attendance.leave_type) .where( (attendance.status.isin(["Absent", "Half Day", "On Leave"])) & (attendance.employee == self.employee) & (attendance.docstatus == 1) & (attendance.attendance_date.between(start_date, end_date)) ) ).run(as_dict=1) return attendance_details def calculate_lwp_ppl_and_absent_days_based_on_attendance( self, holidays, daily_wages_fraction_for_half_day, consider_marked_attendance_on_holidays ): lwp = 0 absent = 0 leave_type_map = self.get_leave_type_map() attendance_details = self.get_employee_attendance( start_date=self.start_date, end_date=self.actual_end_date ) for d in attendance_details: if ( d.status in ("Half Day", "On Leave") and d.leave_type and d.leave_type not in leave_type_map.keys() ): continue # skip counting absent on holidays if not consider_marked_attendance_on_holidays and getdate(d.attendance_date) in holidays: if d.status in ["Absent", "Half Day"] or ( d.leave_type and d.leave_type in leave_type_map.keys() and not leave_type_map[d.leave_type]["include_holiday"] ): continue if d.leave_type: fraction_of_daily_salary_per_leave = leave_type_map[d.leave_type][ "fraction_of_daily_salary_per_leave" ] if d.status == "Half Day": equivalent_lwp = 1 - daily_wages_fraction_for_half_day if d.leave_type in leave_type_map.keys() and leave_type_map[d.leave_type]["is_ppl"]: equivalent_lwp *= ( fraction_of_daily_salary_per_leave if fraction_of_daily_salary_per_leave else 1 ) lwp += equivalent_lwp elif d.status == "On Leave" and d.leave_type and d.leave_type in leave_type_map.keys(): equivalent_lwp = 1 if leave_type_map[d.leave_type]["is_ppl"]: equivalent_lwp *= ( fraction_of_daily_salary_per_leave if fraction_of_daily_salary_per_leave else 1 ) lwp += equivalent_lwp elif d.status == "Absent": absent += 1 return lwp, absent def add_earning_for_hourly_wages(self, doc, salary_component, amount): row_exists = False for row in doc.earnings: if row.salary_component == salary_component: row.amount = amount row_exists = True break if not row_exists: wages_row = { "salary_component": salary_component, "abbr": frappe.db.get_value( "Salary Component", salary_component, "salary_component_abbr", cache=True ), "amount": self.hour_rate * self.total_working_hours, "default_amount": 0.0, "additional_amount": 0.0, } doc.append("earnings", wages_row) def set_salary_structure_assignment(self): self._salary_structure_assignment = frappe.db.get_value( "Salary Structure Assignment", { "employee": self.employee, "salary_structure": self.salary_structure, "from_date": ("<=", self.actual_start_date), "docstatus": 1, }, "*", order_by="from_date desc", as_dict=True, ) if not self._salary_structure_assignment: frappe.throw( _( "Please assign a Salary Structure for Employee {0} applicable from or before {1} first" ).format( frappe.bold(self.employee_name), frappe.bold(formatdate(self.actual_start_date)), ) ) def calculate_net_pay(self): def set_gross_pay_and_base_gross_pay(): self.gross_pay = self.get_component_totals("earnings", depends_on_payment_days=1) self.base_gross_pay = flt( flt(self.gross_pay) * flt(self.exchange_rate), self.precision("base_gross_pay") ) if self.salary_structure: self.calculate_component_amounts("earnings") # get remaining numbers of sub-period (period for which one salary is processed) if self.payroll_period: self.remaining_sub_periods = get_period_factor( self.employee, self.start_date, self.end_date, self.payroll_frequency, self.payroll_period, joining_date=self.joining_date, relieving_date=self.relieving_date, )[1] set_gross_pay_and_base_gross_pay() if self.salary_structure: self.calculate_component_amounts("deductions") set_loan_repayment(self) self.set_precision_for_component_amounts() self.set_net_pay() self.compute_income_tax_breakup() def set_net_pay(self): self.total_deduction = self.get_component_totals("deductions") self.base_total_deduction = flt( flt(self.total_deduction) * flt(self.exchange_rate), self.precision("base_total_deduction") ) self.net_pay = flt(self.gross_pay) - ( flt(self.total_deduction) + flt(self.get("total_loan_repayment")) ) self.rounded_total = rounded(self.net_pay) self.base_net_pay = flt(flt(self.net_pay) * flt(self.exchange_rate), self.precision("base_net_pay")) self.base_rounded_total = flt(rounded(self.base_net_pay), self.precision("base_net_pay")) if self.hour_rate: self.base_hour_rate = flt( flt(self.hour_rate) * flt(self.exchange_rate), self.precision("base_hour_rate") ) self.set_net_total_in_words() def compute_taxable_earnings_for_year(self): # get taxable_earnings, opening_taxable_earning, paid_taxes for previous period self.previous_taxable_earnings, exempted_amount = self.get_taxable_earnings_for_prev_period( self.payroll_period.start_date, self.start_date, self.tax_slab.allow_tax_exemption ) self.previous_taxable_earnings_before_exemption = self.previous_taxable_earnings + exempted_amount self.compute_current_and_future_taxable_earnings() # Deduct taxes forcefully for unsubmitted tax exemption proof and unclaimed benefits in the last period if self.payroll_period.end_date <= getdate(self.end_date): self.deduct_tax_for_unsubmitted_tax_exemption_proof = 1 self.deduct_tax_for_unclaimed_employee_benefits = 1 # Get taxable unclaimed benefits self.unclaimed_taxable_benefits = 0 if self.deduct_tax_for_unclaimed_employee_benefits: self.unclaimed_taxable_benefits = self.calculate_unclaimed_taxable_benefits() # Total exemption amount based on tax exemption declaration self.total_exemption_amount = self.get_total_exemption_amount() # Employee Other Incomes self.other_incomes = self.get_income_form_other_sources() or 0.0 # Total taxable earnings including additional and other incomes self.total_taxable_earnings = ( self.previous_taxable_earnings + self.current_structured_taxable_earnings + self.future_structured_taxable_earnings + self.current_additional_earnings + self.other_incomes + self.unclaimed_taxable_benefits - self.total_exemption_amount ) # Total taxable earnings without additional earnings with full tax self.total_taxable_earnings_without_full_tax_addl_components = ( self.total_taxable_earnings - self.current_additional_earnings_with_full_tax ) def compute_current_and_future_taxable_earnings(self): # get taxable_earnings for current period (all days) self.current_taxable_earnings = self.get_taxable_earnings(self.tax_slab.allow_tax_exemption) self.future_structured_taxable_earnings = self.current_taxable_earnings.taxable_earnings * ( ceil(self.remaining_sub_periods) - 1 ) current_taxable_earnings_before_exemption = ( self.current_taxable_earnings.taxable_earnings + self.current_taxable_earnings.amount_exempted_from_income_tax ) self.future_structured_taxable_earnings_before_exemption = ( current_taxable_earnings_before_exemption * (ceil(self.remaining_sub_periods) - 1) ) # get taxable_earnings, addition_earnings for current actual payment days self.current_taxable_earnings_for_payment_days = self.get_taxable_earnings( self.tax_slab.allow_tax_exemption, based_on_payment_days=1 ) self.current_structured_taxable_earnings = ( self.current_taxable_earnings_for_payment_days.taxable_earnings ) self.current_structured_taxable_earnings_before_exemption = ( self.current_structured_taxable_earnings + self.current_taxable_earnings_for_payment_days.amount_exempted_from_income_tax ) self.current_additional_earnings = self.current_taxable_earnings_for_payment_days.additional_income self.current_additional_earnings_with_full_tax = ( self.current_taxable_earnings_for_payment_days.additional_income_with_full_tax ) def compute_income_tax_breakup(self): if not self.payroll_period: return self.standard_tax_exemption_amount = 0 self.tax_exemption_declaration = 0 self.deductions_before_tax_calculation = 0 self.non_taxable_earnings = self.compute_non_taxable_earnings() self.ctc = self.compute_ctc() self.income_from_other_sources = self.get_income_form_other_sources() self.total_earnings = self.ctc + self.income_from_other_sources if hasattr(self, "tax_slab"): if self.tax_slab.allow_tax_exemption: self.standard_tax_exemption_amount = self.tax_slab.standard_tax_exemption_amount self.deductions_before_tax_calculation = ( self.compute_annual_deductions_before_tax_calculation() ) self.tax_exemption_declaration = ( self.get_total_exemption_amount() - self.standard_tax_exemption_amount ) self.annual_taxable_amount = self.total_earnings - ( self.non_taxable_earnings + self.deductions_before_tax_calculation + self.tax_exemption_declaration + self.standard_tax_exemption_amount ) self.income_tax_deducted_till_date = self.get_income_tax_deducted_till_date() if hasattr(self, "total_structured_tax_amount") and hasattr(self, "current_structured_tax_amount"): self.future_income_tax_deductions = ( self.total_structured_tax_amount - self.income_tax_deducted_till_date ) self.current_month_income_tax = self.current_structured_tax_amount # non included current_month_income_tax separately as its already considered # while calculating income_tax_deducted_till_date self.total_income_tax = self.income_tax_deducted_till_date + self.future_income_tax_deductions def compute_ctc(self): if hasattr(self, "previous_taxable_earnings"): return ( self.previous_taxable_earnings_before_exemption + self.current_structured_taxable_earnings_before_exemption + self.future_structured_taxable_earnings_before_exemption + self.current_additional_earnings + self.other_incomes + self.unclaimed_taxable_benefits + self.non_taxable_earnings ) return 0.0 def compute_non_taxable_earnings(self): # Previous period non taxable earnings prev_period_non_taxable_earnings = self.get_salary_slip_details( self.payroll_period.start_date, self.start_date, parentfield="earnings", is_tax_applicable=0 ) ( current_period_non_taxable_earnings, non_taxable_additional_salary, ) = self.get_non_taxable_earnings_for_current_period() # Future period non taxable earnings future_period_non_taxable_earnings = current_period_non_taxable_earnings * ( ceil(self.remaining_sub_periods) - 1 ) non_taxable_earnings = ( prev_period_non_taxable_earnings + current_period_non_taxable_earnings + future_period_non_taxable_earnings + non_taxable_additional_salary ) return non_taxable_earnings def get_non_taxable_earnings_for_current_period(self): current_period_non_taxable_earnings = 0.0 non_taxable_additional_salary = self.get_salary_slip_details( self.payroll_period.start_date, self.start_date, parentfield="earnings", is_tax_applicable=0, field_to_select="additional_amount", ) # Current period non taxable earnings for earning in self.earnings: if earning.is_tax_applicable: continue if earning.additional_amount: non_taxable_additional_salary += earning.additional_amount # Future recurring additional salary if earning.additional_salary and earning.is_recurring_additional_salary: non_taxable_additional_salary += self.get_future_recurring_additional_amount( earning.additional_salary, earning.additional_amount ) else: current_period_non_taxable_earnings += earning.amount return current_period_non_taxable_earnings, non_taxable_additional_salary def compute_annual_deductions_before_tax_calculation(self): prev_period_exempted_amount = 0 current_period_exempted_amount = 0 future_period_exempted_amount = 0 # Previous period exempted amount prev_period_exempted_amount = self.get_salary_slip_details( self.payroll_period.start_date, self.start_date, parentfield="deductions", exempted_from_income_tax=1, ) # Current period exempted amount for d in self.get("deductions"): if d.exempted_from_income_tax: current_period_exempted_amount += d.amount # Future period exempted amount for deduction in self._salary_structure_doc.get("deductions"): if deduction.exempted_from_income_tax: if deduction.amount_based_on_formula: for sub_period in range(1, ceil(self.remaining_sub_periods)): future_period_exempted_amount += self.get_amount_from_formula(deduction, sub_period) else: future_period_exempted_amount += deduction.amount * (ceil(self.remaining_sub_periods) - 1) return ( prev_period_exempted_amount + current_period_exempted_amount + future_period_exempted_amount ) or 0 def get_amount_from_formula(self, struct_row, sub_period=1): if self.payroll_frequency == "Monthly": start_date = frappe.utils.add_months(self.start_date, sub_period) end_date = frappe.utils.add_months(self.end_date, sub_period) posting_date = frappe.utils.add_months(self.posting_date, sub_period) else: days_to_add = 0 if self.payroll_frequency == "Weekly": days_to_add = sub_period * 6 if self.payroll_frequency == "Fortnightly": days_to_add = sub_period * 13 if self.payroll_frequency == "Daily": days_to_add = start_date start_date = frappe.utils.add_days(self.start_date, days_to_add) end_date = frappe.utils.add_days(self.end_date, days_to_add) posting_date = start_date local_data = self.data.copy() local_data.update({"start_date": start_date, "end_date": end_date, "posting_date": posting_date}) return flt(self.eval_condition_and_formula(struct_row, local_data)) def get_income_tax_deducted_till_date(self): tax_deducted = 0.0 for tax_component in self.get("_component_based_variable_tax") or {}: tax_deducted += ( self._component_based_variable_tax[tax_component]["previous_total_paid_taxes"] + self._component_based_variable_tax[tax_component]["current_tax_amount"] ) return tax_deducted def calculate_component_amounts(self, component_type): if not getattr(self, "_salary_structure_doc", None): self.set_salary_structure_doc() self.add_structure_components(component_type) self.add_additional_salary_components(component_type) if component_type == "earnings": self.add_employee_benefits() else: self.add_tax_components() def set_salary_structure_doc(self) -> None: self._salary_structure_doc = frappe.get_cached_doc("Salary Structure", self.salary_structure) # sanitize condition and formula fields for table in ("earnings", "deductions"): for row in self._salary_structure_doc.get(table): row.condition = sanitize_expression(row.condition) row.formula = sanitize_expression(row.formula) def add_structure_components(self, component_type): self.data, self.default_data = self.get_data_for_eval() for struct_row in self._salary_structure_doc.get(component_type): self.add_structure_component(struct_row, component_type) def add_structure_component(self, struct_row, component_type): if ( self.salary_slip_based_on_timesheet and struct_row.salary_component == self._salary_structure_doc.salary_component ): return amount = self.eval_condition_and_formula(struct_row, self.data) if struct_row.statistical_component: # update statitical component amount in reference data based on payment days # since row for statistical component is not added to salary slip self.default_data[struct_row.abbr] = flt(amount) if struct_row.depends_on_payment_days: payment_days_amount = ( flt(amount) * flt(self.payment_days) / cint(self.total_working_days) if self.total_working_days else 0 ) self.data[struct_row.abbr] = flt(payment_days_amount, struct_row.precision("amount")) else: # default behavior, the system does not add if component amount is zero # if remove_if_zero_valued is unchecked, then ask system to add component row remove_if_zero_valued = frappe.get_cached_value( "Salary Component", struct_row.salary_component, "remove_if_zero_valued" ) default_amount = 0 if ( amount or (struct_row.amount_based_on_formula and amount is not None) or (not remove_if_zero_valued and amount is not None and not self.data[struct_row.abbr]) ): default_amount = self.eval_condition_and_formula(struct_row, self.default_data) self.update_component_row( struct_row, amount, component_type, data=self.data, default_amount=default_amount, remove_if_zero_valued=remove_if_zero_valued, ) def get_data_for_eval(self): """Returns data for evaluating formula""" data = frappe._dict() employee = frappe.get_cached_doc("Employee", self.employee).as_dict() if not hasattr(self, "_salary_structure_assignment"): self.set_salary_structure_assignment() data.update(self._salary_structure_assignment) data.update(self.as_dict()) data.update(employee) data.update(self.get_component_abbr_map()) # shallow copy of data to store default amounts (without payment days) for tax calculation default_data = data.copy() for key in ("earnings", "deductions"): for d in self.get(key): default_data[d.abbr] = d.default_amount or 0 data[d.abbr] = d.amount or 0 return data, default_data def get_component_abbr_map(self): def _fetch_component_values(): return { component_abbr: 0 for component_abbr in frappe.get_all("Salary Component", pluck="salary_component_abbr") } return frappe.cache().get_value(SALARY_COMPONENT_VALUES, generator=_fetch_component_values) def eval_condition_and_formula(self, struct_row, data): try: condition, formula, amount = struct_row.condition, struct_row.formula, struct_row.amount if condition and not _safe_eval(condition, self.whitelisted_globals, data): return None if struct_row.amount_based_on_formula and formula: amount = flt( _safe_eval(formula, self.whitelisted_globals, data), struct_row.precision("amount") ) if amount: data[struct_row.abbr] = amount return amount except NameError as ne: throw_error_message( struct_row, ne, title=_("Name error"), description=_("This error can be due to missing or deleted field."), ) except SyntaxError as se: throw_error_message( struct_row, se, title=_("Syntax error"), description=_("This error can be due to invalid syntax."), ) except Exception as exc: throw_error_message( struct_row, exc, title=_("Error in formula or condition"), description=_("This error can be due to invalid formula or condition."), ) raise def add_employee_benefits(self): for struct_row in self._salary_structure_doc.get("earnings"): if struct_row.is_flexible_benefit == 1: if ( frappe.db.get_value( "Salary Component", struct_row.salary_component, "pay_against_benefit_claim", cache=True, ) != 1 ): benefit_component_amount = get_benefit_component_amount( self.employee, self.start_date, self.end_date, struct_row.salary_component, self._salary_structure_doc, self.payroll_frequency, self.payroll_period, ) if benefit_component_amount: self.update_component_row(struct_row, benefit_component_amount, "earnings") else: benefit_claim_amount = get_benefit_claim_amount( self.employee, self.start_date, self.end_date, struct_row.salary_component ) if benefit_claim_amount: self.update_component_row(struct_row, benefit_claim_amount, "earnings") self.adjust_benefits_in_last_payroll_period(self.payroll_period) def adjust_benefits_in_last_payroll_period(self, payroll_period): if payroll_period: if getdate(payroll_period.end_date) <= getdate(self.end_date): last_benefits = get_last_payroll_period_benefits( self.employee, self.start_date, self.end_date, payroll_period, self._salary_structure_doc ) if last_benefits: for last_benefit in last_benefits: last_benefit = frappe._dict(last_benefit) amount = last_benefit.amount self.update_component_row(frappe._dict(last_benefit.struct_row), amount, "earnings") def add_additional_salary_components(self, component_type): additional_salaries = get_additional_salaries( self.employee, self.start_date, self.end_date, component_type ) for additional_salary in additional_salaries: self.update_component_row( get_salary_component_data(additional_salary.component), additional_salary.amount, component_type, additional_salary, is_recurring=additional_salary.is_recurring, ) def add_tax_components(self): # Calculate variable_based_on_taxable_salary after all components updated in salary slip tax_components, self.other_deduction_components = [], [] for d in self._salary_structure_doc.get("deductions"): if d.variable_based_on_taxable_salary == 1 and not d.formula and not flt(d.amount): tax_components.append(d.salary_component) else: self.other_deduction_components.append(d.salary_component) if self.handle_additional_salary_tax_component(): return # consider manually added tax component if not tax_components: tax_components = [ d.salary_component for d in self.get("deductions") if d.variable_based_on_taxable_salary ] if self.is_new() and not tax_components: tax_components = self.get_tax_components() frappe.msgprint( _( "Added tax components from the Salary Component master as the salary structure didn't have any tax component." ), indicator="blue", alert=True, ) if tax_components and self.payroll_period and self.salary_structure: self.tax_slab = self.get_income_tax_slabs() self.compute_taxable_earnings_for_year() self._component_based_variable_tax = {} for d in tax_components: self._component_based_variable_tax.setdefault(d, {}) tax_amount = self.calculate_variable_based_on_taxable_salary(d) tax_row = get_salary_component_data(d) self.update_component_row(tax_row, tax_amount, "deductions") def get_tax_components(self) -> list: """ Returns: list: A list of tax components specific to the company. If no tax components are defined for the company, it returns the default tax components. """ tax_components = frappe.cache().get_value( TAX_COMPONENTS_BY_COMPANY, self._fetch_tax_components_by_company ) default_tax_components = tax_components.get("default", []) return tax_components.get(self.company, default_tax_components) def _fetch_tax_components_by_company(self) -> dict: """ Returns: dict: A dictionary containing tax components grouped by company. Raises: None """ tax_components = {} sc = frappe.qb.DocType("Salary Component") sca = frappe.qb.DocType("Salary Component Account") components = ( frappe.qb.from_(sc) .left_join(sca) .on(sca.parent == sc.name) .select( sc.name, sca.company, ) .where(sc.variable_based_on_taxable_salary == 1) ).run(as_dict=True) for component in components: key = component.company or "default" tax_components.setdefault(key, []) tax_components[key].append(component.name) return tax_components def handle_additional_salary_tax_component(self) -> bool: component = next( (d for d in self.get("deductions") if d.variable_based_on_taxable_salary and d.additional_salary), None, ) if not component: return False if frappe.db.get_value( "Additional Salary", component.additional_salary, "overwrite_salary_structure_amount" ): return True else: # overwriting disabled, remove addtional salary tax component self.get("deductions", []).remove(component) return False def update_component_row( self, component_data, amount, component_type, additional_salary=None, is_recurring=0, data=None, default_amount=None, remove_if_zero_valued=None, ): component_row = None for d in self.get(component_type): if d.salary_component != component_data.salary_component: continue if (not d.additional_salary and (not additional_salary or additional_salary.overwrite)) or ( additional_salary and additional_salary.name == d.additional_salary ): component_row = d break if additional_salary and additional_salary.overwrite: # Additional Salary with overwrite checked, remove default rows of same component self.set( component_type, [ d for d in self.get(component_type) if d.salary_component != component_data.salary_component or (d.additional_salary and additional_salary.name != d.additional_salary) or d == component_row ], ) if not component_row: if not (amount or default_amount) and remove_if_zero_valued: return component_row = self.append(component_type) for attr in ( "depends_on_payment_days", "salary_component", "abbr", "do_not_include_in_total", "is_tax_applicable", "is_flexible_benefit", "variable_based_on_taxable_salary", "exempted_from_income_tax", ): component_row.set(attr, component_data.get(attr)) if additional_salary: if additional_salary.overwrite: component_row.additional_amount = flt( flt(amount) - flt(component_row.get("default_amount", 0)), component_row.precision("additional_amount"), ) else: component_row.default_amount = 0 component_row.additional_amount = amount component_row.is_recurring_additional_salary = is_recurring component_row.additional_salary = additional_salary.name component_row.deduct_full_tax_on_selected_payroll_date = ( additional_salary.deduct_full_tax_on_selected_payroll_date ) else: component_row.default_amount = default_amount or amount component_row.additional_amount = 0 component_row.deduct_full_tax_on_selected_payroll_date = ( component_data.deduct_full_tax_on_selected_payroll_date ) component_row.amount = amount self.update_component_amount_based_on_payment_days(component_row, remove_if_zero_valued) if data: data[component_row.abbr] = component_row.amount def update_component_amount_based_on_payment_days(self, component_row, remove_if_zero_valued=None): component_row.amount = self.get_amount_based_on_payment_days(component_row)[0] # remove 0 valued components that have been updated later if component_row.amount == 0 and remove_if_zero_valued: self.remove(component_row) def set_precision_for_component_amounts(self): for component_type in ("earnings", "deductions"): for component_row in self.get(component_type): component_row.amount = flt(component_row.amount, component_row.precision("amount")) def calculate_variable_based_on_taxable_salary(self, tax_component): if not self.payroll_period: frappe.msgprint( _("Start and end dates not in a valid Payroll Period, cannot calculate {0}.").format( tax_component ) ) return return self.calculate_variable_tax(tax_component) def calculate_variable_tax(self, tax_component): self.previous_total_paid_taxes = self.get_tax_paid_in_period( self.payroll_period.start_date, self.start_date, tax_component ) # Structured tax amount eval_locals, default_data = self.get_data_for_eval() self.total_structured_tax_amount = calculate_tax_by_tax_slab( self.total_taxable_earnings_without_full_tax_addl_components, self.tax_slab, self.whitelisted_globals, eval_locals, ) self.current_structured_tax_amount = ( self.total_structured_tax_amount - self.previous_total_paid_taxes ) / self.remaining_sub_periods # Total taxable earnings with additional earnings with full tax self.full_tax_on_additional_earnings = 0.0 if self.current_additional_earnings_with_full_tax: self.total_tax_amount = calculate_tax_by_tax_slab( self.total_taxable_earnings, self.tax_slab, self.whitelisted_globals, eval_locals ) self.full_tax_on_additional_earnings = self.total_tax_amount - self.total_structured_tax_amount current_tax_amount = self.current_structured_tax_amount + self.full_tax_on_additional_earnings if flt(current_tax_amount) < 0: current_tax_amount = 0 self._component_based_variable_tax[tax_component].update( { "previous_total_paid_taxes": self.previous_total_paid_taxes, "total_structured_tax_amount": self.total_structured_tax_amount, "current_structured_tax_amount": self.current_structured_tax_amount, "full_tax_on_additional_earnings": self.full_tax_on_additional_earnings, "current_tax_amount": current_tax_amount, } ) return current_tax_amount def get_income_tax_slabs(self): income_tax_slab = self._salary_structure_assignment.income_tax_slab if not income_tax_slab: frappe.throw( _("Income Tax Slab not set in Salary Structure Assignment: {0}").format( get_link_to_form("Salary Structure Assignment", self._salary_structure_assignment.name) ), title=_("Missing Tax Slab"), ) income_tax_slab_doc = frappe.get_cached_doc("Income Tax Slab", income_tax_slab) if income_tax_slab_doc.disabled: frappe.throw(_("Income Tax Slab: {0} is disabled").format(income_tax_slab)) if getdate(income_tax_slab_doc.effective_from) > getdate(self.payroll_period.start_date): frappe.throw( _("Income Tax Slab must be effective on or before Payroll Period Start Date: {0}").format( self.payroll_period.start_date ) ) return income_tax_slab_doc def get_taxable_earnings_for_prev_period(self, start_date, end_date, allow_tax_exemption=False): exempted_amount = 0 taxable_earnings = self.get_salary_slip_details( start_date, end_date, parentfield="earnings", is_tax_applicable=1 ) if allow_tax_exemption: exempted_amount = self.get_salary_slip_details( start_date, end_date, parentfield="deductions", exempted_from_income_tax=1 ) opening_taxable_earning = self.get_opening_for("taxable_earnings_till_date", start_date, end_date) return (taxable_earnings + opening_taxable_earning) - exempted_amount, exempted_amount def get_opening_for(self, field_to_select, start_date, end_date): return self._salary_structure_assignment.get(field_to_select) or 0 def get_salary_slip_details( self, start_date, end_date, parentfield, salary_component=None, is_tax_applicable=None, is_flexible_benefit=0, exempted_from_income_tax=0, variable_based_on_taxable_salary=0, field_to_select="amount", ): ss = frappe.qb.DocType("Salary Slip") sd = frappe.qb.DocType("Salary Detail") if field_to_select == "amount": field = sd.amount else: field = sd.additional_amount query = ( frappe.qb.from_(ss) .join(sd) .on(sd.parent == ss.name) .select(Sum(field)) .where(sd.parentfield == parentfield) .where(sd.is_flexible_benefit == is_flexible_benefit) .where(ss.docstatus == 1) .where(ss.employee == self.employee) .where(ss.start_date.between(start_date, end_date)) .where(ss.end_date.between(start_date, end_date)) ) if is_tax_applicable is not None: query = query.where(sd.is_tax_applicable == is_tax_applicable) if exempted_from_income_tax: query = query.where(sd.exempted_from_income_tax == exempted_from_income_tax) if variable_based_on_taxable_salary: query = query.where(sd.variable_based_on_taxable_salary == variable_based_on_taxable_salary) if salary_component: query = query.where(sd.salary_component == salary_component) result = query.run() return flt(result[0][0]) if result else 0.0 def get_tax_paid_in_period(self, start_date, end_date, tax_component): # find total_tax_paid, tax paid for benefit, additional_salary total_tax_paid = self.get_salary_slip_details( start_date, end_date, parentfield="deductions", salary_component=tax_component, variable_based_on_taxable_salary=1, ) tax_deducted_till_date = self.get_opening_for("tax_deducted_till_date", start_date, end_date) return total_tax_paid + tax_deducted_till_date def get_taxable_earnings(self, allow_tax_exemption=False, based_on_payment_days=0): taxable_earnings = 0 additional_income = 0 additional_income_with_full_tax = 0 flexi_benefits = 0 amount_exempted_from_income_tax = 0 for earning in self.earnings: if based_on_payment_days: amount, additional_amount = self.get_amount_based_on_payment_days(earning) else: if earning.additional_amount: amount, additional_amount = earning.amount, earning.additional_amount else: amount, additional_amount = earning.default_amount, earning.additional_amount if earning.is_tax_applicable: if earning.is_flexible_benefit: flexi_benefits += amount else: taxable_earnings += amount - additional_amount additional_income += additional_amount # Get additional amount based on future recurring additional salary if additional_amount and earning.is_recurring_additional_salary: additional_income += self.get_future_recurring_additional_amount( earning.additional_salary, earning.additional_amount ) # Used earning.additional_amount to consider the amount for the full month if earning.deduct_full_tax_on_selected_payroll_date: additional_income_with_full_tax += additional_amount if allow_tax_exemption: for ded in self.deductions: if ded.exempted_from_income_tax: amount, additional_amount = ded.amount, ded.additional_amount if based_on_payment_days: amount, additional_amount = self.get_amount_based_on_payment_days(ded) taxable_earnings -= flt(amount - additional_amount) additional_income -= additional_amount amount_exempted_from_income_tax = flt(amount - additional_amount) if additional_amount and ded.is_recurring_additional_salary: additional_income -= self.get_future_recurring_additional_amount( ded.additional_salary, ded.additional_amount ) # Used ded.additional_amount to consider the amount for the full month return frappe._dict( { "taxable_earnings": taxable_earnings, "additional_income": additional_income, "amount_exempted_from_income_tax": amount_exempted_from_income_tax, "additional_income_with_full_tax": additional_income_with_full_tax, "flexi_benefits": flexi_benefits, } ) def get_future_recurring_period( self, additional_salary, ): to_date = None if self.relieving_date: to_date = self.relieving_date if not to_date: to_date = frappe.db.get_value("Additional Salary", additional_salary, "to_date", cache=True) # future month count excluding current from_date, to_date = getdate(self.start_date), getdate(to_date) # If recurring period end date is beyond the payroll period, # last day of payroll period should be considered for recurring period calculation if getdate(to_date) > getdate(self.payroll_period.end_date): to_date = getdate(self.payroll_period.end_date) future_recurring_period = ((to_date.year - from_date.year) * 12) + (to_date.month - from_date.month) return future_recurring_period def get_future_recurring_additional_amount(self, additional_salary, monthly_additional_amount): future_recurring_additional_amount = 0 future_recurring_period = self.get_future_recurring_period(additional_salary) if future_recurring_period > 0: future_recurring_additional_amount = ( monthly_additional_amount * future_recurring_period ) # Used earning.additional_amount to consider the amount for the full month return future_recurring_additional_amount def get_amount_based_on_payment_days(self, row): amount, additional_amount = row.amount, row.additional_amount timesheet_component = self._salary_structure_doc.salary_component if ( self.salary_structure and cint(row.depends_on_payment_days) and cint(self.total_working_days) and not ( row.additional_salary and row.default_amount ) # to identify overwritten additional salary and ( row.salary_component != timesheet_component or getdate(self.start_date) < self.joining_date or (self.relieving_date and getdate(self.end_date) > self.relieving_date) ) ): additional_amount = flt( (flt(row.additional_amount) * flt(self.payment_days) / cint(self.total_working_days)), row.precision("additional_amount"), ) amount = ( flt( (flt(row.default_amount) * flt(self.payment_days) / cint(self.total_working_days)), row.precision("amount"), ) + additional_amount ) elif ( not self.payment_days and row.salary_component != timesheet_component and cint(row.depends_on_payment_days) ): amount, additional_amount = 0, 0 elif not row.amount: amount = flt(row.default_amount) + flt(row.additional_amount) # apply rounding if frappe.db.get_value( "Salary Component", row.salary_component, "round_to_the_nearest_integer", cache=True ): amount, additional_amount = rounded(amount or 0), rounded(additional_amount or 0) return amount, additional_amount def calculate_unclaimed_taxable_benefits(self): # get total sum of benefits paid total_benefits_paid = self.get_salary_slip_details( self.payroll_period.start_date, self.start_date, parentfield="earnings", is_tax_applicable=1, is_flexible_benefit=1, ) # get total benefits claimed BenefitClaim = frappe.qb.DocType("Employee Benefit Claim") total_benefits_claimed = ( frappe.qb.from_(BenefitClaim) .select(Sum(BenefitClaim.claimed_amount)) .where( (BenefitClaim.docstatus == 1) & (BenefitClaim.employee == self.employee) & (BenefitClaim.claim_date.between(self.payroll_period.start_date, self.end_date)) ) ).run() total_benefits_claimed = flt(total_benefits_claimed[0][0]) if total_benefits_claimed else 0 unclaimed_taxable_benefits = ( total_benefits_paid - total_benefits_claimed ) + self.current_taxable_earnings_for_payment_days.flexi_benefits return unclaimed_taxable_benefits def get_total_exemption_amount(self): total_exemption_amount = 0 if self.tax_slab.allow_tax_exemption: if self.deduct_tax_for_unsubmitted_tax_exemption_proof: exemption_proof = frappe.db.get_value( "Employee Tax Exemption Proof Submission", {"employee": self.employee, "payroll_period": self.payroll_period.name, "docstatus": 1}, "exemption_amount", cache=True, ) if exemption_proof: total_exemption_amount = exemption_proof else: declaration = frappe.db.get_value( "Employee Tax Exemption Declaration", {"employee": self.employee, "payroll_period": self.payroll_period.name, "docstatus": 1}, "total_exemption_amount", cache=True, ) if declaration: total_exemption_amount = declaration if self.tax_slab.standard_tax_exemption_amount: total_exemption_amount += flt(self.tax_slab.standard_tax_exemption_amount) return total_exemption_amount def get_income_form_other_sources(self): return ( frappe.get_all( "Employee Other Income", filters={ "employee": self.employee, "payroll_period": self.payroll_period.name, "company": self.company, "docstatus": 1, }, fields="SUM(amount) as total_amount", )[0].total_amount or 0.0 ) def get_component_totals(self, component_type, depends_on_payment_days=0): total = 0.0 for d in self.get(component_type): if not d.do_not_include_in_total: if depends_on_payment_days: amount = self.get_amount_based_on_payment_days(d)[0] else: amount = flt(d.amount, d.precision("amount")) total += amount return total def email_salary_slip(self): receiver = frappe.db.get_value("Employee", self.employee, "prefered_email", cache=True) payroll_settings = frappe.get_single("Payroll Settings") subject = f"Salary Slip - from {self.start_date} to {self.end_date}" message = _("Please see attachment") if payroll_settings.email_template: email_template = frappe.get_doc("Email Template", payroll_settings.email_template) context = self.as_dict() subject = frappe.render_template(email_template.subject, context) message = frappe.render_template(email_template.response, context) password = None if payroll_settings.encrypt_salary_slips_in_emails: password = generate_password_for_pdf(payroll_settings.password_policy, self.employee) if not payroll_settings.email_template: message += "<br>" + _( "Note: Your salary slip is password protected, the password to unlock the PDF is of the format {0}." ).format(payroll_settings.password_policy) if receiver: email_args = { "sender": payroll_settings.sender_email, "recipients": [receiver], "message": message, "subject": subject, "attachments": [ frappe.attach_print(self.doctype, self.name, file_name=self.name, password=password) ], "reference_doctype": self.doctype, "reference_name": self.name, } if not frappe.flags.in_test: enqueue(method=frappe.sendmail, queue="short", timeout=300, is_async=True, **email_args) else: frappe.sendmail(**email_args) else: msgprint(_("{0}: Employee email not found, hence email not sent").format(self.employee_name)) def update_status(self, salary_slip=None): for data in self.timesheets: if data.time_sheet: timesheet = frappe.get_doc("Timesheet", data.time_sheet) timesheet.salary_slip = salary_slip timesheet.flags.ignore_validate_update_after_submit = True timesheet.set_status() timesheet.save() def set_status(self, status=None): """Get and update status""" if not status: status = self.get_status() self.db_set("status", status) def process_salary_structure(self, for_preview=0): """Calculate salary after salary structure details have been updated""" if not self.salary_slip_based_on_timesheet: self.get_date_details() self.pull_emp_details() self.get_working_days_details(for_preview=for_preview) self.calculate_net_pay() def pull_emp_details(self): account_details = frappe.get_cached_value( "Employee", self.employee, ["bank_name", "bank_ac_no", "salary_mode"], as_dict=1 ) if account_details: self.mode_of_payment = account_details.salary_mode self.bank_name = account_details.bank_name self.bank_account_no = account_details.bank_ac_no @frappe.whitelist() def process_salary_based_on_working_days(self): self.get_working_days_details(lwp=self.leave_without_pay) self.calculate_net_pay() @frappe.whitelist() def set_totals(self): self.gross_pay = 0.0 if self.salary_slip_based_on_timesheet == 1: self.calculate_total_for_salary_slip_based_on_timesheet() else: self.total_deduction = 0.0 if hasattr(self, "earnings"): for earning in self.earnings: self.gross_pay += flt(earning.amount, earning.precision("amount")) if hasattr(self, "deductions"): for deduction in self.deductions: self.total_deduction += flt(deduction.amount, deduction.precision("amount")) self.net_pay = ( flt(self.gross_pay) - flt(self.total_deduction) - flt(self.get("total_loan_repayment")) ) self.set_base_totals() def set_base_totals(self): self.base_gross_pay = flt(self.gross_pay) * flt(self.exchange_rate) self.base_total_deduction = flt(self.total_deduction) * flt(self.exchange_rate) self.rounded_total = rounded(self.net_pay or 0) self.base_net_pay = flt(self.net_pay) * flt(self.exchange_rate) self.base_rounded_total = rounded(self.base_net_pay or 0) self.set_net_total_in_words() # calculate total working hours, earnings based on hourly wages and totals def calculate_total_for_salary_slip_based_on_timesheet(self): if self.timesheets: self.total_working_hours = 0 for timesheet in self.timesheets: if timesheet.working_hours: self.total_working_hours += timesheet.working_hours wages_amount = self.total_working_hours * self.hour_rate self.base_hour_rate = flt(self.hour_rate) * flt(self.exchange_rate) salary_component = frappe.db.get_value( "Salary Structure", {"name": self.salary_structure}, "salary_component", cache=True ) if self.earnings: for i, earning in enumerate(self.earnings): if earning.salary_component == salary_component: self.earnings[i].amount = wages_amount self.gross_pay += flt(self.earnings[i].amount, earning.precision("amount")) self.net_pay = flt(self.gross_pay) - flt(self.total_deduction) def compute_year_to_date(self): year_to_date = 0 period_start_date, period_end_date = self.get_year_to_date_period() salary_slip_sum = frappe.get_list( "Salary Slip", fields=["sum(net_pay) as net_sum", "sum(gross_pay) as gross_sum"], filters={ "employee": self.employee, "start_date": [">=", period_start_date], "end_date": ["<", period_end_date], "name": ["!=", self.name], "docstatus": 1, }, ) year_to_date = flt(salary_slip_sum[0].net_sum) if salary_slip_sum else 0.0 gross_year_to_date = flt(salary_slip_sum[0].gross_sum) if salary_slip_sum else 0.0 year_to_date += self.net_pay gross_year_to_date += self.gross_pay self.year_to_date = year_to_date self.gross_year_to_date = gross_year_to_date def compute_month_to_date(self): month_to_date = 0 first_day_of_the_month = get_first_day(self.start_date) salary_slip_sum = frappe.get_list( "Salary Slip", fields=["sum(net_pay) as sum"], filters={ "employee": self.employee, "start_date": [">=", first_day_of_the_month], "end_date": ["<", self.start_date], "name": ["!=", self.name], "docstatus": 1, }, ) month_to_date = flt(salary_slip_sum[0].sum) if salary_slip_sum else 0.0 month_to_date += self.net_pay self.month_to_date = month_to_date def compute_component_wise_year_to_date(self): period_start_date, period_end_date = self.get_year_to_date_period() ss = frappe.qb.DocType("Salary Slip") sd = frappe.qb.DocType("Salary Detail") for key in ("earnings", "deductions"): for component in self.get(key): year_to_date = 0 component_sum = ( frappe.qb.from_(sd) .inner_join(ss) .on(sd.parent == ss.name) .select(Sum(sd.amount).as_("sum")) .where( (ss.employee == self.employee) & (sd.salary_component == component.salary_component) & (ss.start_date >= period_start_date) & (ss.end_date < period_end_date) & (ss.name != self.name) & (ss.docstatus == 1) ) ).run() year_to_date = flt(component_sum[0][0]) if component_sum else 0.0 year_to_date += component.amount component.year_to_date = year_to_date def get_year_to_date_period(self): if self.payroll_period: period_start_date = self.payroll_period.start_date period_end_date = self.payroll_period.end_date else: # get dates based on fiscal year if no payroll period exists fiscal_year = get_fiscal_year(date=self.start_date, company=self.company, as_dict=1) period_start_date = fiscal_year.year_start_date period_end_date = fiscal_year.year_end_date return period_start_date, period_end_date def add_leave_balances(self): self.set("leave_details", []) if frappe.db.get_single_value("Payroll Settings", "show_leave_balances_in_salary_slip"): from hrms.hr.doctype.leave_application.leave_application import get_leave_details leave_details = get_leave_details(self.employee, self.end_date) for leave_type, leave_values in leave_details["leave_allocation"].items(): self.append( "leave_details", { "leave_type": leave_type, "total_allocated_leaves": flt(leave_values.get("total_leaves")), "expired_leaves": flt(leave_values.get("expired_leaves")), "used_leaves": flt(leave_values.get("leaves_taken")), "pending_leaves": flt(leave_values.get("leaves_pending_approval")), "available_leaves": flt(leave_values.get("remaining_leaves")), }, ) def unlink_ref_doc_from_salary_slip(doc, method=None): """Unlinks accrual Journal Entry from Salary Slips on cancellation""" linked_ss = frappe.get_all( "Salary Slip", filters={"journal_entry": doc.name, "docstatus": ["<", 2]}, pluck="name" ) if linked_ss: for ss in linked_ss: ss_doc = frappe.get_doc("Salary Slip", ss) frappe.db.set_value("Salary Slip", ss_doc.name, "journal_entry", "") def generate_password_for_pdf(policy_template, employee): employee = frappe.get_cached_doc("Employee", employee) return policy_template.format(**employee.as_dict()) def get_salary_component_data(component): # get_cached_value doesn't work here due to alias "name as salary_component" return frappe.db.get_value( "Salary Component", component, ( "name as salary_component", "depends_on_payment_days", "salary_component_abbr as abbr", "do_not_include_in_total", "is_tax_applicable", "is_flexible_benefit", "variable_based_on_taxable_salary", ), as_dict=1, cache=True, ) def get_payroll_payable_account(company, payroll_entry): if payroll_entry: payroll_payable_account = frappe.db.get_value( "Payroll Entry", payroll_entry, "payroll_payable_account", cache=True ) else: payroll_payable_account = frappe.db.get_value( "Company", company, "default_payroll_payable_account", cache=True ) return payroll_payable_account def calculate_tax_by_tax_slab(annual_taxable_earning, tax_slab, eval_globals=None, eval_locals=None): eval_locals.update({"annual_taxable_earning": annual_taxable_earning}) tax_amount = 0 for slab in tax_slab.slabs: cond = cstr(slab.condition).strip() if cond and not eval_tax_slab_condition(cond, eval_globals, eval_locals): continue if not slab.to_amount and annual_taxable_earning >= slab.from_amount: tax_amount += (annual_taxable_earning - slab.from_amount + 1) * slab.percent_deduction * 0.01 continue if annual_taxable_earning >= slab.from_amount and annual_taxable_earning < slab.to_amount: tax_amount += (annual_taxable_earning - slab.from_amount + 1) * slab.percent_deduction * 0.01 elif annual_taxable_earning >= slab.from_amount and annual_taxable_earning >= slab.to_amount: tax_amount += (slab.to_amount - slab.from_amount + 1) * slab.percent_deduction * 0.01 # other taxes and charges on income tax for d in tax_slab.other_taxes_and_charges: if flt(d.min_taxable_income) and flt(d.min_taxable_income) > annual_taxable_earning: continue if flt(d.max_taxable_income) and flt(d.max_taxable_income) < annual_taxable_earning: continue tax_amount += tax_amount * flt(d.percent) / 100 return tax_amount def eval_tax_slab_condition(condition, eval_globals=None, eval_locals=None): if not eval_globals: eval_globals = { "int": int, "float": float, "long": int, "round": round, "date": date, "getdate": getdate, } try: condition = condition.strip() if condition: return frappe.safe_eval(condition, eval_globals, eval_locals) except NameError as err: frappe.throw( _("{0} <br> This error can be due to missing or deleted field.").format(err), title=_("Name error"), ) except SyntaxError as err: frappe.throw(_("Syntax error in condition: {0} in Income Tax Slab").format(err)) except Exception as e: frappe.throw(_("Error in formula or condition: {0} in Income Tax Slab").format(e)) raise def get_lwp_or_ppl_for_date_range(employee, start_date, end_date): LeaveApplication = frappe.qb.DocType("Leave Application") LeaveType = frappe.qb.DocType("Leave Type") leaves = ( frappe.qb.from_(LeaveApplication) .inner_join(LeaveType) .on(LeaveType.name == LeaveApplication.leave_type) .select( LeaveApplication.name, LeaveType.is_ppl, LeaveType.fraction_of_daily_salary_per_leave, LeaveType.include_holiday, LeaveApplication.from_date, LeaveApplication.to_date, LeaveApplication.half_day, LeaveApplication.half_day_date, ) .where( ((LeaveType.is_lwp == 1) | (LeaveType.is_ppl == 1)) & (LeaveApplication.docstatus == 1) & (LeaveApplication.status == "Approved") & (LeaveApplication.employee == employee) & ((LeaveApplication.salary_slip.isnull()) | (LeaveApplication.salary_slip == "")) & ((LeaveApplication.from_date <= end_date) & (LeaveApplication.to_date >= start_date)) ) ).run(as_dict=True) leave_date_mapper = frappe._dict() for leave in leaves: if leave.from_date == leave.to_date: leave_date_mapper[leave.from_date] = leave else: date_diff = (getdate(leave.to_date) - getdate(leave.from_date)).days for i in range(date_diff + 1): date = add_days(leave.from_date, i) leave_date_mapper[date] = leave return leave_date_mapper @frappe.whitelist() def make_salary_slip_from_timesheet(source_name, target_doc=None): target = frappe.new_doc("Salary Slip") set_missing_values(source_name, target) target.run_method("get_emp_and_working_day_details") return target def set_missing_values(time_sheet, target): doc = frappe.get_doc("Timesheet", time_sheet) target.employee = doc.employee target.employee_name = doc.employee_name target.salary_slip_based_on_timesheet = 1 target.start_date = doc.start_date target.end_date = doc.end_date target.posting_date = doc.modified target.total_working_hours = doc.total_hours target.append("timesheets", {"time_sheet": doc.name, "working_hours": doc.total_hours}) def throw_error_message(row, error, title, description=None): data = frappe._dict( { "doctype": row.parenttype, "name": row.parent, "doclink": get_link_to_form(row.parenttype, row.parent), "row_id": row.idx, "error": error, "title": title, "description": description or "", } ) message = _( "Error while evaluating the {doctype} {doclink} at row {row_id}. <br><br> <b>Error:</b> {error} <br><br> <b>Hint:</b> {description}" ).format(**data) frappe.throw(message, title=title) def on_doctype_update(): frappe.db.add_index("Salary Slip", ["employee", "start_date", "end_date"]) def _safe_eval(code: str, eval_globals: dict | None = None, eval_locals: dict | None = None): """Old version of safe_eval from framework. Note: current frappe.safe_eval transforms code so if you have nested iterations with too much depth then it can hit recursion limit of python. There's no workaround for this and people need large formulas in some countries so this is alternate implementation for that. WARNING: DO NOT use this function anywhere else outside of this file. """ code = unicodedata.normalize("NFKC", code) _check_attributes(code) whitelisted_globals = {"int": int, "float": float, "long": int, "round": round} if not eval_globals: eval_globals = {} eval_globals["__builtins__"] = {} eval_globals.update(whitelisted_globals) return eval(code, eval_globals, eval_locals) # nosemgrep def _check_attributes(code: str) -> None: import ast from frappe.utils.safe_exec import UNSAFE_ATTRIBUTES unsafe_attrs = set(UNSAFE_ATTRIBUTES).union(["__"]) - {"format"} for attribute in unsafe_attrs: if attribute in code: raise SyntaxError(f'Illegal rule {frappe.bold(code)}. Cannot use "{attribute}"') BLOCKED_NODES = (ast.NamedExpr,) tree = ast.parse(code, mode="eval") for node in ast.walk(tree): if isinstance(node, BLOCKED_NODES): raise SyntaxError(f"Operation not allowed: line {node.lineno} column {node.col_offset}") if isinstance(node, ast.Attribute) and isinstance(node.attr, str) and node.attr in UNSAFE_ATTRIBUTES: raise SyntaxError(f'Illegal rule {frappe.bold(code)}. Cannot use "{node.attr}"') @frappe.whitelist() def enqueue_email_salary_slips(names) -> None: """enqueue bulk emailing salary slips""" import json if isinstance(names, str): names = json.loads(names) frappe.enqueue("hrms.payroll.doctype.salary_slip.salary_slip.email_salary_slips", names=names) frappe.msgprint( _("Salary slip emails have been enqueued for sending. Check {0} for status.").format( f"""<a href='{frappe.utils.get_url_to_list("Email Queue")}' target='blank'>Email Queue</a>""" ) ) def email_salary_slips(names) -> None: for name in names: salary_slip = frappe.get_doc("Salary Slip", name) salary_slip.email_salary_slip()
2302_79757062/hrms
hrms/payroll/doctype/salary_slip/salary_slip.py
Python
agpl-3.0
76,450
frappe.listview_settings["Salary Slip"] = { onload: function (listview) { if ( !has_common(frappe.user_roles, [ "Administrator", "System Manager", "HR Manager", "HR User", ]) ) return; listview.page.add_menu_item(__("Email Salary Slips"), () => { if (!listview.get_checked_items().length) { frappe.msgprint(__("Please select the salary slips to email")); return; } frappe.confirm(__("Are you sure you want to email the selected salary slips?"), () => { listview.call_for_selected_items( "hrms.payroll.doctype.salary_slip.salary_slip.enqueue_email_salary_slips", ); }); }); }, };
2302_79757062/hrms
hrms/payroll/doctype/salary_slip/salary_slip_list.js
JavaScript
agpl-3.0
649
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from typing import TYPE_CHECKING import frappe from frappe import _ if TYPE_CHECKING: from hrms.payroll.doctype.salary_slip.salary_slip import SalarySlip def if_lending_app_installed(function): """Decorator to check if lending app is installed""" def wrapper(*args, **kwargs): if "lending" in frappe.get_installed_apps(): return function(*args, **kwargs) return return wrapper @if_lending_app_installed def set_loan_repayment(doc: "SalarySlip"): from lending.loan_management.doctype.loan_repayment.loan_repayment import calculate_amounts doc.total_loan_repayment = 0 doc.total_interest_amount = 0 doc.total_principal_amount = 0 if not doc.get("loans", []): loan_details = _get_loan_details(doc) if loan_details: process_loan_interest_accruals(loan_details, doc.end_date) for loan in loan_details: amounts = calculate_amounts(loan.name, doc.end_date, "Regular Payment") if amounts["interest_amount"] or amounts["payable_principal_amount"]: doc.append( "loans", { "loan": loan.name, "total_payment": amounts["interest_amount"] + amounts["payable_principal_amount"], "interest_amount": amounts["interest_amount"], "principal_amount": amounts["payable_principal_amount"], "loan_account": loan.loan_account, "interest_income_account": loan.interest_income_account, }, ) if not doc.get("loans"): doc.set("loans", []) for payment in doc.get("loans", []): amounts = calculate_amounts(payment.loan, doc.end_date, "Regular Payment") total_amount = amounts["interest_amount"] + amounts["payable_principal_amount"] if payment.total_payment > total_amount: frappe.throw( _( """Row {0}: Paid amount {1} is greater than pending accrued amount {2} against loan {3}""" ).format( payment.idx, frappe.bold(payment.total_payment), frappe.bold(total_amount), frappe.bold(payment.loan), ) ) doc.total_interest_amount += payment.interest_amount doc.total_principal_amount += payment.principal_amount doc.total_loan_repayment += payment.total_payment def _get_loan_details(doc: "SalarySlip") -> dict[str, str | bool]: loan_details = frappe.get_all( "Loan", fields=["name", "interest_income_account", "loan_account", "loan_product", "is_term_loan"], filters={ "applicant": doc.employee, "docstatus": 1, "repay_from_salary": 1, "company": doc.company, "status": ("!=", "Closed"), }, ) return loan_details def process_loan_interest_accruals(loan_details: dict[str, str | bool], posting_date: str): from lending.loan_management.doctype.process_loan_interest_accrual.process_loan_interest_accrual import ( process_loan_interest_accrual_for_term_loans, ) for loan in loan_details: if loan.is_term_loan: process_loan_interest_accrual_for_term_loans( posting_date=posting_date, loan_product=loan.loan_product, loan=loan.name ) @if_lending_app_installed def make_loan_repayment_entry(doc: "SalarySlip"): from lending.loan_management.doctype.loan_repayment.loan_repayment import create_repayment_entry payroll_payable_account = get_payroll_payable_account(doc.company, doc.payroll_entry) process_payroll_accounting_entry_based_on_employee = frappe.db.get_single_value( "Payroll Settings", "process_payroll_accounting_entry_based_on_employee" ) if not doc.get("loans"): doc.set("loans", []) for loan in doc.get("loans", []): if not loan.total_payment: continue repayment_entry = create_repayment_entry( loan.loan, doc.employee, doc.company, doc.posting_date, loan.loan_product, "Regular Payment", loan.interest_amount, loan.principal_amount, loan.total_payment, payroll_payable_account=payroll_payable_account, process_payroll_accounting_entry_based_on_employee=process_payroll_accounting_entry_based_on_employee, ) repayment_entry.save() repayment_entry.submit() frappe.db.set_value("Salary Slip Loan", loan.name, "loan_repayment_entry", repayment_entry.name) @if_lending_app_installed def cancel_loan_repayment_entry(doc: "SalarySlip"): if not doc.get("loans"): doc.set("loans", []) for loan in doc.get("loans", []): if loan.loan_repayment_entry: repayment_entry = frappe.get_doc("Loan Repayment", loan.loan_repayment_entry) repayment_entry.cancel() def get_payroll_payable_account(company, payroll_entry): if payroll_entry: payroll_payable_account = frappe.db.get_value( "Payroll Entry", payroll_entry, "payroll_payable_account" ) else: payroll_payable_account = frappe.db.get_value("Company", company, "default_payroll_payable_account") return payroll_payable_account
2302_79757062/hrms
hrms/payroll/doctype/salary_slip/salary_slip_loan_utils.py
Python
agpl-3.0
4,772
# 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 SalarySlipLeave(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/salary_slip_leave/salary_slip_leave.py
Python
agpl-3.0
221
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class SalarySlipLoan(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/salary_slip_loan/salary_slip_loan.py
Python
agpl-3.0
220
# 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 SalarySlipTimesheet(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/salary_slip_timesheet/salary_slip_timesheet.py
Python
agpl-3.0
225
<h3>Variables</h3> <ul> <li> Variables from Salary Structure Assignment:<br> <code>base = Base</code>, <code>variable = Variable</code> etc. </li> <li> Variables from Employee:<br> <code>Employment Type = employment_type</code>, <code>Branch = branch</code> etc. </li> <li> Variables from Salary Slip:<br> <code>Payment Days = payment_days</code>, <code>Leave without pay = leave_without_pay</code> etc. </li> <li> Abbreviation from Salary Component:<br> <code>BS = Basic Salary</code> etc. </li> <li> Some additional variable:<br> <code>gross_pay</code> and <code>annual_taxable_earning</code> can also be used. </li> <li>Direct Amount can also be used</li> </ul> <h3>Examples for Conditions and formula</h3> <ul> <li> Calculating Basic Salary based on <code>base</code> <pre><code>Condition: base &lt; 10000</code></pre> <pre><code>Formula: base * .2</code></pre> </li> <li> Calculating HRA based on Basic Salary<code>BS</code> <pre><code>Condition: BS &gt; 2000</code></pre> <pre><code>Formula: BS * .1</code></pre> </li> <li> Calculating TDS based on Employment Type<code>employment_type</code> <pre><code>Condition: employment_type=="Intern"</code></pre> <pre><code>Amount: 1000</code></pre> </li> <li> Calculating Income Tax based on <code>annual_taxable_earning </code> <pre><code>Condition: annual_taxable_earning > 20000000</code></pre> <pre><code>Formula: annual_taxable_earning * 0.10 </code></pre> </li> </ul>
2302_79757062/hrms
hrms/payroll/doctype/salary_structure/condition_and_formula_help.html
HTML
agpl-3.0
1,671
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.ui.form.on("Salary Structure", { onload: function (frm) { frm.alerted_rows = []; let help_button = $(`<a class = 'control-label'> ${__("Condition and Formula Help")} </a>`).click(() => { let d = new frappe.ui.Dialog({ title: __("Condition and Formula Help"), fields: [ { fieldname: "msg_wrapper", fieldtype: "HTML", }, ], }); let message_html = frappe.render_template("condition_and_formula_help"); d.fields_dict.msg_wrapper.$wrapper.append(message_html); d.show(); }); let help_button_wrapper = frm.get_field( "conditions_and_formula_variable_and_example", ).$wrapper; help_button_wrapper.empty(); help_button_wrapper.append(frm.doc.filters_html).append(help_button); frm.toggle_reqd(["payroll_frequency"], !frm.doc.salary_slip_based_on_timesheet); frm.set_query("payment_account", function () { var account_types = ["Bank", "Cash"]; return { filters: { account_type: ["in", account_types], is_group: 0, company: frm.doc.company, }, }; }); frm.trigger("set_earning_deduction_component"); }, mode_of_payment: function (frm) { erpnext.accounts.pos.get_payment_mode_account( frm, frm.doc.mode_of_payment, function (account) { frm.set_value("payment_account", account); }, ); }, set_earning_deduction_component: function (frm) { if (!frm.doc.company) return; frm.set_query("salary_component", "earnings", function () { return { filters: { component_type: "earning", company: frm.doc.company }, query: "hrms.payroll.doctype.salary_structure.salary_structure.get_salary_component", }; }); frm.set_query("salary_component", "deductions", function () { return { filters: { component_type: "deduction", company: frm.doc.company }, query: "hrms.payroll.doctype.salary_structure.salary_structure.get_salary_component", }; }); }, company: function (frm) { frm.trigger("set_earning_deduction_component"); }, currency: function (frm) { calculate_totals(frm.doc); frm.trigger("set_dynamic_labels"); frm.refresh(); }, set_dynamic_labels: function (frm) { frm.set_currency_labels( [ "net_pay", "hour_rate", "leave_encashment_amount_per_day", "max_benefits", "total_earning", "total_deduction", ], frm.doc.currency, ); frm.set_currency_labels( ["amount", "additional_amount", "tax_on_flexible_benefit", "tax_on_additional_salary"], frm.doc.currency, "earnings", ); frm.set_currency_labels( ["amount", "additional_amount", "tax_on_flexible_benefit", "tax_on_additional_salary"], frm.doc.currency, "deductions", ); frm.refresh_fields(); }, refresh: function (frm) { frm.trigger("set_dynamic_labels"); frm.trigger("toggle_fields"); frm.fields_dict["earnings"].grid.set_column_disp("default_amount", false); frm.fields_dict["deductions"].grid.set_column_disp("default_amount", false); if (frm.doc.docstatus === 1) { frm.add_custom_button( __("Single Assignment"), function () { const doc = frappe.model.get_new_doc("Salary Structure Assignment"); doc.salary_structure = frm.doc.name; doc.company = frm.doc.company; frappe.set_route("Form", "Salary Structure Assignment", doc.name); }, __("Create"), ); frm.add_custom_button( __("Bulk Assignments"), () => { const doc = frappe.model.get_new_doc("Bulk Salary Structure Assignment"); doc.salary_structure = frm.doc.name; doc.company = frm.doc.company; frappe.set_route("Form", "Bulk Salary Structure Assignment", doc.name); }, __("Create"), ); frm.add_custom_button( __("Income Tax Slab"), () => { frappe.model.with_doctype("Income Tax Slab", () => { const doc = frappe.model.get_new_doc("Income Tax Slab"); frappe.set_route("Form", "Income Tax Slab", doc.name); }); }, __("Create"), ); frm.page.set_inner_btn_group_as_primary(__("Create")); frm.add_custom_button( __("Preview Salary Slip"), function () { frm.trigger("preview_salary_slip"); }, __("Actions"), ); } // set columns read-only let fields_read_only = [ "is_tax_applicable", "is_flexible_benefit", "variable_based_on_taxable_salary", ]; fields_read_only.forEach(function (field) { frm.fields_dict.earnings.grid.update_docfield_property(field, "read_only", 1); frm.fields_dict.deductions.grid.update_docfield_property(field, "read_only", 1); }); frm.trigger("set_earning_deduction_component"); }, salary_slip_based_on_timesheet: function (frm) { frm.trigger("toggle_fields"); hrms.set_payroll_frequency_to_null(frm); }, preview_salary_slip: function (frm) { frappe.call({ method: "hrms.payroll.doctype.salary_structure.salary_structure.get_employees", args: { salary_structure: frm.doc.name, }, callback: function (r) { var employees = r.message; if (!employees) return; if (employees.length == 1) { frm.events.open_salary_slip(frm, employees[0]); } else { var d = new frappe.ui.Dialog({ title: __("Preview Salary Slip"), fields: [ { label: __("Employee"), fieldname: "employee", fieldtype: "Autocomplete", reqd: true, options: employees, }, { fieldname: "fetch", label: __("Show Salary Slip"), fieldtype: "Button", }, ], }); d.get_input("fetch").on("click", function () { var values = d.get_values(); if (!values) return; frm.events.open_salary_slip(frm, values.employee); }); d.show(); } }, }); }, open_salary_slip: function (frm, employee) { var print_format = frm.doc.salary_slip_based_on_timesheet ? "Salary Slip based on Timesheet" : "Salary Slip Standard"; frappe.call({ method: "hrms.payroll.doctype.salary_structure.salary_structure.make_salary_slip", args: { source_name: frm.doc.name, employee: employee, as_print: 1, print_format: print_format, for_preview: 1, }, callback: function (r) { var new_window = window.open(); new_window.document.write(r.message); }, }); }, toggle_fields: function (frm) { frm.toggle_display( ["salary_component", "hour_rate"], frm.doc.salary_slip_based_on_timesheet, ); frm.toggle_reqd(["salary_component", "hour_rate"], frm.doc.salary_slip_based_on_timesheet); frm.toggle_reqd(["payroll_frequency"], !frm.doc.salary_slip_based_on_timesheet); }, }); var validate_date = function (frm, cdt, cdn) { var doc = locals[cdt][cdn]; if (doc.to_date && doc.from_date) { var from_date = frappe.datetime.str_to_obj(doc.from_date); var to_date = frappe.datetime.str_to_obj(doc.to_date); if (to_date < from_date) { frappe.model.set_value(cdt, cdn, "to_date", ""); frappe.throw(__("From Date cannot be greater than To Date")); } } }; // nosemgrep: frappe-semgrep-rules.rules.frappe-cur-frm-usage cur_frm.cscript.amount = function (doc, cdt, cdn) { calculate_totals(doc, cdt, cdn); }; var calculate_totals = function (doc) { var tbl1 = doc.earnings || []; var tbl2 = doc.deductions || []; var total_earn = 0; var total_ded = 0; for (var i = 0; i < tbl1.length; i++) { total_earn += flt(tbl1[i].amount); } for (var j = 0; j < tbl2.length; j++) { total_ded += flt(tbl2[j].amount); } doc.total_earning = total_earn; doc.total_deduction = total_ded; doc.net_pay = 0.0; if (doc.salary_slip_based_on_timesheet == 0) { doc.net_pay = flt(total_earn) - flt(total_ded); } refresh_many(["total_earning", "total_deduction", "net_pay"]); }; // nosemgrep: frappe-semgrep-rules.rules.frappe-cur-frm-usage cur_frm.cscript.validate = function (doc, cdt, cdn) { calculate_totals(doc); }; frappe.ui.form.on("Salary Detail", { form_render: function (frm, cdt, cdn) { const row = locals[cdt][cdn]; hrms.payroll_utils.set_autocompletions_for_condition_and_formula(frm, row); }, amount: function (frm) { calculate_totals(frm.doc); }, earnings_remove: function (frm) { calculate_totals(frm.doc); }, deductions_remove: function (frm) { calculate_totals(frm.doc); }, formula: function (frm, cdt, cdn) { const row = locals[cdt][cdn]; if (row.formula && !row?.amount_based_on_formula && !frm.alerted_rows.includes(cdn)) { frappe.msgprint({ message: __( "{0} Row #{1}: {2} needs to be enabled for the formula to be considered.", [toTitle(row.parentfield), row.idx, __("Amount based on formula").bold()], ), title: __("Warning"), indicator: "orange", }); frm.alerted_rows.push(cdn); } }, salary_component: function (frm, cdt, cdn) { var child = locals[cdt][cdn]; if (child.salary_component) { frappe.call({ method: "frappe.client.get", args: { doctype: "Salary Component", name: child.salary_component, }, callback: function (data) { if (data.message) { var result = data.message; frappe.model.set_value(cdt, cdn, "condition", result.condition); frappe.model.set_value( cdt, cdn, "amount_based_on_formula", result.amount_based_on_formula, ); if (result.amount_based_on_formula == 1) { frappe.model.set_value(cdt, cdn, "formula", result.formula); } else { frappe.model.set_value(cdt, cdn, "amount", result.amount); } frappe.model.set_value( cdt, cdn, "statistical_component", result.statistical_component, ); frappe.model.set_value( cdt, cdn, "depends_on_payment_days", result.depends_on_payment_days, ); frappe.model.set_value( cdt, cdn, "do_not_include_in_total", result.do_not_include_in_total, ); frappe.model.set_value( cdt, cdn, "variable_based_on_taxable_salary", result.variable_based_on_taxable_salary, ); frappe.model.set_value( cdt, cdn, "is_tax_applicable", result.is_tax_applicable, ); frappe.model.set_value( cdt, cdn, "is_flexible_benefit", result.is_flexible_benefit, ); refresh_field("earnings"); refresh_field("deductions"); } }, }); } }, amount_based_on_formula: function (frm, cdt, cdn) { var child = locals[cdt][cdn]; if (child.amount_based_on_formula == 1) { frappe.model.set_value(cdt, cdn, "amount", null); const index = frm.alerted_rows.indexOf(cdn); if (index > -1) frm.alerted_rows.splice(index, 1); } else { frappe.model.set_value(cdt, cdn, "formula", null); } }, });
2302_79757062/hrms
hrms/payroll/doctype/salary_structure/salary_structure.js
JavaScript
agpl-3.0
10,800
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import re import frappe from frappe import _ from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from frappe.utils import cint, cstr, flt import erpnext from hrms.payroll.utils import sanitize_expression class SalaryStructure(Document): def before_validate(self): self.sanitize_condition_and_formula_fields() def before_update_after_submit(self): self.sanitize_condition_and_formula_fields() def validate(self): self.set_missing_values() self.validate_amount() self.validate_max_benefits_with_flexi() self.validate_component_based_on_tax_slab() self.validate_payment_days_based_dependent_component() self.validate_timesheet_component() self.validate_formula_setup() def on_update(self): self.reset_condition_and_formula_fields() def on_update_after_submit(self): self.reset_condition_and_formula_fields() def validate_formula_setup(self): for table in ["earnings", "deductions"]: for row in self.get(table): if not row.amount_based_on_formula and row.formula: frappe.msgprint( _( "{0} Row #{1}: Formula is set but {2} is disabled for the Salary Component {3}." ).format( table.capitalize(), row.idx, frappe.bold(_("Amount Based on Formula")), frappe.bold(row.salary_component), ), title=_("Warning"), indicator="orange", ) def set_missing_values(self): overwritten_fields = [ "depends_on_payment_days", "variable_based_on_taxable_salary", "is_tax_applicable", "is_flexible_benefit", ] overwritten_fields_if_missing = ["amount_based_on_formula", "formula", "amount"] for table in ["earnings", "deductions"]: for d in self.get(table): component_default_value = frappe.db.get_value( "Salary Component", cstr(d.salary_component), overwritten_fields + overwritten_fields_if_missing, as_dict=1, ) if component_default_value: for fieldname in overwritten_fields: value = component_default_value.get(fieldname) if d.get(fieldname) != value: d.set(fieldname, value) if not (d.get("amount") or d.get("formula")): for fieldname in overwritten_fields_if_missing: d.set(fieldname, component_default_value.get(fieldname)) def validate_component_based_on_tax_slab(self): for row in self.deductions: if row.variable_based_on_taxable_salary and (row.amount or row.formula): frappe.throw( _( "Row #{0}: Cannot set amount or formula for Salary Component {1} with Variable Based On Taxable Salary" ).format(row.idx, row.salary_component) ) def validate_amount(self): if flt(self.net_pay) < 0 and self.salary_slip_based_on_timesheet: frappe.throw(_("Net pay cannot be negative")) def validate_payment_days_based_dependent_component(self): abbreviations = self.get_component_abbreviations() for component_type in ("earnings", "deductions"): for row in self.get(component_type): if ( row.formula and row.depends_on_payment_days # check if the formula contains any of the payment days components and any(re.search(r"\b" + abbr + r"\b", row.formula) for abbr in abbreviations) ): message = _("Row #{0}: The {1} Component has the options {2} and {3} enabled.").format( row.idx, frappe.bold(row.salary_component), frappe.bold(_("Amount based on formula")), frappe.bold(_("Depends On Payment Days")), ) message += "<br><br>" + _( "Disable {0} for the {1} component, to prevent the amount from being deducted twice, as its formula already uses a payment-days-based component." ).format(frappe.bold(_("Depends On Payment Days")), frappe.bold(row.salary_component)) frappe.throw(message, title=_("Payment Days Dependency")) def get_component_abbreviations(self): abbr = [d.abbr for d in self.earnings if d.depends_on_payment_days] abbr += [d.abbr for d in self.deductions if d.depends_on_payment_days] return abbr def validate_timesheet_component(self): if not self.salary_slip_based_on_timesheet: return for component in self.earnings: if component.salary_component == self.salary_component: frappe.msgprint( _( "Row #{0}: Timesheet amount will overwrite the Earning component amount for the Salary Component {1}" ).format(self.idx, frappe.bold(self.salary_component)), title=_("Warning"), indicator="orange", ) break def sanitize_condition_and_formula_fields(self): for table in ("earnings", "deductions"): for row in self.get(table): row.condition = row.condition.strip() if row.condition else "" row.formula = row.formula.strip() if row.formula else "" row._condition, row.condition = row.condition, sanitize_expression(row.condition) row._formula, row.formula = row.formula, sanitize_expression(row.formula) def reset_condition_and_formula_fields(self): # set old values (allowing multiline strings for better readability in the doctype form) for table in ("earnings", "deductions"): for row in self.get(table): row.condition = row._condition row.formula = row._formula self.db_update_all() def validate_max_benefits_with_flexi(self): have_a_flexi = False if self.earnings: flexi_amount = 0 for earning_component in self.earnings: if earning_component.is_flexible_benefit == 1: have_a_flexi = True max_of_component = frappe.db.get_value( "Salary Component", earning_component.salary_component, "max_benefit_amount" ) flexi_amount += max_of_component if have_a_flexi and flt(self.max_benefits) == 0: frappe.throw(_("Max benefits should be greater than zero to dispense benefits")) if have_a_flexi and flexi_amount and flt(self.max_benefits) > flexi_amount: frappe.throw( _( "Total flexible benefit component amount {0} should not be less than max benefits {1}" ).format(flexi_amount, self.max_benefits) ) if not have_a_flexi and flt(self.max_benefits) > 0: frappe.throw( _("Salary Structure should have flexible benefit component(s) to dispense benefit amount") ) def get_employees(self, **kwargs): conditions, values = [], [] for field, value in kwargs.items(): if value: conditions.append(f"{field}=%s") values.append(value) condition_str = " and " + " and ".join(conditions) if conditions else "" # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql employees = frappe.db.sql_list( f"select name from tabEmployee where status='Active' {condition_str}", tuple(values), ) return employees @frappe.whitelist() def assign_salary_structure( self, branch=None, grade=None, department=None, designation=None, employee=None, payroll_payable_account=None, from_date=None, base=None, variable=None, income_tax_slab=None, ): employees = self.get_employees( company=self.company, grade=grade, department=department, designation=designation, name=employee, branch=branch, ) if employees: if len(employees) > 20: frappe.enqueue( assign_salary_structure_for_employees, timeout=3000, employees=employees, salary_structure=self, payroll_payable_account=payroll_payable_account, from_date=from_date, base=base, variable=variable, income_tax_slab=income_tax_slab, ) else: assign_salary_structure_for_employees( employees, self, payroll_payable_account=payroll_payable_account, from_date=from_date, base=base, variable=variable, income_tax_slab=income_tax_slab, ) else: frappe.msgprint(_("No Employee Found")) def assign_salary_structure_for_employees( employees, salary_structure, payroll_payable_account=None, from_date=None, base=None, variable=None, income_tax_slab=None, ): assignments = [] existing_assignments_for = get_existing_assignments(employees, salary_structure, from_date) count = 0 savepoint = "before_assignment_submission" for employee in employees: try: frappe.db.savepoint(savepoint) if employee in existing_assignments_for: continue count += 1 assignment = create_salary_structure_assignment( employee, salary_structure.name, salary_structure.company, salary_structure.currency, from_date, payroll_payable_account, base, variable, income_tax_slab, ) assignments.append(assignment) frappe.publish_progress( count * 100 / len(set(employees) - set(existing_assignments_for)), title=_("Assigning Structures..."), ) except Exception: frappe.db.rollback(save_point=savepoint) frappe.log_error( f"Salary Structure Assignment failed for employee {employee}", reference_doctype="Salary Structure Assignment", ) if assignments: frappe.msgprint(_("Structures have been assigned successfully")) def create_salary_structure_assignment( employee, salary_structure, company, currency, from_date, payroll_payable_account=None, base=None, variable=None, income_tax_slab=None, ): assignment = frappe.new_doc("Salary Structure Assignment") if not payroll_payable_account: payroll_payable_account = frappe.db.get_value("Company", company, "default_payroll_payable_account") if not payroll_payable_account: frappe.throw(_('Please set "Default Payroll Payable Account" in Company Defaults')) payroll_payable_account_currency = frappe.db.get_value( "Account", payroll_payable_account, "account_currency" ) company_curency = erpnext.get_company_currency(company) if payroll_payable_account_currency != currency and payroll_payable_account_currency != company_curency: frappe.throw( _("Invalid Payroll Payable Account. The account currency must be {0} or {1}").format( currency, company_curency ) ) assignment.employee = employee assignment.salary_structure = salary_structure assignment.company = company assignment.currency = currency assignment.payroll_payable_account = payroll_payable_account assignment.from_date = from_date assignment.base = base assignment.variable = variable assignment.income_tax_slab = income_tax_slab assignment.save(ignore_permissions=True) assignment.submit() return assignment.name def get_existing_assignments(employees, salary_structure, from_date): # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql salary_structures_assignments = frappe.db.sql_list( f""" SELECT DISTINCT employee FROM `tabSalary Structure Assignment` WHERE salary_structure=%s AND employee IN ({", ".join(["%s"] * len(employees))}) AND from_date=%s AND company=%s AND docstatus=1 """, [salary_structure.name, *employees, from_date, salary_structure.company], ) if salary_structures_assignments: frappe.msgprint( _( "Skipping Salary Structure Assignment for the following employees, as Salary Structure Assignment records already exists against them. {0}" ).format("\n".join(salary_structures_assignments)) ) return salary_structures_assignments @frappe.whitelist() def make_salary_slip( source_name, target_doc=None, employee=None, posting_date=None, as_print=False, print_format=None, for_preview=0, ignore_permissions=False, ): def postprocess(source, target): if employee: target.employee = employee if posting_date: target.posting_date = posting_date target.run_method("process_salary_structure", for_preview=for_preview) doc = get_mapped_doc( "Salary Structure", source_name, { "Salary Structure": { "doctype": "Salary Slip", "field_map": { "total_earning": "gross_pay", "name": "salary_structure", "currency": "currency", }, } }, target_doc, postprocess, ignore_child_tables=True, ignore_permissions=ignore_permissions, cached=True, ) if cint(as_print): doc.name = f"Preview for {employee}" return frappe.get_print(doc.doctype, doc.name, doc=doc, print_format=print_format) else: return doc @frappe.whitelist() def get_employees(salary_structure): employees = frappe.get_list( "Salary Structure Assignment", filters={"salary_structure": salary_structure, "docstatus": 1}, pluck="employee", ) if not employees: frappe.throw( _( "There's no Employee with Salary Structure: {0}. Assign {1} to an Employee to preview Salary Slip" ).format(salary_structure, salary_structure) ) return list(set(employees)) @frappe.whitelist() def get_salary_component(doctype, txt, searchfield, start, page_len, filters): sc = frappe.qb.DocType("Salary Component") sca = frappe.qb.DocType("Salary Component Account") salary_components = ( frappe.qb.from_(sc) .left_join(sca) .on(sca.parent == sc.name) .select(sc.name, sca.account, sca.company) .where( (sc.type == filters.get("component_type")) & (sc.disabled == 0) & (sc[searchfield].like(f"%{txt}%") | sc.name.like(f"%{txt}%")) ) .limit(page_len) .offset(start) ).run(as_dict=True) accounts = [] for component in salary_components: if not component.company: accounts.append((component.name, component.account, component.company)) else: if component.company == filters["company"]: accounts.append((component.name, component.account, component.company)) return accounts
2302_79757062/hrms
hrms/payroll/doctype/salary_structure/salary_structure.py
Python
agpl-3.0
13,352
def get_data(): return { "fieldname": "salary_structure", "non_standard_fieldnames": {"Employee Grade": "default_salary_structure"}, "transactions": [ {"items": ["Salary Structure Assignment", "Salary Slip"]}, {"items": ["Employee Grade"]}, ], }
2302_79757062/hrms
hrms/payroll/doctype/salary_structure/salary_structure_dashboard.py
Python
agpl-3.0
262
frappe.listview_settings["Salary Structure"] = { onload: function (list_view) { list_view.page.add_inner_button(__("Bulk Salary Structure Assignment"), function () { frappe.set_route("Form", "Bulk Salary Structure Assignment"); }); }, };
2302_79757062/hrms
hrms/payroll/doctype/salary_structure/salary_structure_list.js
JavaScript
agpl-3.0
247
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Salary Structure Assignment", { setup: function (frm) { frm.set_query("employee", function () { return { query: "erpnext.controllers.queries.employee_query", filters: { company: frm.doc.company }, }; }); frm.set_query("salary_structure", function () { return { filters: { company: frm.doc.company, docstatus: 1, is_active: "Yes", }, }; }); frm.set_query("income_tax_slab", function () { return { filters: { company: frm.doc.company, docstatus: 1, disabled: 0, currency: frm.doc.currency, }, }; }); frm.set_query("payroll_payable_account", function () { var 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]], }, }; }); frm.set_query("cost_center", "payroll_cost_centers", function () { return { filters: { company: frm.doc.company, is_group: 0, }, }; }); }, refresh: function (frm) { if (frm.doc.__onload) { frm.unhide_earnings_and_taxation_section = frm.doc.__onload.earning_and_deduction_entries_does_not_exists; frm.trigger("set_earnings_and_taxation_section_visibility"); } if (frm.doc.docstatus != 1) return; frm.add_custom_button( __("Payroll Entry"), () => { frappe.model.with_doctype("Payroll Entry", () => { const doc = frappe.model.get_new_doc("Payroll Entry"); frappe.set_route("Form", "Payroll Entry", doc.name); }); }, __("Create"), ); frm.page.set_inner_btn_group_as_primary(__("Create")); frm.add_custom_button( __("Preview Salary Slip"), function () { frm.trigger("preview_salary_slip"); }, __("Actions"), ); }, employee: function (frm) { if (frm.doc.employee) { frm.trigger("set_payroll_cost_centers"); frm.trigger("valiadte_joining_date_and_salary_slips"); } else { frm.set_value("payroll_cost_centers", []); } }, company: function (frm) { if (frm.doc.company) { frappe.db.get_value( "Company", frm.doc.company, "default_payroll_payable_account", (r) => { frm.set_value("payroll_payable_account", r.default_payroll_payable_account); }, ); } }, preview_salary_slip: function (frm) { frappe.db.get_value( "Salary Structure", frm.doc.salary_structure, "salary_slip_based_on_timesheet", (r) => { const print_format = r.salary_slip_based_on_timesheet ? "Salary Slip based on Timesheet" : "Salary Slip Standard"; frappe.call({ method: "hrms.payroll.doctype.salary_structure.salary_structure.make_salary_slip", args: { source_name: frm.doc.salary_structure, employee: frm.doc.employee, posting_date: frm.doc.from_date, as_print: 1, print_format: print_format, for_preview: 1, }, callback: function (r) { const new_window = window.open(); new_window.document.write(r.message); }, }); }, ); }, set_payroll_cost_centers: function (frm) { if (frm.doc.payroll_cost_centers && frm.doc.payroll_cost_centers.length < 1) { frappe.call({ method: "set_payroll_cost_centers", doc: frm.doc, callback: function (data) { refresh_field("payroll_cost_centers"); }, }); } }, valiadte_joining_date_and_salary_slips: function (frm) { frappe.call({ method: "earning_and_deduction_entries_does_not_exists", doc: frm.doc, callback: function (data) { let earning_and_deduction_entries_does_not_exists = data.message; frm.unhide_earnings_and_taxation_section = earning_and_deduction_entries_does_not_exists; frm.trigger("set_earnings_and_taxation_section_visibility"); }, }); }, set_earnings_and_taxation_section_visibility: function (frm) { if (frm.unhide_earnings_and_taxation_section) { frm.set_df_property("earnings_and_taxation_section", "hidden", 0); } else { frm.set_df_property("earnings_and_taxation_section", "hidden", 1); } }, from_date: function (frm) { if (frm.doc.from_date) { frm.trigger("valiadte_joining_date_and_salary_slips"); } }, });
2302_79757062/hrms
hrms/payroll/doctype/salary_structure_assignment/salary_structure_assignment.js
JavaScript
agpl-3.0
4,344
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import cint, flt, get_link_to_form, getdate class DuplicateAssignment(frappe.ValidationError): pass class SalaryStructureAssignment(Document): def onload(self): if self.employee: self.set_onload( "earning_and_deduction_entries_does_not_exists", self.earning_and_deduction_entries_does_not_exists(), ) def validate(self): self.validate_dates() self.validate_company() self.validate_income_tax_slab() self.set_payroll_payable_account() if self.earning_and_deduction_entries_does_not_exists(): if not self.taxable_earnings_till_date and not self.tax_deducted_till_date: frappe.msgprint( _( """ Not found any salary slip record(s) for the employee {0}. <br><br> Please specify {1} and {2} (if any), for the correct tax calculation in future salary slips. """ ).format( self.employee, "<b>" + _("Taxable Earnings Till Date") + "</b>", "<b>" + _("Tax Deducted Till Date") + "</b>", ), indicator="orange", title=_("Warning"), ) if not self.get("payroll_cost_centers"): self.set_payroll_cost_centers() self.validate_cost_center_distribution() def validate_dates(self): joining_date, relieving_date = frappe.db.get_value( "Employee", self.employee, ["date_of_joining", "relieving_date"] ) if self.from_date: if frappe.db.exists( "Salary Structure Assignment", {"employee": self.employee, "from_date": self.from_date, "docstatus": 1}, ): frappe.throw( _("Salary Structure Assignment for Employee already exists"), DuplicateAssignment ) if joining_date and getdate(self.from_date) < joining_date: frappe.throw( _("From Date {0} cannot be before employee's joining Date {1}").format( self.from_date, joining_date ) ) # flag - old_employee is for migrating the old employees data via patch if relieving_date and getdate(self.from_date) > relieving_date and not self.flags.old_employee: frappe.throw( _("From Date {0} cannot be after employee's relieving Date {1}").format( self.from_date, relieving_date ) ) def validate_company(self): salary_structure_company = frappe.db.get_value( "Salary Structure", self.salary_structure, "company", cache=True ) if self.company != salary_structure_company: frappe.throw( _("Salary Structure {0} does not belong to company {1}").format( frappe.bold(self.salary_structure), frappe.bold(self.company) ) ) def validate_income_tax_slab(self): tax_component = get_tax_component(self.salary_structure) if tax_component and not self.income_tax_slab: frappe.throw( _( "Income Tax Slab is mandatory since the Salary Structure {0} has a tax component {1}" ).format( get_link_to_form("Salary Structure", self.salary_structure), frappe.bold(tax_component) ), exc=frappe.MandatoryError, title=_("Missing Mandatory Field"), ) if not self.income_tax_slab: return income_tax_slab_currency = frappe.db.get_value("Income Tax Slab", self.income_tax_slab, "currency") if self.currency != income_tax_slab_currency: frappe.throw( _("Currency of selected Income Tax Slab should be {0} instead of {1}").format( self.currency, income_tax_slab_currency ) ) def set_payroll_payable_account(self): if not self.payroll_payable_account: payroll_payable_account = frappe.db.get_value( "Company", self.company, "default_payroll_payable_account" ) if not payroll_payable_account: payroll_payable_account = frappe.db.get_value( "Account", { "account_name": _("Payroll Payable"), "company": self.company, "account_currency": frappe.db.get_value("Company", self.company, "default_currency"), "is_group": 0, }, ) self.payroll_payable_account = payroll_payable_account @frappe.whitelist() def set_payroll_cost_centers(self): self.payroll_cost_centers = [] default_payroll_cost_center = self.get_payroll_cost_center() if default_payroll_cost_center: self.append( "payroll_cost_centers", {"cost_center": default_payroll_cost_center, "percentage": 100} ) def get_payroll_cost_center(self): payroll_cost_center = frappe.db.get_value("Employee", self.employee, "payroll_cost_center") if not payroll_cost_center and self.department: payroll_cost_center = frappe.db.get_value("Department", self.department, "payroll_cost_center") return payroll_cost_center def validate_cost_center_distribution(self): if self.get("payroll_cost_centers"): total_percentage = sum([flt(d.percentage) for d in self.get("payroll_cost_centers", [])]) if total_percentage != 100: frappe.throw(_("Total percentage against cost centers should be 100")) @frappe.whitelist() def earning_and_deduction_entries_does_not_exists(self): if self.enabled_settings_to_specify_earnings_and_deductions_till_date(): if not self.joined_in_the_same_month() and not self.have_salary_slips(): return True else: if self.docstatus in [1, 2] and ( self.taxable_earnings_till_date or self.tax_deducted_till_date ): return True return False else: return False def enabled_settings_to_specify_earnings_and_deductions_till_date(self): """returns True if settings are enabled to specify earnings and deductions till date else False""" if frappe.db.get_single_value( "Payroll Settings", "define_opening_balance_for_earning_and_deductions" ): return True return False def have_salary_slips(self): """returns True if salary structure assignment has salary slips else False""" salary_slip = frappe.db.get_value("Salary Slip", filters={"employee": self.employee, "docstatus": 1}) if salary_slip: return True return False def joined_in_the_same_month(self): """returns True if employee joined in same month as salary structure assignment from date else False""" date_of_joining = frappe.db.get_value("Employee", self.employee, "date_of_joining") from_date = getdate(self.from_date) if not self.from_date or not date_of_joining: return False elif date_of_joining.month == from_date.month: return True else: return False def get_assigned_salary_structure(employee, on_date): if not employee or not on_date: return None salary_structure = frappe.db.sql( """ select salary_structure from `tabSalary Structure Assignment` where employee=%(employee)s and docstatus = 1 and %(on_date)s >= from_date order by from_date desc limit 1""", { "employee": employee, "on_date": on_date, }, ) return salary_structure[0][0] if salary_structure else None @frappe.whitelist() def get_employee_currency(employee): employee_currency = frappe.db.get_value("Salary Structure Assignment", {"employee": employee}, "currency") if not employee_currency: frappe.throw( _("There is no Salary Structure assigned to {0}. First assign a Salary Stucture.").format( employee ) ) return employee_currency def get_tax_component(salary_structure: str) -> str | None: salary_structure = frappe.get_cached_doc("Salary Structure", salary_structure) for d in salary_structure.deductions: if cint(d.variable_based_on_taxable_salary) and not d.formula and not flt(d.amount): return d.salary_component return None
2302_79757062/hrms
hrms/payroll/doctype/salary_structure_assignment/salary_structure_assignment.py
Python
agpl-3.0
7,510
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Salary Withholding", { employee(frm) { if (!frm.doc.employee) return; frappe .call({ method: "hrms.payroll.doctype.salary_withholding.salary_withholding.get_payroll_frequency", args: { employee: frm.doc.employee, posting_date: frm.doc.posting_date, }, }) .then((r) => { if (r.message) { frm.set_value("payroll_frequency", r.message); } }); }, from_date(frm) { if (!frm.doc.from_date || !frm.doc.payroll_frequency) frappe.msgprint(__("Please select From Date and Payroll Frequency first")); frm.call({ method: "set_withholding_cycles_and_to_date", doc: frm.doc, }).then((r) => { frm.refresh_field("to_date"); frm.refresh_field("cycles"); }); }, });
2302_79757062/hrms
hrms/payroll/doctype/salary_withholding/salary_withholding.js
JavaScript
agpl-3.0
870
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from datetime import date from dateutil.relativedelta import relativedelta import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import add_days, add_to_date, cint, get_link_to_form, getdate class SalaryWithholding(Document): def validate(self): if not self.payroll_frequency: self.payroll_frequency = get_payroll_frequency(self.employee, self.from_date) self.set_withholding_cycles_and_to_date() self.validate_duplicate_record() self.set_status() def validate_duplicate_record(self): Withholding = frappe.qb.DocType("Salary Withholding") duplicate = ( frappe.qb.from_(Withholding) .select(Withholding.name) .where( (Withholding.employee == self.employee) & (Withholding.docstatus != 2) & (Withholding.name != self.name) & (Withholding.to_date >= self.from_date) & (Withholding.from_date <= self.to_date) ) ).run(pluck=True) if duplicate: frappe.throw( _("Salary Withholding {0} already exists for employee {1} for the selected period").format( get_link_to_form("Salary Withholding", duplicate[0]), frappe.bold(f"{self.employee}: {self.employee_name}"), ), title=_("Duplicate Salary Withholding"), ) def set_status(self, update=False): if self.docstatus == 0: status = "Draft" elif self.docstatus == 1: if all(cycle.is_salary_released for cycle in self.cycles): status = "Released" else: status = "Withheld" elif self.docstatus == 2: status = "Cancelled" if update: self.db_set("status", status) else: self.status = status @frappe.whitelist() def set_withholding_cycles_and_to_date(self): self.to_date = self.get_to_date() cycle_from_date = cycle_to_date = getdate(self.from_date) self.cycles = [] while cycle_to_date < getdate(self.to_date): cycle_to_date = add_to_date(cycle_from_date, **self.get_frequency_kwargs()) - relativedelta( days=1 ) self.append( "cycles", { "from_date": cycle_from_date, "to_date": cycle_to_date, "is_salary_released": 0, }, ) cycle_from_date = add_days(cycle_to_date, 1) def get_to_date(self) -> str: from_date = getdate(self.from_date) kwargs = self.get_frequency_kwargs(self.number_of_withholding_cycles) to_date = add_to_date(from_date, **kwargs) - relativedelta(days=1) return to_date def get_frequency_kwargs(self, withholding_cycles: int = 0) -> dict: cycles = cint(withholding_cycles) or 1 frequency_dict = { "Monthly": {"months": 1 * cycles}, "Bimonthly": {"months": 2 * cycles}, "Fortnightly": {"days": 14 * cycles}, "Weekly": {"days": 7 * cycles}, "Daily": {"days": 1 * cycles}, } return frequency_dict.get(self.payroll_frequency) @frappe.whitelist() def get_payroll_frequency(employee: str, posting_date: str | date) -> str | None: salary_structure = frappe.db.get_value( "Salary Structure Assignment", { "employee": employee, "from_date": ("<=", posting_date), "docstatus": 1, }, "salary_structure", order_by="from_date desc", ) if not salary_structure: frappe.throw( _("No Salary Structure Assignment found for employee {0} on or before {1}").format( employee, posting_date ), title=_("Error"), ) return frappe.db.get_value("Salary Structure", salary_structure, "payroll_frequency") def link_bank_entry_in_salary_withholdings(salary_slips: list[dict], bank_entry: str): WithholdingCycle = frappe.qb.DocType("Salary Withholding Cycle") ( frappe.qb.update(WithholdingCycle) .set(WithholdingCycle.journal_entry, bank_entry) .where( WithholdingCycle.name.isin([salary_slip.salary_withholding_cycle for salary_slip in salary_slips]) ) ).run() def update_salary_withholding_payment_status(doc: "SalaryWithholding", method: str | None = None): """update withholding status on bank entry submission/cancellation. Called from hooks""" Withholding = frappe.qb.DocType("Salary Withholding") WithholdingCycle = frappe.qb.DocType("Salary Withholding Cycle") withholdings = ( frappe.qb.from_(WithholdingCycle) .inner_join(Withholding) .on(WithholdingCycle.parent == Withholding.name) .select( WithholdingCycle.name.as_("salary_withholding_cycle"), WithholdingCycle.parent.as_("salary_withholding"), Withholding.employee, ) .where((WithholdingCycle.journal_entry == doc.name) & (WithholdingCycle.docstatus == 1)) ).run(as_dict=True) if not withholdings: return cancel = method == "on_cancel" _update_payment_status_in_payroll(withholdings, cancel=cancel) _update_salary_withholdings(withholdings, cancel=cancel) def _update_payment_status_in_payroll(withholdings: list[dict], cancel: bool = False) -> None: status = "Withheld" if cancel else "Submitted" SalarySlip = frappe.qb.DocType("Salary Slip") ( frappe.qb.update(SalarySlip) .set(SalarySlip.status, status) .where( SalarySlip.salary_withholding_cycle.isin( [withholding.salary_withholding_cycle for withholding in withholdings] ) ) ).run() employees = [withholding.employee for withholding in withholdings] is_salary_withheld = 1 if cancel else 0 PayrollEmployee = frappe.qb.DocType("Payroll Employee Detail") ( frappe.qb.update(PayrollEmployee) .set(PayrollEmployee.is_salary_withheld, is_salary_withheld) .where(PayrollEmployee.employee.isin(employees)) ).run() def _update_salary_withholdings(withholdings: list[dict], cancel: bool = False) -> None: is_salary_released = 0 if cancel else 1 for withholding in withholdings: withholding_doc = frappe.get_doc("Salary Withholding", withholding.salary_withholding) for cycle in withholding_doc.cycles: if cycle.name == withholding.salary_withholding_cycle: cycle.db_set("is_salary_released", is_salary_released) if cancel: cycle.db_set("journal_entry", None) break withholding_doc.set_status(update=True)
2302_79757062/hrms
hrms/payroll/doctype/salary_withholding/salary_withholding.py
Python
agpl-3.0
5,985
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class SalaryWithholdingCycle(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/salary_withholding_cycle/salary_withholding_cycle.py
Python
agpl-3.0
227
# 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 TaxableSalarySlab(Document): pass
2302_79757062/hrms
hrms/payroll/doctype/taxable_salary_slab/taxable_salary_slab.py
Python
agpl-3.0
223
def get_context(context): # do your magic here pass
2302_79757062/hrms
hrms/payroll/notification/retention_bonus/retention_bonus.py
Python
agpl-3.0
54
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Bank Remittance"] = { 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", }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", }, ], };
2302_79757062/hrms
hrms/payroll/report/bank_remittance/bank_remittance.js
JavaScript
agpl-3.0
545
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _, get_all def execute(filters=None): columns = [ { "label": _("Payroll Number"), "fieldtype": "Link", "fieldname": "payroll_no", "options": "Payroll Entry", "width": 150, }, { "label": _("Debit A/C Number"), "fieldtype": "Int", "fieldname": "debit_account", "hidden": 1, "width": 200, }, { "label": _("Payment Date"), "fieldtype": "Data", "fieldname": "payment_date", "width": 100, }, { "label": _("Employee Name"), "fieldtype": "Link", "fieldname": "employee_name", "options": "Employee", "width": 200, }, {"label": _("Bank Name"), "fieldtype": "Data", "fieldname": "bank_name", "width": 50}, { "label": _("Employee A/C Number"), "fieldtype": "Int", "fieldname": "employee_account_no", "width": 50, }, ] if frappe.db.has_column("Employee", "ifsc_code"): columns.append({"label": _("IFSC Code"), "fieldtype": "Data", "fieldname": "bank_code", "width": 100}) columns += [ {"label": _("Currency"), "fieldtype": "Data", "fieldname": "currency", "width": 50}, { "label": _("Net Salary Amount"), "fieldtype": "Currency", "options": "currency", "fieldname": "amount", "width": 100, }, ] data = [] accounts = get_bank_accounts() payroll_entries = get_payroll_entries(accounts, filters) salary_slips = get_salary_slips(payroll_entries) if frappe.db.has_column("Employee", "ifsc_code"): get_emp_bank_ifsc_code(salary_slips) for salary in salary_slips: if ( salary.bank_name and salary.bank_account_no and salary.debit_acc_no and salary.status in ["Submitted", "Paid"] ): row = { "payroll_no": salary.payroll_entry, "debit_account": salary.debit_acc_no, "payment_date": frappe.utils.formatdate(salary.modified.strftime("%Y-%m-%d")), "bank_name": salary.bank_name, "employee_account_no": salary.bank_account_no, "bank_code": salary.ifsc_code, "employee_name": salary.employee + ": " + salary.employee_name, "currency": frappe.get_cached_value("Company", filters.company, "default_currency"), "amount": salary.net_pay, } data.append(row) return columns, data def get_bank_accounts(): accounts = [d.name for d in get_all("Account", filters={"account_type": "Bank"})] return accounts def get_payroll_entries(accounts, filters): payroll_filter = [ ("payment_account", "IN", accounts), ("number_of_employees", ">", 0), ("Company", "=", filters.company), ] if filters.to_date: payroll_filter.append(("posting_date", "<", filters.to_date)) if filters.from_date: payroll_filter.append(("posting_date", ">", filters.from_date)) entries = get_all("Payroll Entry", payroll_filter, ["name", "payment_account"]) payment_accounts = [d.payment_account for d in entries] entries = set_company_account(payment_accounts, entries) return entries def get_salary_slips(payroll_entries): payroll = [d.name for d in payroll_entries] salary_slips = get_all( "Salary Slip", filters=[("payroll_entry", "IN", payroll)], fields=[ "modified", "net_pay", "bank_name", "bank_account_no", "payroll_entry", "employee", "employee_name", "status", ], ) payroll_entry_map = {} for entry in payroll_entries: payroll_entry_map[entry.name] = entry # appending company debit accounts for slip in salary_slips: if slip.payroll_entry: slip["debit_acc_no"] = payroll_entry_map[slip.payroll_entry]["company_account"] else: slip["debit_acc_no"] = None return salary_slips def get_emp_bank_ifsc_code(salary_slips): emp_names = [d.employee for d in salary_slips] ifsc_codes = get_all("Employee", [("name", "IN", emp_names)], ["ifsc_code", "name"]) ifsc_codes_map = {code.name: code.ifsc_code for code in ifsc_codes} for slip in salary_slips: slip["ifsc_code"] = ifsc_codes_map[slip.employee] return salary_slips def set_company_account(payment_accounts, payroll_entries): company_accounts = get_all( "Bank Account", [("account", "in", payment_accounts)], ["account", "bank_account_no"] ) company_accounts_map = {} for acc in company_accounts: company_accounts_map[acc.account] = acc for entry in payroll_entries: company_account = "" if entry.payment_account in company_accounts_map: company_account = company_accounts_map[entry.payment_account]["bank_account_no"] entry["company_account"] = company_account return payroll_entries
2302_79757062/hrms
hrms/payroll/report/bank_remittance/bank_remittance.py
Python
agpl-3.0
4,545
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Income Tax Computation"] = { filters: [ { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), width: "100px", reqd: 1, }, { fieldname: "payroll_period", label: __("Payroll Period"), fieldtype: "Link", options: "Payroll Period", width: "100px", reqd: 1, }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", width: "100px", }, { fieldname: "department", label: __("Department"), fieldtype: "Link", options: "Department", width: "100px", }, { fieldname: "consider_tax_exemption_declaration", label: __("Consider Tax Exemption Declaration"), fieldtype: "Check", width: "180px", }, ], };
2302_79757062/hrms
hrms/payroll/report/income_tax_computation/income_tax_computation.js
JavaScript
agpl-3.0
974
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _, scrub from frappe.query_builder.functions import Sum from frappe.utils import add_days, flt, getdate, rounded from hrms.payroll.doctype.payroll_entry.payroll_entry import get_start_end_dates from hrms.payroll.doctype.salary_slip.salary_slip import calculate_tax_by_tax_slab def execute(filters=None): return IncomeTaxComputationReport(filters).run() class IncomeTaxComputationReport: def __init__(self, filters=None): self.filters = frappe._dict(filters or {}) self.columns = [] self.data = [] self.employees = frappe._dict() self.payroll_period_start_date = None self.payroll_period_end_date = None if self.filters.payroll_period: self.payroll_period_start_date, self.payroll_period_end_date = frappe.db.get_value( "Payroll Period", self.filters.payroll_period, ["start_date", "end_date"] ) def run(self): self.get_fixed_columns() self.get_data() return self.columns, self.data def get_data(self): self.get_employee_details() self.get_future_salary_slips() self.get_ctc() self.get_tax_exempted_earnings_and_deductions() self.get_employee_tax_exemptions() self.get_hra() self.get_standard_tax_exemption() self.get_total_taxable_amount() self.get_applicable_tax() self.get_total_deducted_tax() self.get_payable_tax() self.data = list(self.employees.values()) def get_employee_details(self): filters, or_filters = self.get_employee_filters() fields = [ "name as employee", "employee_name", "department", "designation", "date_of_joining", "relieving_date", ] employees = frappe.get_all("Employee", filters=filters, or_filters=or_filters, fields=fields) ss_assignments = self.get_ss_assignments([d.employee for d in employees]) for d in employees: if d.employee in list(ss_assignments.keys()): d.update(ss_assignments[d.employee]) self.employees.setdefault(d.employee, d) if not self.employees: frappe.throw(_("No employees found with selected filters and active salary structure")) def get_employee_filters(self): filters = {"company": self.filters.company} or_filters = { "status": "Active", "relieving_date": ["between", [self.payroll_period_start_date, self.payroll_period_end_date]], } if self.filters.employee: filters = {"name": self.filters.employee} elif self.filters.department: filters.update({"department": self.filters.department}) return filters, or_filters def get_ss_assignments(self, employees): ss_assignments = frappe.get_all( "Salary Structure Assignment", filters={ "employee": ["in", employees], "docstatus": 1, "salary_structure": ["is", "set"], "income_tax_slab": ["is", "set"], }, fields=["employee", "income_tax_slab", "salary_structure"], order_by="from_date desc", ) employee_ss_assignments = frappe._dict() for d in ss_assignments: if d.employee not in list(employee_ss_assignments.keys()): tax_slab = frappe.get_cached_value( "Income Tax Slab", d.income_tax_slab, ["allow_tax_exemption", "disabled"], as_dict=1 ) if tax_slab and not tax_slab.disabled: employee_ss_assignments.setdefault( d.employee, { "salary_structure": d.salary_structure, "income_tax_slab": d.income_tax_slab, "allow_tax_exemption": tax_slab.allow_tax_exemption, }, ) return employee_ss_assignments def get_future_salary_slips(self): self.future_salary_slips = frappe._dict() for employee in list(self.employees.keys()): last_ss = self.get_last_salary_slip(employee) if last_ss and last_ss.end_date == self.payroll_period_end_date: continue relieving_date = self.employees[employee].get("relieving_date", "") if last_ss: ss_start_date = add_days(last_ss.end_date, 1) else: ss_start_date = self.payroll_period_start_date last_ss = frappe._dict( { "payroll_frequency": "Monthly", "salary_structure": self.employees[employee].get("salary_structure"), } ) while getdate(ss_start_date) < getdate(self.payroll_period_end_date) and ( not relieving_date or getdate(ss_start_date) < relieving_date ): ss_end_date = get_start_end_dates(last_ss.payroll_frequency, ss_start_date).end_date ss = frappe.new_doc("Salary Slip") ss.employee = employee ss.start_date = ss_start_date ss.end_date = ss_end_date ss.salary_structure = last_ss.salary_structure ss.payroll_frequency = last_ss.payroll_frequency ss.company = self.filters.company try: ss.process_salary_structure(for_preview=1) self.future_salary_slips.setdefault(employee, []).append(ss.as_dict()) except Exception: break ss_start_date = add_days(ss_end_date, 1) def get_last_salary_slip(self, employee): last_salary_slip = frappe.db.get_value( "Salary Slip", { "employee": employee, "docstatus": 1, "start_date": ["between", [self.payroll_period_start_date, self.payroll_period_end_date]], }, ["name", "start_date", "end_date", "salary_structure", "payroll_frequency"], order_by="start_date desc", as_dict=1, ) return last_salary_slip def get_ctc(self): # Get total earnings from existing salary slip ss = frappe.qb.DocType("Salary Slip") existing_ss = frappe._dict( ( frappe.qb.from_(ss) .select(ss.employee, Sum(ss.base_gross_pay).as_("amount")) .where(ss.docstatus == 1) .where(ss.employee.isin(list(self.employees.keys()))) .where(ss.start_date >= self.payroll_period_start_date) .where(ss.end_date <= self.payroll_period_end_date) .groupby(ss.employee) ).run() ) for employee in list(self.employees.keys()): future_ss_earnings = self.get_future_earnings(employee) ctc = flt(existing_ss.get(employee)) + future_ss_earnings self.employees[employee].setdefault("ctc", ctc) def get_future_earnings(self, employee): future_earnings = 0.0 for ss in self.future_salary_slips.get(employee, []): future_earnings += flt(ss.base_gross_pay) return future_earnings def get_tax_exempted_earnings_and_deductions(self): tax_exempted_components = self.get_tax_exempted_components() if not tax_exempted_components: return # Get component totals from existing salary slips ss = frappe.qb.DocType("Salary Slip") ss_comps = frappe.qb.DocType("Salary Detail") records = ( frappe.qb.from_(ss) .inner_join(ss_comps) .on(ss.name == ss_comps.parent) .select(ss.name, ss.employee, ss_comps.salary_component, Sum(ss_comps.amount).as_("amount")) .where(ss.docstatus == 1) .where(ss.employee.isin(list(self.employees.keys()))) .where(ss_comps.salary_component.isin(tax_exempted_components)) .where(ss.start_date >= self.payroll_period_start_date) .where(ss.end_date <= self.payroll_period_end_date) .groupby(ss.employee, ss_comps.salary_component) ).run(as_dict=True) existing_ss_exemptions = frappe._dict() for d in records: existing_ss_exemptions.setdefault(d.employee, {}).setdefault(scrub(d.salary_component), d.amount) for employee in list(self.employees.keys()): if not self.employees[employee]["allow_tax_exemption"]: continue exemptions = existing_ss_exemptions.get(employee, {}) self.add_exemptions_from_future_salary_slips(employee, exemptions) self.employees[employee].update(exemptions) total_exemptions = sum(list(exemptions.values())) self.employees[employee]["total_exemption"] = 0 self.employees[employee]["total_exemption"] += total_exemptions def add_exemptions_from_future_salary_slips(self, employee, exemptions): for ss in self.future_salary_slips.get(employee, []): for e in ss.earnings: if not e.is_tax_applicable: exemptions.setdefault(scrub(e.salary_component), 0) exemptions[scrub(e.salary_component)] += flt(e.amount) for d in ss.deductions: if d.exempted_from_income_tax: exemptions.setdefault(scrub(d.salary_component), 0) exemptions[scrub(d.salary_component)] += flt(d.amount) return exemptions def get_tax_exempted_components(self): # nontaxable earning components nontaxable_earning_components = [ d.name for d in frappe.get_all( "Salary Component", {"type": "Earning", "is_tax_applicable": 0, "disabled": 0} ) ] # tax exempted deduction components tax_exempted_deduction_components = [ d.name for d in frappe.get_all( "Salary Component", {"type": "Deduction", "exempted_from_income_tax": 1, "disabled": 0} ) ] tax_exempted_components = nontaxable_earning_components + tax_exempted_deduction_components # Add columns for d in tax_exempted_components: self.add_column(d) return tax_exempted_components def get_employee_tax_exemptions(self): # add columns exemption_categories = frappe.get_all("Employee Tax Exemption Category", {"is_active": 1}) for d in exemption_categories: self.add_column(d.name) self.employees_with_proofs = [] self.get_tax_exemptions("Employee Tax Exemption Proof Submission") if self.filters.consider_tax_exemption_declaration: self.get_tax_exemptions("Employee Tax Exemption Declaration") def get_tax_exemptions(self, source): # Get category-wise exmeptions based on submitted proofs or declarations if source == "Employee Tax Exemption Proof Submission": child_doctype = "Employee Tax Exemption Proof Submission Detail" else: child_doctype = "Employee Tax Exemption Declaration Category" max_exemptions = self.get_max_exemptions_based_on_category() par = frappe.qb.DocType(source) child = frappe.qb.DocType(child_doctype) records = ( frappe.qb.from_(par) .inner_join(child) .on(par.name == child.parent) .select(par.employee, child.exemption_category, Sum(child.amount).as_("amount")) .where(par.docstatus == 1) .where(par.employee.isin(list(self.employees.keys()))) .where(par.payroll_period == self.filters.payroll_period) .groupby(par.employee, child.exemption_category) ).run(as_dict=True) for d in records: if not self.employees[d.employee]["allow_tax_exemption"]: continue if source == "Employee Tax Exemption Declaration" and d.employee in self.employees_with_proofs: continue amount = flt(d.amount) max_eligible_amount = flt(max_exemptions.get(d.exemption_category)) if max_eligible_amount and amount > max_eligible_amount: amount = max_eligible_amount self.employees[d.employee].setdefault(scrub(d.exemption_category), amount) self.employees[d.employee]["total_exemption"] += amount if ( source == "Employee Tax Exemption Proof Submission" and d.employee not in self.employees_with_proofs ): self.employees_with_proofs.append(d.employee) def get_max_exemptions_based_on_category(self): return dict( frappe.get_all( "Employee Tax Exemption Category", filters={"is_active": 1}, fields=["name", "max_amount"], as_list=1, ) ) def get_hra(self): if not frappe.get_meta("Employee Tax Exemption Declaration").has_field("monthly_house_rent"): return self.add_column("HRA") self.employees_with_proofs = [] self.get_eligible_hra("Employee Tax Exemption Proof Submission") if self.filters.consider_tax_exemption_declaration: self.get_eligible_hra("Employee Tax Exemption Declaration") def get_eligible_hra(self, source): if source == "Employee Tax Exemption Proof Submission": hra_amount_field = "total_eligible_hra_exemption" else: hra_amount_field = "annual_hra_exemption" records = frappe.get_all( source, filters={ "docstatus": 1, "employee": ["in", list(self.employees.keys())], "payroll_period": self.filters.payroll_period, }, fields=["employee", hra_amount_field], as_list=1, ) for d in records: if not self.employees[d[0]]["allow_tax_exemption"]: continue if d[0] not in self.employees_with_proofs: self.employees[d[0]].setdefault("hra", d[1]) self.employees[d[0]]["total_exemption"] += d[1] self.employees_with_proofs.append(d[0]) def get_standard_tax_exemption(self): self.add_column("Standard Tax Exemption") standard_exemptions_per_slab = dict( frappe.get_all( "Income Tax Slab", filters={"company": self.filters.company, "docstatus": 1, "disabled": 0}, fields=["name", "standard_tax_exemption_amount"], as_list=1, ) ) for emp, emp_details in self.employees.items(): if not self.employees[emp]["allow_tax_exemption"]: continue income_tax_slab = emp_details.get("income_tax_slab") standard_exemption = standard_exemptions_per_slab.get(income_tax_slab, 0) emp_details["standard_tax_exemption"] = standard_exemption self.employees[emp]["total_exemption"] += standard_exemption self.add_column("Total Exemption") def get_total_taxable_amount(self): self.add_column("Total Taxable Amount") for __, emp_details in self.employees.items(): emp_details["total_taxable_amount"] = flt(emp_details.get("ctc")) - flt( emp_details.get("total_exemption") ) def get_applicable_tax(self): self.add_column("Applicable Tax") is_tax_rounded = frappe.db.get_value( "Salary Component", {"variable_based_on_taxable_salary": 1, "disabled": 0}, "round_to_the_nearest_integer", ) for emp, emp_details in self.employees.items(): tax_slab = emp_details.get("income_tax_slab") if tax_slab: tax_slab = frappe.get_cached_doc("Income Tax Slab", tax_slab) eval_globals, eval_locals = self.get_data_for_eval(emp, emp_details) tax_amount = calculate_tax_by_tax_slab( emp_details["total_taxable_amount"], tax_slab, eval_globals=eval_globals, eval_locals=eval_locals, ) else: tax_amount = 0.0 if is_tax_rounded: tax_amount = rounded(tax_amount) emp_details["applicable_tax"] = tax_amount def get_data_for_eval(self, emp: str, emp_details: dict) -> tuple: last_ss = self.get_last_salary_slip(emp) if last_ss: salary_slip = frappe.get_cached_doc("Salary Slip", last_ss.name) else: salary_slip = frappe.new_doc("Salary Slip") salary_slip.employee = emp salary_slip.salary_structure = emp_details.salary_structure salary_slip.start_date = max(self.payroll_period_start_date, emp_details.date_of_joining) salary_slip.payroll_frequency = frappe.db.get_value( "Salary Structure", emp_details.salary_structure, "payroll_frequency" ) salary_slip.end_date = get_start_end_dates( salary_slip.payroll_frequency, salary_slip.start_date ).end_date salary_slip.process_salary_structure() eval_locals, __ = salary_slip.get_data_for_eval() return salary_slip.whitelisted_globals, eval_locals def get_total_deducted_tax(self): self.add_column("Total Tax Deducted") ss = frappe.qb.DocType("Salary Slip") ss_ded = frappe.qb.DocType("Salary Detail") records = ( frappe.qb.from_(ss) .inner_join(ss_ded) .on(ss.name == ss_ded.parent) .select(ss.employee, Sum(ss_ded.amount).as_("amount")) .where(ss.docstatus == 1) .where(ss.employee.isin(list(self.employees.keys()))) .where(ss_ded.parentfield == "deductions") .where(ss_ded.variable_based_on_taxable_salary == 1) .where(ss.start_date >= self.payroll_period_start_date) .where(ss.end_date <= self.payroll_period_end_date) .groupby(ss.employee) ).run(as_dict=True) for d in records: self.employees[d.employee].setdefault("total_tax_deducted", d.amount) def get_payable_tax(self): self.add_column("Payable Tax") for __, emp_details in self.employees.items(): emp_details["payable_tax"] = flt(emp_details.get("applicable_tax")) - flt( emp_details.get("total_tax_deducted") ) def add_column(self, label, fieldname=None, fieldtype=None, options=None, width=None): col = { "label": _(label), "fieldname": fieldname or scrub(label), "fieldtype": fieldtype or "Currency", "options": options, "width": width or "140px", } self.columns.append(col) def get_fixed_columns(self): self.columns = [ { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": "140px", }, { "label": _("Employee Name"), "fieldname": "employee_name", "fieldtype": "Data", "width": "160px", }, { "label": _("Department"), "fieldname": "department", "fieldtype": "Link", "options": "Department", "width": "140px", }, { "label": _("Designation"), "fieldname": "designation", "fieldtype": "Link", "options": "Designation", "width": "140px", }, {"label": _("Date of Joining"), "fieldname": "date_of_joining", "fieldtype": "Date"}, { "label": _("Income Tax Slab"), "fieldname": "income_tax_slab", "fieldtype": "Link", "options": "Income Tax Slab", "width": "140px", }, {"label": _("CTC"), "fieldname": "ctc", "fieldtype": "Currency", "width": "140px"}, ]
2302_79757062/hrms
hrms/payroll/report/income_tax_computation/income_tax_computation.py
Python
agpl-3.0
16,964
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Income Tax Deductions"] = $.extend( {}, hrms.salary_slip_deductions_report_filters, );
2302_79757062/hrms
hrms/payroll/report/income_tax_deductions/income_tax_deductions.js
JavaScript
agpl-3.0
254
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.query_builder.functions import Extract import erpnext Filters = frappe._dict def execute(filters: Filters = None) -> tuple: is_indian_company = erpnext.get_region(filters.get("company")) == "India" columns = get_columns(is_indian_company) data = get_data(filters, is_indian_company) return columns, data def get_columns(is_indian_company: bool) -> list[dict]: columns = [ { "label": _("Employee"), "options": "Employee", "fieldname": "employee", "fieldtype": "Link", "width": 200, }, { "label": _("Employee Name"), "fieldname": "employee_name", "fieldtype": "Data", "width": 160, }, ] if is_indian_company: columns.append( {"label": _("PAN Number"), "fieldname": "pan_number", "fieldtype": "Data", "width": 140} ) columns += [ {"label": _("Income Tax Component"), "fieldname": "it_comp", "fieldtype": "Data", "width": 170}, { "label": _("Income Tax Amount"), "fieldname": "it_amount", "fieldtype": "Currency", "options": "currency", "width": 140, }, { "label": _("Gross Pay"), "fieldname": "gross_pay", "fieldtype": "Currency", "options": "currency", "width": 140, }, {"label": _("Posting Date"), "fieldname": "posting_date", "fieldtype": "Date", "width": 140}, ] return columns def get_data(filters: Filters, is_indian_company: bool) -> list[dict]: data = [] employee_pan_dict = {} if is_indian_company: employee_pan_dict = frappe._dict( frappe.get_all("Employee", fields=["name", "pan_number"], as_list=True) ) deductions = get_income_tax_deductions(filters) for d in deductions: employee = { "employee": d.employee, "employee_name": d.employee_name, "it_comp": d.salary_component, "posting_date": d.posting_date, "it_amount": d.amount, "gross_pay": d.gross_pay, } if is_indian_company: employee["pan_number"] = employee_pan_dict.get(d.employee) data.append(employee) return data def get_income_tax_deductions(filters: Filters) -> list[dict]: component_types = frappe.get_all("Salary Component", filters={"is_income_tax_component": 1}, pluck="name") if not component_types: return [] SalarySlip = frappe.qb.DocType("Salary Slip") SalaryDetail = frappe.qb.DocType("Salary Detail") query = ( frappe.qb.from_(SalarySlip) .inner_join(SalaryDetail) .on(SalarySlip.name == SalaryDetail.parent) .select( SalarySlip.employee, SalarySlip.employee_name, SalarySlip.posting_date, SalaryDetail.salary_component, SalaryDetail.amount, SalarySlip.gross_pay, ) .where( (SalarySlip.docstatus == 1) & (SalaryDetail.parentfield == "deductions") & (SalaryDetail.parenttype == "Salary Slip") & (SalaryDetail.salary_component.isin(component_types)) ) ) for field in ["department", "branch", "company"]: if filters.get(field): query = query.where(getattr(SalarySlip, field) == filters.get(field)) if filters.get("month"): query = query.where(Extract("month", SalarySlip.start_date) == filters.month) if filters.get("year"): query = query.where(Extract("year", SalarySlip.start_date) == filters.year) return query.run(as_dict=True)
2302_79757062/hrms
hrms/payroll/report/income_tax_deductions/income_tax_deductions.py
Python
agpl-3.0
3,305
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Professional Tax Deductions"] = $.extend( {}, hrms.salary_slip_deductions_report_filters, );
2302_79757062/hrms
hrms/payroll/report/professional_tax_deductions/professional_tax_deductions.js
JavaScript
agpl-3.0
260
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from hrms.payroll.report.provident_fund_deductions.provident_fund_deductions import get_conditions def execute(filters=None): data = get_data(filters) columns = get_columns(filters) if len(data) else [] return columns, data def get_columns(filters): columns = [ { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 200, }, { "label": _("Employee Name"), "fieldname": "employee_name", "width": 160, }, {"label": _("Amount"), "fieldname": "amount", "fieldtype": "Currency", "width": 140}, ] return columns def get_data(filters): data = [] component_type_dict = frappe._dict( frappe.db.sql( """ select name, component_type from `tabSalary Component` where component_type = 'Professional Tax' """ ) ) if not len(component_type_dict): return [] conditions = get_conditions(filters) # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql entry = frappe.db.sql( """SELECT sal.employee, sal.employee_name, ded.salary_component, ded.amount FROM `tabSalary Slip` sal, `tabSalary Detail` ded WHERE sal.name = ded.parent AND ded.parentfield = 'deductions' AND ded.parenttype = 'Salary Slip' AND sal.docstatus = 1 {} AND ded.salary_component IN ({}) """.format(conditions, ", ".join(["%s"] * len(component_type_dict))), tuple(component_type_dict.keys()), as_dict=1, ) for d in entry: employee = {"employee": d.employee, "employee_name": d.employee_name, "amount": d.amount} data.append(employee) return data
2302_79757062/hrms
hrms/payroll/report/professional_tax_deductions/professional_tax_deductions.py
Python
agpl-3.0
1,708
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Provident Fund Deductions"] = $.extend( {}, hrms.salary_slip_deductions_report_filters, );
2302_79757062/hrms
hrms/payroll/report/provident_fund_deductions/provident_fund_deductions.js
JavaScript
agpl-3.0
258
# 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 getdate def execute(filters=None): data = get_data(filters) columns = get_columns(filters) if len(data) else [] return columns, data def get_columns(filters): columns = [ { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 200, }, { "label": _("Employee Name"), "fieldname": "employee_name", "width": 160, }, {"label": _("PF Account"), "fieldname": "pf_account", "fieldtype": "Data", "width": 140}, {"label": _("PF Amount"), "fieldname": "pf_amount", "fieldtype": "Currency", "width": 140}, { "label": _("Additional PF"), "fieldname": "additional_pf", "fieldtype": "Currency", "width": 140, }, {"label": _("PF Loan"), "fieldname": "pf_loan", "fieldtype": "Currency", "width": 140}, {"label": _("Total"), "fieldname": "total", "fieldtype": "Currency", "width": 140}, ] return columns def get_conditions(filters): conditions = [""] if filters.get("department"): conditions.append("sal.department = '%s' " % (filters["department"])) if filters.get("branch"): conditions.append("sal.branch = '%s' " % (filters["branch"])) if filters.get("company"): conditions.append("sal.company = '%s' " % (filters["company"])) if filters.get("month"): conditions.append("month(sal.start_date) = '%s' " % (filters["month"])) if filters.get("year"): conditions.append("year(start_date) = '%s' " % (filters["year"])) if filters.get("mode_of_payment"): conditions.append("sal.mode_of_payment = '%s' " % (filters["mode_of_payment"])) return " and ".join(conditions) def prepare_data(entry, component_type_dict): data_list = {} employee_account_dict = frappe._dict( frappe.db.sql(""" select name, provident_fund_account from `tabEmployee`""") ) for d in entry: component_type = component_type_dict.get(d.salary_component) if data_list.get(d.name): data_list[d.name][component_type] = d.amount else: data_list.setdefault( d.name, { "employee": d.employee, "employee_name": d.employee_name, "pf_account": employee_account_dict.get(d.employee), component_type: d.amount, }, ) return data_list def get_data(filters): data = [] conditions = get_conditions(filters) salary_slips = frappe.db.sql( """ select sal.name from `tabSalary Slip` sal where docstatus = 1 %s """ % (conditions), as_dict=1, ) component_type_dict = frappe._dict( frappe.db.sql( """ select name, component_type from `tabSalary Component` where component_type in ('Provident Fund', 'Additional Provident Fund', 'Provident Fund Loan')""" ) ) if not len(component_type_dict): return [] # nosemgrep: frappe-semgrep-rules.rules.frappe-using-db-sql entry = frappe.db.sql( """ select sal.name, sal.employee, sal.employee_name, ded.salary_component, ded.amount from `tabSalary Slip` sal, `tabSalary Detail` ded where sal.name = ded.parent and ded.parentfield = 'deductions' and ded.parenttype = 'Salary Slip' and sal.docstatus = 1 {} and ded.salary_component in ({}) """.format(conditions, ", ".join(["%s"] * len(component_type_dict.keys()))), tuple(component_type_dict.keys()), as_dict=1, ) data_list = prepare_data(entry, component_type_dict) for d in salary_slips: total = 0 if data_list.get(d.name): employee = { "employee": data_list.get(d.name).get("employee"), "employee_name": data_list.get(d.name).get("employee_name"), "pf_account": data_list.get(d.name).get("pf_account"), } if data_list.get(d.name).get("Provident Fund"): employee["pf_amount"] = data_list.get(d.name).get("Provident Fund") total += data_list.get(d.name).get("Provident Fund") if data_list.get(d.name).get("Additional Provident Fund"): employee["additional_pf"] = data_list.get(d.name).get("Additional Provident Fund") total += data_list.get(d.name).get("Additional Provident Fund") if data_list.get(d.name).get("Provident Fund Loan"): employee["pf_loan"] = data_list.get(d.name).get("Provident Fund Loan") total += data_list.get(d.name).get("Provident Fund Loan") employee["total"] = total data.append(employee) return data @frappe.whitelist() def get_years(): year_list = frappe.db.sql_list( """select distinct YEAR(end_date) from `tabSalary Slip` ORDER BY YEAR(end_date) DESC""" ) if not year_list: year_list = [getdate().year] return "\n".join(str(year) for year in year_list)
2302_79757062/hrms
hrms/payroll/report/provident_fund_deductions/provident_fund_deductions.py
Python
agpl-3.0
4,622
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Salary Payments Based On Payment Mode"] = $.extend( {}, hrms.salary_slip_deductions_report_filters, { formatter: function (value, row, column, data, default_formatter) { value = default_formatter(value, row, column, data); if (data.branch && data.branch.includes("Total") && column.colIndex === 1) { value = value.bold(); } return value; }, }, );
2302_79757062/hrms
hrms/payroll/report/salary_payments_based_on_payment_mode/salary_payments_based_on_payment_mode.js
JavaScript
agpl-3.0
536
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ import erpnext from hrms.payroll.report.provident_fund_deductions.provident_fund_deductions import get_conditions def execute(filters=None): mode_of_payments = get_payment_modes() if not len(mode_of_payments): return [], [] columns = get_columns(filters, mode_of_payments) data, total_rows, report_summary = get_data(filters, mode_of_payments) chart = get_chart(mode_of_payments, total_rows) return columns, data, None, chart, report_summary def get_columns(filters, mode_of_payments): columns = [ { "label": _("Branch"), "options": "Branch", "fieldname": "branch", "fieldtype": "Link", "width": 200, } ] for mode in mode_of_payments: columns.append({"label": _(mode), "fieldname": mode, "fieldtype": "Currency", "width": 160}) columns.append({"label": _("Total"), "fieldname": "total", "fieldtype": "Currency", "width": 140}) return columns def get_payment_modes(): mode_of_payments = frappe.db.sql_list( """ select distinct mode_of_payment from `tabSalary Slip` where docstatus = 1 """ ) return mode_of_payments def prepare_data(entry): branch_wise_entries = {} gross_pay = 0 for d in entry: gross_pay += d.gross_pay if branch_wise_entries.get(d.branch): branch_wise_entries[d.branch][d.mode_of_payment] = d.net_pay else: branch_wise_entries.setdefault(d.branch, {}).setdefault(d.mode_of_payment, d.net_pay) return branch_wise_entries, gross_pay def get_data(filters, mode_of_payments): data = [] conditions = get_conditions(filters) entry = frappe.db.sql( """ select branch, mode_of_payment, sum(net_pay) as net_pay, sum(gross_pay) as gross_pay from `tabSalary Slip` sal where docstatus = 1 %s group by branch, mode_of_payment """ % (conditions), as_dict=1, ) branch_wise_entries, gross_pay = prepare_data(entry) branches = frappe.db.sql_list( """ select distinct branch from `tabSalary Slip` sal where docstatus = 1 %s """ % (conditions) ) total_row = {"total": 0, "branch": "Total"} for branch in branches: total = 0 row = {"branch": branch} for mode in mode_of_payments: if branch_wise_entries.get(branch).get(mode): row[mode] = branch_wise_entries.get(branch).get(mode) total += branch_wise_entries.get(branch).get(mode) row["total"] = total data.append(row) total_row = get_total_based_on_mode_of_payment(data, mode_of_payments) total_deductions = gross_pay - total_row.get("total") report_summary = [] if data: data.append(total_row) data.append({}) data.append({"branch": "Total Gross Pay", mode_of_payments[0]: gross_pay}) data.append({"branch": "Total Deductions", mode_of_payments[0]: total_deductions}) data.append({"branch": "Total Net Pay", mode_of_payments[0]: total_row.get("total")}) currency = erpnext.get_company_currency(filters.company) report_summary = get_report_summary(gross_pay, total_deductions, total_row.get("total"), currency) return data, total_row, report_summary def get_total_based_on_mode_of_payment(data, mode_of_payments): total = 0 total_row = {"branch": "Total"} for mode in mode_of_payments: sum_of_payment = sum([detail[mode] for detail in data if mode in detail.keys()]) total_row[mode] = sum_of_payment total += sum_of_payment total_row["total"] = total return total_row def get_report_summary(gross_pay, total_deductions, net_pay, currency): return [ { "value": gross_pay, "label": _("Total Gross Pay"), "indicator": "Green", "datatype": "Currency", "currency": currency, }, { "value": total_deductions, "label": _("Total Deduction"), "datatype": "Currency", "indicator": "Red", "currency": currency, }, { "value": net_pay, "label": _("Total Net Pay"), "datatype": "Currency", "indicator": "Blue", "currency": currency, }, ] def get_chart(mode_of_payments, data): if data: values = [] labels = [] for mode in mode_of_payments: values.append(data[mode]) labels.append([mode]) chart = {"data": {"labels": labels, "datasets": [{"name": "Mode Of Payments", "values": values}]}} chart["type"] = "bar" return chart
2302_79757062/hrms
hrms/payroll/report/salary_payments_based_on_payment_mode/salary_payments_based_on_payment_mode.py
Python
agpl-3.0
4,273
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Salary Payments via ECS"] = $.extend( {}, hrms.salary_slip_deductions_report_filters, ); frappe.query_reports["Salary Payments via ECS"]["filters"].push({ fieldname: "type", label: __("Type"), fieldtype: "Select", options: ["", "Bank", "Cash", "Cheque"], });
2302_79757062/hrms
hrms/payroll/report/salary_payments_via_ecs/salary_payments_via_ecs.js
JavaScript
agpl-3.0
431
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ import erpnext def execute(filters=None): columns = get_columns(filters) data = get_data(filters) return columns, data def get_columns(filters): columns = [ { "label": _("Branch"), "options": "Branch", "fieldname": "branch", "fieldtype": "Link", "width": 200, }, { "label": _("Employee Name"), "options": "Employee", "fieldname": "employee_name", "fieldtype": "Link", "width": 160, }, { "label": _("Employee"), "options": "Employee", "fieldname": "employee", "fieldtype": "Link", "width": 140, }, { "label": _("Gross Pay"), "fieldname": "gross_pay", "fieldtype": "Currency", "options": "currency", "width": 140, }, { "label": _("Net Pay"), "fieldname": "net_pay", "fieldtype": "Currency", "options": "currency", "width": 140, }, {"label": _("Bank"), "fieldname": "bank", "fieldtype": "Data", "width": 140}, {"label": _("Account No"), "fieldname": "account_no", "fieldtype": "Data", "width": 140}, ] if erpnext.get_region() == "India": columns += [ {"label": _("IFSC"), "fieldname": "ifsc", "fieldtype": "Data", "width": 140}, {"label": _("MICR"), "fieldname": "micr", "fieldtype": "Data", "width": 140}, ] return columns def get_conditions(filters): conditions = [""] if filters.get("department"): conditions.append("department = '%s' " % (filters["department"])) if filters.get("branch"): conditions.append("branch = '%s' " % (filters["branch"])) if filters.get("company"): conditions.append("company = '%s' " % (filters["company"])) if filters.get("month"): conditions.append("month(start_date) = '%s' " % (filters["month"])) if filters.get("year"): conditions.append("year(start_date) = '%s' " % (filters["year"])) return " and ".join(conditions) def get_data(filters): data = [] fields = ["employee", "branch", "bank_name", "bank_ac_no", "salary_mode"] if erpnext.get_region() == "India": fields += ["ifsc_code", "micr_code"] employee_details = frappe.get_list("Employee", fields=fields) employee_data_dict = {} for d in employee_details: employee_data_dict.setdefault( d.employee, { "bank_ac_no": d.bank_ac_no, "ifsc_code": d.ifsc_code or None, "micr_code": d.micr_code or None, "branch": d.branch, "salary_mode": d.salary_mode, "bank_name": d.bank_name, }, ) conditions = get_conditions(filters) entry = frappe.db.sql( """ select employee, employee_name, gross_pay, net_pay from `tabSalary Slip` where docstatus = 1 %s """ % (conditions), as_dict=1, ) for d in entry: employee = { "branch": employee_data_dict.get(d.employee).get("branch"), "employee_name": d.employee_name, "employee": d.employee, "gross_pay": d.gross_pay, "net_pay": d.net_pay, } if employee_data_dict.get(d.employee).get("salary_mode") == "Bank": employee["bank"] = employee_data_dict.get(d.employee).get("bank_name") employee["account_no"] = employee_data_dict.get(d.employee).get("bank_ac_no") if erpnext.get_region() == "India": employee["ifsc"] = employee_data_dict.get(d.employee).get("ifsc_code") employee["micr"] = employee_data_dict.get(d.employee).get("micr_code") else: employee["account_no"] = employee_data_dict.get(d.employee).get("salary_mode") if filters.get("type") and employee_data_dict.get(d.employee).get("salary_mode") == filters.get( "type" ): data.append(employee) elif not filters.get("type"): data.append(employee) return data
2302_79757062/hrms
hrms/payroll/report/salary_payments_via_ecs/salary_payments_via_ecs.py
Python
agpl-3.0
3,661
{% var report_columns = report.get_columns_for_print(); %} <div style="margin-bottom: 7px;" class="text-center"> {%= frappe.boot.letter_heads[filters.letter_head || frappe.defaults.get_default("letter_head")].header %} </div> <h2 class="text-center">{%= __(report.report_name) %}</h2> <h5 class="text-center">{{ __("From") }} {%= filters.from_date %} {{ __("to") }} {%= filters.to_date %}</h5> <hr> <table class="table table-bordered"> <thead> <tr> {% for(var i=1, l=report_columns.length; i<l; i++) { %} <th class="text-right">{%= report_columns[i].label %}</th> {% } %} </tr> </thead> <tbody> {% for(var j=0, k=data.length; j<k; j++) { %} {% var row = data[j]; %} <tr> {% for(var i=1, l=report_columns.length; i<l; i++) { %} <td class="text-right"> {% var fieldname = report_columns[i].fieldname; %} {% if (report_columns[i].fieldtype=='Currency' && !isNaN(row[fieldname])) { %} {%= format_currency(row[fieldname]) %} {% } else { %} {% if (!is_null(row[fieldname])) { %} {%= row[fieldname] %} {% } %} {% } %} </td> {% } %} </tr> {% } %} </tbody> </table> <p class="text-right text-muted">{{ __("Printed On") }} {%= frappe.datetime.str_to_user(frappe.datetime.get_datetime_as_string()) %}</p>
2302_79757062/hrms
hrms/payroll/report/salary_register/salary_register.html
HTML
agpl-3.0
1,305
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.query_reports["Salary Register"] = { filters: [ { fieldname: "from_date", label: __("From"), fieldtype: "Date", default: frappe.datetime.add_months(frappe.datetime.get_today(), -1), reqd: 1, width: "100px", }, { fieldname: "to_date", label: __("To"), fieldtype: "Date", default: frappe.datetime.get_today(), reqd: 1, width: "100px", }, { fieldname: "currency", fieldtype: "Link", options: "Currency", label: __("Currency"), default: erpnext.get_currency(frappe.defaults.get_default("Company")), width: "50px", }, { fieldname: "employee", label: __("Employee"), fieldtype: "Link", options: "Employee", width: "100px", }, { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", default: frappe.defaults.get_user_default("Company"), width: "100px", reqd: 1, }, { fieldname: "docstatus", label: __("Document Status"), fieldtype: "Select", options: ["Draft", "Submitted", "Cancelled"], default: "Submitted", width: "100px", }, ], };
2302_79757062/hrms
hrms/payroll/report/salary_register/salary_register.js
JavaScript
agpl-3.0
1,220
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ from frappe.utils import flt import erpnext salary_slip = frappe.qb.DocType("Salary Slip") salary_detail = frappe.qb.DocType("Salary Detail") salary_component = frappe.qb.DocType("Salary Component") def execute(filters=None): if not filters: filters = {} currency = None if filters.get("currency"): currency = filters.get("currency") company_currency = erpnext.get_company_currency(filters.get("company")) salary_slips = get_salary_slips(filters, company_currency) if not salary_slips: return [], [] earning_types, ded_types = get_earning_and_deduction_types(salary_slips) columns = get_columns(earning_types, ded_types) ss_earning_map = get_salary_slip_details(salary_slips, currency, company_currency, "earnings") ss_ded_map = get_salary_slip_details(salary_slips, currency, company_currency, "deductions") doj_map = get_employee_doj_map() data = [] for ss in salary_slips: row = { "salary_slip_id": ss.name, "employee": ss.employee, "employee_name": ss.employee_name, "data_of_joining": doj_map.get(ss.employee), "branch": ss.branch, "department": ss.department, "designation": ss.designation, "company": ss.company, "start_date": ss.start_date, "end_date": ss.end_date, "leave_without_pay": ss.leave_without_pay, "payment_days": ss.payment_days, "currency": currency or company_currency, "total_loan_repayment": ss.total_loan_repayment, } update_column_width(ss, columns) for e in earning_types: row.update({frappe.scrub(e): ss_earning_map.get(ss.name, {}).get(e)}) for d in ded_types: row.update({frappe.scrub(d): ss_ded_map.get(ss.name, {}).get(d)}) if currency == company_currency: row.update( { "gross_pay": flt(ss.gross_pay) * flt(ss.exchange_rate), "total_deduction": flt(ss.total_deduction) * flt(ss.exchange_rate), "net_pay": flt(ss.net_pay) * flt(ss.exchange_rate), } ) else: row.update( {"gross_pay": ss.gross_pay, "total_deduction": ss.total_deduction, "net_pay": ss.net_pay} ) data.append(row) return columns, data def get_earning_and_deduction_types(salary_slips): salary_component_and_type = {_("Earning"): [], _("Deduction"): []} for salary_compoent in get_salary_components(salary_slips): component_type = get_salary_component_type(salary_compoent) salary_component_and_type[_(component_type)].append(salary_compoent) return sorted(salary_component_and_type[_("Earning")]), sorted(salary_component_and_type[_("Deduction")]) def update_column_width(ss, columns): if ss.branch is not None: columns[3].update({"width": 120}) if ss.department is not None: columns[4].update({"width": 120}) if ss.designation is not None: columns[5].update({"width": 120}) if ss.leave_without_pay is not None: columns[9].update({"width": 120}) def get_columns(earning_types, ded_types): columns = [ { "label": _("Salary Slip ID"), "fieldname": "salary_slip_id", "fieldtype": "Link", "options": "Salary Slip", "width": 150, }, { "label": _("Employee"), "fieldname": "employee", "fieldtype": "Link", "options": "Employee", "width": 120, }, { "label": _("Employee Name"), "fieldname": "employee_name", "fieldtype": "Data", "width": 140, }, { "label": _("Date of Joining"), "fieldname": "data_of_joining", "fieldtype": "Date", "width": 80, }, { "label": _("Branch"), "fieldname": "branch", "fieldtype": "Link", "options": "Branch", "width": -1, }, { "label": _("Department"), "fieldname": "department", "fieldtype": "Link", "options": "Department", "width": -1, }, { "label": _("Designation"), "fieldname": "designation", "fieldtype": "Link", "options": "Designation", "width": 120, }, { "label": _("Company"), "fieldname": "company", "fieldtype": "Link", "options": "Company", "width": 120, }, { "label": _("Start Date"), "fieldname": "start_date", "fieldtype": "Data", "width": 80, }, { "label": _("End Date"), "fieldname": "end_date", "fieldtype": "Data", "width": 80, }, { "label": _("Leave Without Pay"), "fieldname": "leave_without_pay", "fieldtype": "Float", "width": 50, }, { "label": _("Payment Days"), "fieldname": "payment_days", "fieldtype": "Float", "width": 120, }, ] for earning in earning_types: columns.append( { "label": earning, "fieldname": frappe.scrub(earning), "fieldtype": "Currency", "options": "currency", "width": 120, } ) columns.append( { "label": _("Gross Pay"), "fieldname": "gross_pay", "fieldtype": "Currency", "options": "currency", "width": 120, } ) for deduction in ded_types: columns.append( { "label": deduction, "fieldname": frappe.scrub(deduction), "fieldtype": "Currency", "options": "currency", "width": 120, } ) columns.extend( [ { "label": _("Loan Repayment"), "fieldname": "total_loan_repayment", "fieldtype": "Currency", "options": "currency", "width": 120, }, { "label": _("Total Deduction"), "fieldname": "total_deduction", "fieldtype": "Currency", "options": "currency", "width": 120, }, { "label": _("Net Pay"), "fieldname": "net_pay", "fieldtype": "Currency", "options": "currency", "width": 120, }, { "label": _("Currency"), "fieldtype": "Data", "fieldname": "currency", "options": "Currency", "hidden": 1, }, ] ) return columns def get_salary_components(salary_slips): return ( frappe.qb.from_(salary_detail) .where((salary_detail.amount != 0) & (salary_detail.parent.isin([d.name for d in salary_slips]))) .select(salary_detail.salary_component) .distinct() ).run(pluck=True) def get_salary_component_type(salary_component): return frappe.db.get_value("Salary Component", salary_component, "type", cache=True) def get_salary_slips(filters, company_currency): doc_status = {"Draft": 0, "Submitted": 1, "Cancelled": 2} query = frappe.qb.from_(salary_slip).select(salary_slip.star) if filters.get("docstatus"): query = query.where(salary_slip.docstatus == doc_status[filters.get("docstatus")]) if filters.get("from_date"): query = query.where(salary_slip.start_date >= filters.get("from_date")) if filters.get("to_date"): query = query.where(salary_slip.end_date <= filters.get("to_date")) if filters.get("company"): query = query.where(salary_slip.company == filters.get("company")) if filters.get("employee"): query = query.where(salary_slip.employee == filters.get("employee")) if filters.get("currency") and filters.get("currency") != company_currency: query = query.where(salary_slip.currency == filters.get("currency")) salary_slips = query.run(as_dict=1) return salary_slips or [] def get_employee_doj_map(): employee = frappe.qb.DocType("Employee") result = (frappe.qb.from_(employee).select(employee.name, employee.date_of_joining)).run() return frappe._dict(result) def get_salary_slip_details(salary_slips, currency, company_currency, component_type): salary_slips = [ss.name for ss in salary_slips] result = ( frappe.qb.from_(salary_slip) .join(salary_detail) .on(salary_slip.name == salary_detail.parent) .where((salary_detail.parent.isin(salary_slips)) & (salary_detail.parentfield == component_type)) .select( salary_detail.parent, salary_detail.salary_component, salary_detail.amount, salary_slip.exchange_rate, ) ).run(as_dict=1) ss_map = {} for d in result: ss_map.setdefault(d.parent, frappe._dict()).setdefault(d.salary_component, 0.0) if currency == company_currency: ss_map[d.parent][d.salary_component] += flt(d.amount) * flt( d.exchange_rate if d.exchange_rate else 1 ) else: ss_map[d.parent][d.salary_component] += flt(d.amount) return ss_map
2302_79757062/hrms
hrms/payroll/report/salary_register/salary_register.py
Python
agpl-3.0
8,064
import frappe def sanitize_expression(string: str | None = None) -> str | None: """ Removes leading and trailing whitespace and merges multiline strings into a single line. Args: string (str, None): The string expression to be sanitized. Defaults to None. Returns: str or None: The sanitized string expression or None if the input string is None. Example: expression = "\r\n gross_pay > 10000\n " sanitized_expr = sanitize_expression(expression) """ if not string: return None parts = string.strip().splitlines() string = " ".join(parts) return string @frappe.whitelist() def get_payroll_settings_for_payment_days() -> dict: return frappe.get_cached_value( "Payroll Settings", None, [ "payroll_based_on", "consider_unmarked_attendance_as", "include_holidays_in_total_working_days", "consider_marked_attendance_on_holidays", ], as_dict=True, )
2302_79757062/hrms
hrms/payroll/utils.py
Python
agpl-3.0
916
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Bank Transaction", { get_payment_doctypes: function () { return [ "Payment Entry", "Journal Entry", "Sales Invoice", "Purchase Invoice", "Expense Claim", ]; }, });
2302_79757062/hrms
hrms/public/js/erpnext/bank_transaction.js
JavaScript
agpl-3.0
326
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Company", { refresh: function (frm) { frm.set_query("default_expense_claim_payable_account", function () { return { filters: { company: frm.doc.name, is_group: 0, }, }; }); frm.set_query("default_employee_advance_account", function () { return { filters: { company: frm.doc.name, is_group: 0, root_type: "Asset", }, }; }); frm.set_query("default_payroll_payable_account", function () { return { filters: { company: frm.doc.name, is_group: 0, root_type: "Liability", }, }; }); frm.set_query("hra_component", function () { return { filters: { type: "Earning" }, }; }); }, });
2302_79757062/hrms
hrms/public/js/erpnext/company.js
JavaScript
agpl-3.0
828
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Delivery Trip", { refresh: function (frm) { if (frm.doc.docstatus === 1 && frm.doc.employee) { frm.add_custom_button( __("Expense Claim"), function () { frappe.model.open_mapped_doc({ method: "hrms.hr.doctype.expense_claim.expense_claim.make_expense_claim_for_delivery_trip", frm: frm, }); }, __("Create"), ); } }, });
2302_79757062/hrms
hrms/public/js/erpnext/delivery_trip.js
JavaScript
agpl-3.0
510
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Department", { refresh: function (frm) { frm.set_query("payroll_cost_center", function () { return { filters: { company: frm.doc.company, is_group: 0, }, }; }); }, });
2302_79757062/hrms
hrms/public/js/erpnext/department.js
JavaScript
agpl-3.0
339
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Employee", { refresh: function (frm) { frm.set_query("payroll_cost_center", function () { return { filters: { company: frm.doc.company, is_group: 0, }, }; }); }, date_of_birth(frm) { frm.call({ method: "hrms.overrides.employee_master.get_retirement_date", args: { date_of_birth: frm.doc.date_of_birth, }, }).then((r) => { if (r && r.message) frm.set_value("date_of_retirement", r.message); }); }, });
2302_79757062/hrms
hrms/public/js/erpnext/employee.js
JavaScript
agpl-3.0
597
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Journal Entry", { setup(frm) { frm.ignore_doctypes_on_cancel_all.push("Salary Withholding"); if (frm.doc.voucher_type === "Bank Entry") { // since salary withholding is linked to salary slip, nested links are also pulled for cancellation frm.ignore_doctypes_on_cancel_all.push("Salary Slip"); } }, refresh(frm) { frm.set_query("reference_name", "accounts", function (frm, cdt, cdn) { let jvd = frappe.get_doc(cdt, cdn); // filters for hrms doctypes if (jvd.reference_type === "Expense Claim") { return { filters: { total_sanctioned_amount: [">", 0], status: ["!=", "Paid"], docstatus: 1, }, }; } if (jvd.reference_type === "Employee Advance") { return { filters: { docstatus: 1, }, }; } if (jvd.reference_type === "Payroll Entry") { return { query: "hrms.payroll.doctype.payroll_entry.payroll_entry.get_payroll_entries_for_jv", }; } // filters for erpnext doctypes if (jvd.reference_type === "Journal Entry") { frappe.model.validate_missing(jvd, "account"); return { query: "erpnext.accounts.doctype.journal_entry.journal_entry.get_against_jv", filters: { account: jvd.account, party: jvd.party, }, }; } const out = { filters: [[jvd.reference_type, "docstatus", "=", 1]], }; if (["Sales Invoice", "Purchase Invoice"].includes(jvd.reference_type)) { out.filters.push([jvd.reference_type, "outstanding_amount", "!=", 0]); // Filter by cost center if (jvd.cost_center) { out.filters.push([ jvd.reference_type, "cost_center", "in", ["", jvd.cost_center], ]); } // account filter frappe.model.validate_missing(jvd, "account"); const party_account_field = jvd.reference_type === "Sales Invoice" ? "debit_to" : "credit_to"; out.filters.push([jvd.reference_type, party_account_field, "=", jvd.account]); } if (["Sales Order", "Purchase Order"].includes(jvd.reference_type)) { // party_type and party mandatory frappe.model.validate_missing(jvd, "party_type"); frappe.model.validate_missing(jvd, "party"); out.filters.push([jvd.reference_type, "per_billed", "<", 100]); } if (jvd.party_type && jvd.party) { let party_field = ""; if (jvd.reference_type.indexOf("Sales") === 0) { party_field = "customer"; } else if (jvd.reference_type.indexOf("Purchase") === 0) { party_field = "supplier"; } if (party_field) { out.filters.push([jvd.reference_type, party_field, "=", jvd.party]); } } return out; }); }, });
2302_79757062/hrms
hrms/public/js/erpnext/journal_entry.js
JavaScript
agpl-3.0
2,772
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Payment Entry", { refresh: function (frm) { frm.set_query("reference_doctype", "references", function () { let doctypes = []; if (frm.doc.party_type == "Customer") { doctypes = ["Sales Order", "Sales Invoice", "Journal Entry", "Dunning"]; } else if (frm.doc.party_type == "Supplier") { doctypes = ["Purchase Order", "Purchase Invoice", "Journal Entry"]; } else if (frm.doc.party_type == "Employee") { doctypes = ["Expense Claim", "Employee Advance", "Journal Entry"]; } else { doctypes = ["Journal Entry"]; } return { filters: { name: ["in", doctypes] }, }; }); frm.set_query("reference_name", "references", function (doc, cdt, cdn) { const child = locals[cdt][cdn]; const filters = { docstatus: 1, company: doc.company }; const party_type_doctypes = [ "Sales Invoice", "Sales Order", "Purchase Invoice", "Purchase Order", "Expense Claim", "Dunning", ]; if (in_list(party_type_doctypes, child.reference_doctype)) { filters[doc.party_type.toLowerCase()] = doc.party; } if (child.reference_doctype == "Expense Claim") { filters["is_paid"] = 0; } if (child.reference_doctype == "Employee Advance") { filters["status"] = "Unpaid"; } return { filters: filters, }; }); }, get_order_doctypes: function (frm) { return ["Sales Order", "Purchase Order", "Expense Claim"]; }, get_invoice_doctypes: function (frm) { return ["Sales Invoice", "Purchase Invoice", "Expense Claim"]; }, }); frappe.ui.form.on("Payment Entry Reference", { reference_name: function (frm, cdt, cdn) { let row = locals[cdt][cdn]; if (row.reference_name && row.reference_doctype) { return frappe.call({ method: "hrms.overrides.employee_payment_entry.get_payment_reference_details", args: { reference_doctype: row.reference_doctype, reference_name: row.reference_name, party_account_currency: frm.doc.payment_type == "Receive" ? frm.doc.paid_from_account_currency : frm.doc.paid_to_account_currency, party_type: frm.doc.party_type, party: frm.doc.party, }, callback: function (r, rt) { if (r.message) { $.each(r.message, function (field, value) { frappe.model.set_value(cdt, cdn, field, value); }); let allocated_amount = frm.doc.unallocated_amount > row.outstanding_amount ? row.outstanding_amount : frm.doc.unallocated_amount; frappe.model.set_value(cdt, cdn, "allocated_amount", allocated_amount); frm.refresh_fields(); } }, }); } }, });
2302_79757062/hrms
hrms/public/js/erpnext/payment_entry.js
JavaScript
agpl-3.0
2,742
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on("Timesheet", { refresh(frm) { if (frm.doc.docstatus === 1 && frappe.model.can_create("Salary Slip")) { if (!frm.doc.salary_slip && frm.doc.employee) { frm.add_custom_button(__("Create Salary Slip"), function () { frm.trigger("make_salary_slip"); }); } } }, make_salary_slip: function (frm) { frappe.model.open_mapped_doc({ method: "hrms.payroll.doctype.salary_slip.salary_slip.make_salary_slip_from_timesheet", frm: frm, }); }, });
2302_79757062/hrms
hrms/public/js/erpnext/timesheet.js
JavaScript
agpl-3.0
610
import "./hierarchy_chart/hierarchy_chart_desktop.js"; import "./hierarchy_chart/hierarchy_chart_mobile.js"; import "./templates/node_card.html";
2302_79757062/hrms
hrms/public/js/hierarchy-chart.bundle.js
JavaScript
agpl-3.0
146
import html2canvas from "html2canvas"; hrms.HierarchyChart = class { /* Options: - doctype - wrapper: wrapper for the hierarchy view - method: - to get the data for each node - this method should return id, name, title, image, and connections for each node */ constructor(doctype, wrapper, method) { this.page = wrapper.page; this.method = method; this.doctype = doctype; this.setup_page_style(); this.page.main.addClass("frappe-card"); this.nodes = {}; this.setup_node_class(); } setup_page_style() { this.page.main.css({ "min-height": "300px", "max-height": "600px", overflow: "auto", position: "relative", }); } setup_node_class() { let me = this; this.Node = class { constructor({ id, parent, parent_id, image, name, title, expandable, connections, is_root, // eslint-disable-line }) { // to setup values passed via constructor $.extend(this, arguments[0]); this.expanded = 0; me.nodes[this.id] = this; me.make_node_element(this); if (!me.all_nodes_expanded) { me.setup_node_click_action(this); } me.setup_edit_node_action(this); } }; } make_node_element(node) { let node_card = frappe.render_template("node_card", { id: node.id, name: node.name, title: node.title, image: node.image, parent: node.parent_id, connections: node.connections, is_mobile: false, }); node.parent.append(node_card); node.$link = $(`[id="${node.id}"]`); } show() { this.setup_actions(); if (this.page.main.find('[data-fieldname="company"]').length) return; let me = this; let company = this.page.add_field({ fieldtype: "Link", options: "Company", fieldname: "company", placeholder: __("Select Company"), default: frappe.defaults.get_default("company"), only_select: true, reqd: 1, change: () => { me.company = ""; $("#hierarchy-chart-wrapper").remove(); if (company.get_value()) { me.company = company.get_value(); // svg for connectors me.make_svg_markers(); me.setup_hierarchy(); me.render_root_nodes(); me.all_nodes_expanded = false; } else { frappe.throw(__("Please select a company first.")); } }, }); company.refresh(); $(`[data-fieldname="company"]`).trigger("change"); $(`[data-fieldname="company"] .link-field`).css("z-index", 2); } setup_actions() { let me = this; this.page.clear_inner_toolbar(); this.page.add_inner_button(__("Export"), function () { me.export_chart(); }); this.page.add_inner_button(__("Expand All"), function () { me.load_children(me.root_node, true); me.all_nodes_expanded = true; me.page.remove_inner_button(__("Expand All")); me.page.add_inner_button(__("Collapse All"), function () { me.setup_hierarchy(); me.render_root_nodes(); me.all_nodes_expanded = false; me.page.remove_inner_button(__("Collapse All")); me.setup_actions(); }); }); } export_chart() { frappe.dom.freeze(__("Exporting...")); this.page.main.css({ "min-height": "", "max-height": "", overflow: "visible", position: "fixed", left: "0", top: "0", }); $(".node-card").addClass("exported"); html2canvas(document.querySelector("#hierarchy-chart-wrapper"), { scrollY: -window.scrollY, scrollX: 0, }) .then(function (canvas) { // Export the canvas to its data URI representation let dataURL = canvas.toDataURL("image/png"); // download the image let a = document.createElement("a"); a.href = dataURL; a.download = "hierarchy_chart"; a.click(); }) .finally(() => { frappe.dom.unfreeze(); }); this.setup_page_style(); $(".node-card").removeClass("exported"); } setup_hierarchy() { if (this.$hierarchy) this.$hierarchy.remove(); $(`#connectors`).empty(); // setup hierarchy this.$hierarchy = $( `<ul class="hierarchy"> <li class="root-level level"> <ul class="node-children"></ul> </li> </ul>`, ); this.page.main.find("#hierarchy-chart").empty().append(this.$hierarchy); this.nodes = {}; } make_svg_markers() { $("#hierarchy-chart-wrapper").remove(); this.page.main.append(` <div id="hierarchy-chart-wrapper"> <svg id="arrows" width="100%" height="100%"> <defs> <marker id="arrowhead-active" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="6" markerHeight="6" orient="auto" fill="var(--gray-600)"> <path d="M 0 0 L 10 5 L 0 10 z"></path> </marker> <marker id="arrowhead-collapsed" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="6" markerHeight="6" orient="auto" fill="var(--gray-400)"> <path d="M 0 0 L 10 5 L 0 10 z"></path> </marker> <marker id="arrowstart-active" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="8" markerHeight="8" orient="auto" fill="var(--gray-600)"> <circle cx="4" cy="4" r="3.5" fill="white" stroke="var(--gray-600)"/> </marker> <marker id="arrowstart-collapsed" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="8" markerHeight="8" orient="auto" fill="var(--gray-400)"> <circle cx="4" cy="4" r="3.5" fill="white" stroke="var(--gray-400)"/> </marker> </defs> <g id="connectors" fill="none"> </g> </svg> <div id="hierarchy-chart"> </div> </div>`); } render_root_nodes(expanded_view = false) { let me = this; return frappe .call({ method: me.method, args: { company: me.company, }, }) .then((r) => { if (r.message.length) { let expand_node; let node; $.each(r.message, (_i, data) => { if ($(`[id="${data.id}"]`).length) return; node = new me.Node({ id: data.id, parent: $('<li class="child-node"></li>').appendTo( me.$hierarchy.find(".node-children"), ), parent_id: "", image: data.image, name: data.name, title: data.title, expandable: true, connections: data.connections, is_root: true, }); if (!expand_node && data.connections) expand_node = node; }); me.root_node = expand_node; if (!expanded_view) { me.expand_node(expand_node); } } }); } expand_node(node) { const is_sibling = this.selected_node && this.selected_node.parent_id === node.parent_id; this.set_selected_node(node); this.show_active_path(node); this.collapse_previous_level_nodes(node); // since the previous node collapses, all connections to that node need to be rebuilt // if a sibling node is clicked, connections don't need to be rebuilt if (!is_sibling) { // rebuild outgoing connections this.refresh_connectors(node.parent_id); // rebuild incoming connections let grandparent = $(`[id="${node.parent_id}"]`).attr("data-parent"); this.refresh_connectors(grandparent); } if (node.expandable && !node.expanded) { return this.load_children(node); } } collapse_node() { if (this.selected_node.expandable) { this.selected_node.$children.hide(); $(`path[data-parent="${this.selected_node.id}"]`).hide(); this.selected_node.expanded = false; } } show_active_path(node) { // mark node parent on active path $(`[id="${node.parent_id}"]`).addClass("active-path"); } load_children(node, deep = false) { if (!this.company) { frappe.throw(__("Please select a company first.")); } if (!deep) { frappe.run_serially([ () => this.get_child_nodes(node.id), (child_nodes) => this.render_child_nodes(node, child_nodes), ]); } else { frappe.run_serially([ () => frappe.dom.freeze(), () => this.setup_hierarchy(), () => this.render_root_nodes(true), () => this.get_all_nodes(), (data_list) => this.render_children_of_all_nodes(data_list), () => frappe.dom.unfreeze(), ]); } } get_child_nodes(node_id) { let me = this; return new Promise((resolve) => { frappe .call({ method: me.method, args: { parent: node_id, company: me.company, }, }) .then((r) => resolve(r.message)); }); } render_child_nodes(node, child_nodes) { const last_level = this.$hierarchy.find(".level:last").index(); const current_level = $(`[id="${node.id}"]`).parent().parent().parent().index(); if (last_level === current_level) { this.$hierarchy.append(` <li class="level"></li> `); } if (!node.$children) { node.$children = $('<ul class="node-children"></ul>') .hide() .appendTo(this.$hierarchy.find(".level:last")); node.$children.empty(); if (child_nodes) { $.each(child_nodes, (_i, data) => { if (!$(`[id="${data.id}"]`).length) { this.add_node(node, data); setTimeout(() => { this.add_connector(node.id, data.id); }, 250); } }); } } node.$children.show(); $(`path[data-parent="${node.id}"]`).show(); node.expanded = true; } get_all_nodes() { let me = this; return new Promise((resolve) => { frappe.call({ method: "hrms.utils.hierarchy_chart.get_all_nodes", args: { method: me.method, company: me.company, }, callback: (r) => { resolve(r.message); }, }); }); } render_children_of_all_nodes(data_list) { let entry; let node; while (data_list.length) { // to avoid overlapping connectors entry = data_list.shift(); node = this.nodes[entry.parent]; if (node) { this.render_child_nodes_for_expanded_view(node, entry.data); } else if (data_list.length) { data_list.push(entry); } } } render_child_nodes_for_expanded_view(node, child_nodes) { node.$children = $('<ul class="node-children"></ul>'); const last_level = this.$hierarchy.find(".level:last").index(); const node_level = $(`[id="${node.id}"]`).parent().parent().parent().index(); if (last_level === node_level) { this.$hierarchy.append(` <li class="level"></li> `); node.$children.appendTo(this.$hierarchy.find(".level:last")); } else { node.$children.appendTo(this.$hierarchy.find(".level:eq(" + (node_level + 1) + ")")); } node.$children.hide().empty(); if (child_nodes) { $.each(child_nodes, (_i, data) => { this.add_node(node, data); setTimeout(() => { this.add_connector(node.id, data.id); }, 250); }); } node.$children.show(); $(`path[data-parent="${node.id}"]`).show(); node.expanded = true; } add_node(node, data) { return new this.Node({ id: data.id, parent: $('<li class="child-node"></li>').appendTo(node.$children), parent_id: node.id, image: data.image, name: data.name, title: data.title, expandable: data.expandable, connections: data.connections, children: null, }); } add_connector(parent_id, child_id) { // using pure javascript for better performance const parent_node = document.getElementById(`${parent_id}`); const child_node = document.getElementById(`${child_id}`); let path = document.createElementNS("http://www.w3.org/2000/svg", "path"); // we need to connect right side of the parent to the left side of the child node const pos_parent_right = { x: parent_node.offsetLeft + parent_node.offsetWidth, y: parent_node.offsetTop + parent_node.offsetHeight / 2, }; const pos_child_left = { x: child_node.offsetLeft - 5, y: child_node.offsetTop + child_node.offsetHeight / 2, }; const connector = this.get_connector(pos_parent_right, pos_child_left); path.setAttribute("d", connector); this.set_path_attributes(path, parent_id, child_id); document.getElementById("connectors").appendChild(path); } get_connector(pos_parent_right, pos_child_left) { if (pos_parent_right.y === pos_child_left.y) { // don't add arcs if it's a straight line return ( "M" + pos_parent_right.x + "," + pos_parent_right.y + " " + "L" + pos_child_left.x + "," + pos_child_left.y ); } else { let arc_1 = ""; let arc_2 = ""; let offset = 0; if (pos_parent_right.y > pos_child_left.y) { // if child is above parent on Y axis 1st arc is anticlocwise // second arc is clockwise arc_1 = "a10,10 1 0 0 10,-10 "; arc_2 = "a10,10 0 0 1 10,-10 "; offset = 10; } else { // if child is below parent on Y axis 1st arc is clockwise // second arc is anticlockwise arc_1 = "a10,10 0 0 1 10,10 "; arc_2 = "a10,10 1 0 0 10,10 "; offset = -10; } return ( "M" + pos_parent_right.x + "," + pos_parent_right.y + " " + "L" + (pos_parent_right.x + 40) + "," + pos_parent_right.y + " " + arc_1 + "L" + (pos_parent_right.x + 50) + "," + (pos_child_left.y + offset) + " " + arc_2 + "L" + pos_child_left.x + "," + pos_child_left.y ); } } set_path_attributes(path, parent_id, child_id) { path.setAttribute("data-parent", parent_id); path.setAttribute("data-child", child_id); const parent = $(`[id="${parent_id}"]`); if (parent.hasClass("active")) { path.setAttribute("class", "active-connector"); path.setAttribute("marker-start", "url(#arrowstart-active)"); path.setAttribute("marker-end", "url(#arrowhead-active)"); } else { path.setAttribute("class", "collapsed-connector"); path.setAttribute("marker-start", "url(#arrowstart-collapsed)"); path.setAttribute("marker-end", "url(#arrowhead-collapsed)"); } } set_selected_node(node) { // remove active class from the current node if (this.selected_node) this.selected_node.$link.removeClass("active"); // add active class to the newly selected node this.selected_node = node; node.$link.addClass("active"); } collapse_previous_level_nodes(node) { let node_parent = $(`[id="${node.parent_id}"]`); let previous_level_nodes = node_parent.parent().parent().children("li"); let node_card; previous_level_nodes.each(function () { node_card = $(this).find(".node-card"); if (!node_card.hasClass("active-path")) { node_card.addClass("collapsed"); } }); } refresh_connectors(node_parent) { if (!node_parent) return; $(`path[data-parent="${node_parent}"]`).remove(); frappe.run_serially([ () => this.get_child_nodes(node_parent), (child_nodes) => { if (child_nodes) { $.each(child_nodes, (_i, data) => { this.add_connector(node_parent, data.id); }); } }, ]); } setup_node_click_action(node) { let me = this; let node_element = $(`[id="${node.id}"]`); node_element.click(function () { const is_sibling = me.selected_node.parent_id === node.parent_id; if (is_sibling) { me.collapse_node(); } else if ( node_element.is(":visible") && (node_element.hasClass("collapsed") || node_element.hasClass("active-path")) ) { me.remove_levels_after_node(node); me.remove_orphaned_connectors(); } me.expand_node(node); }); } setup_edit_node_action(node) { let node_element = $(`[id="${node.id}"]`); let me = this; node_element.find(".btn-edit-node").click(function () { frappe.set_route("Form", me.doctype, node.id); }); } remove_levels_after_node(node) { let level = $(`[id="${node.id}"]`).parent().parent().parent().index(); level = $(".hierarchy > li:eq(" + level + ")"); level.nextAll("li").remove(); let nodes = level.find(".node-card"); let node_object; $.each(nodes, (_i, element) => { node_object = this.nodes[element.id]; node_object.expanded = 0; node_object.$children = null; }); nodes.removeClass("collapsed active-path"); } remove_orphaned_connectors() { let paths = $("#connectors > path"); $.each(paths, (_i, path) => { const parent = $(path).data("parent"); const child = $(path).data("child"); if ($(`[id="${parent}"]`).length && $(`[id="${child}"]`).length) return; $(path).remove(); }); } };
2302_79757062/hrms
hrms/public/js/hierarchy_chart/hierarchy_chart_desktop.js
JavaScript
agpl-3.0
15,845
hrms.HierarchyChartMobile = class { /* Options: - doctype - wrapper: wrapper for the hierarchy view - method: - to get the data for each node - this method should return id, name, title, image, and connections for each node */ constructor(doctype, wrapper, method) { this.page = wrapper.page; this.method = method; this.doctype = doctype; this.page.main.css({ "min-height": "300px", "max-height": "600px", overflow: "auto", position: "relative", }); this.page.main.addClass("frappe-card"); this.nodes = {}; this.setup_node_class(); } setup_node_class() { let me = this; this.Node = class { constructor({ id, parent, parent_id, image, name, title, expandable, connections, is_root, // eslint-disable-line }) { // to setup values passed via constructor $.extend(this, arguments[0]); this.expanded = 0; me.nodes[this.id] = this; me.make_node_element(this); me.setup_node_click_action(this); me.setup_edit_node_action(this); } }; } make_node_element(node) { let node_card = frappe.render_template("node_card", { id: node.id, name: node.name, title: node.title, image: node.image, parent: node.parent_id, connections: node.connections, is_mobile: true, }); node.parent.append(node_card); node.$link = $(`[id="${node.id}"]`); node.$link.addClass("mobile-node"); } show() { if (this.page.main.find('[data-fieldname="company"]').length) return; let me = this; let company = this.page.add_field({ fieldtype: "Link", options: "Company", fieldname: "company", placeholder: __("Select Company"), default: frappe.defaults.get_default("company"), only_select: true, reqd: 1, change: () => { me.company = ""; if (company.get_value() && me.company != company.get_value()) { me.company = company.get_value(); // svg for connectors me.make_svg_markers(); if (me.$sibling_group) me.$sibling_group.remove(); // setup sibling group wrapper me.$sibling_group = $(`<div class="sibling-group mt-4 mb-4"></div>`); me.page.main.append(me.$sibling_group); me.setup_hierarchy(); me.render_root_nodes(); } }, }); company.refresh(); $(`[data-fieldname="company"]`).trigger("change"); } make_svg_markers() { $("#arrows").remove(); this.page.main.prepend(` <svg id="arrows" width="100%" height="100%"> <defs> <marker id="arrowhead-active" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="6" markerHeight="6" orient="auto" fill="var(--gray-500)"> <path d="M 0 0 L 10 5 L 0 10 z"></path> </marker> <marker id="arrowhead-collapsed" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="6" markerHeight="6" orient="auto" fill="var(--gray-300)"> <path d="M 0 0 L 10 5 L 0 10 z"></path> </marker> <marker id="arrowstart-active" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="8" markerHeight="8" orient="auto" fill="var(--gray-500)"> <circle cx="4" cy="4" r="3.5" fill="white" stroke="var(--gray-500)"/> </marker> <marker id="arrowstart-collapsed" viewBox="0 0 10 10" refX="3" refY="5" markerWidth="8" markerHeight="8" orient="auto" fill="var(--gray-300)"> <circle cx="4" cy="4" r="3.5" fill="white" stroke="var(--gray-300)"/> </marker> </defs> <g id="connectors" fill="none"> </g> </svg>`); } setup_hierarchy() { $(`#connectors`).empty(); if (this.$hierarchy) this.$hierarchy.remove(); if (this.$sibling_group) this.$sibling_group.empty(); this.$hierarchy = $( `<ul class="hierarchy-mobile"> <li class="root-level level"></li> </ul>`, ); this.page.main.append(this.$hierarchy); } render_root_nodes() { let me = this; frappe .call({ method: me.method, args: { company: me.company, }, }) .then((r) => { if (r.message.length) { let root_level = me.$hierarchy.find(".root-level"); root_level.empty(); $.each(r.message, (_i, data) => { return new me.Node({ id: data.id, parent: root_level, parent_id: "", image: data.image, name: data.name, title: data.title, expandable: true, connections: data.connections, is_root: true, }); }); } }); } expand_node(node) { const is_same_node = this.selected_node && this.selected_node.id === node.id; this.set_selected_node(node); this.show_active_path(node); if (this.$sibling_group) { const sibling_parent = this.$sibling_group.find(".node-group").attr("data-parent"); if (node.parent_id != "" && node.parent_id != sibling_parent) this.$sibling_group.empty(); } if (!is_same_node) { // since the previous/parent node collapses, all connections to that node need to be rebuilt // rebuild outgoing connections of parent this.refresh_connectors(node.parent_id, node.id); // rebuild incoming connections of parent let grandparent = $(`[id="${node.parent_id}"]`).attr("data-parent"); this.refresh_connectors(grandparent, node.parent_id); } if (node.expandable && !node.expanded) { return this.load_children(node); } } collapse_node() { let node = this.selected_node; if (node.expandable && node.$children) { node.$children.hide(); node.expanded = 0; // add a collapsed level to show the collapsed parent // and a button beside it to move to that level let node_parent = node.$link.parent(); node_parent.prepend(`<div class="collapsed-level d-flex flex-row"></div>`); node_parent.find(".collapsed-level").append(node.$link); frappe.run_serially([ () => this.get_child_nodes(node.parent_id, node.id), (child_nodes) => this.get_node_group(child_nodes, node.parent_id), (node_group) => node_parent.find(".collapsed-level").append(node_group), () => this.setup_node_group_action(), ]); } } show_active_path(node) { // mark node parent on active path $(`[id="${node.parent_id}"]`).addClass("active-path"); } load_children(node) { if (!this.company) { frappe.throw(__("Please select a company first")); } frappe.run_serially([ () => this.get_child_nodes(node.id), (child_nodes) => this.render_child_nodes(node, child_nodes), ]); } get_child_nodes(node_id, exclude_node = null) { let me = this; return new Promise((resolve) => { frappe .call({ method: me.method, args: { parent: node_id, company: me.company, exclude_node: exclude_node, }, }) .then((r) => resolve(r.message)); }); } render_child_nodes(node, child_nodes) { if (!node.$children) { node.$children = $('<ul class="node-children"></ul>') .hide() .appendTo(node.$link.parent()); node.$children.empty(); if (child_nodes) { $.each(child_nodes, (_i, data) => { this.add_node(node, data); $(`[id="${data.id}"]`).addClass("active-child"); setTimeout(() => { this.add_connector(node.id, data.id); }, 250); }); } } node.$children.show(); node.expanded = 1; } add_node(node, data) { var $li = $('<li class="child-node"></li>'); return new this.Node({ id: data.id, parent: $li.appendTo(node.$children), parent_id: node.id, image: data.image, name: data.name, title: data.title, expandable: data.expandable, connections: data.connections, children: null, }); } add_connector(parent_id, child_id) { const parent_node = document.getElementById(`${parent_id}`); const child_node = document.getElementById(`${child_id}`); const path = document.createElementNS("http://www.w3.org/2000/svg", "path"); let connector = null; if ($(`[id="${parent_id}"]`).hasClass("active")) { connector = this.get_connector_for_active_node(parent_node, child_node); } else if ($(`[id="${parent_id}"]`).hasClass("active-path")) { connector = this.get_connector_for_collapsed_node(parent_node, child_node); } path.setAttribute("d", connector); this.set_path_attributes(path, parent_id, child_id); document.getElementById("connectors").appendChild(path); } get_connector_for_active_node(parent_node, child_node) { // we need to connect the bottom left of the parent to the left side of the child node let pos_parent_bottom = { x: parent_node.offsetLeft + 20, y: parent_node.offsetTop + parent_node.offsetHeight, }; let pos_child_left = { x: child_node.offsetLeft - 5, y: child_node.offsetTop + child_node.offsetHeight / 2, }; let connector = "M" + pos_parent_bottom.x + "," + pos_parent_bottom.y + " " + "L" + pos_parent_bottom.x + "," + (pos_child_left.y - 10) + " " + "a10,10 1 0 0 10,10 " + "L" + pos_child_left.x + "," + pos_child_left.y; return connector; } get_connector_for_collapsed_node(parent_node, child_node) { // we need to connect the bottom left of the parent to the top left of the child node let pos_parent_bottom = { x: parent_node.offsetLeft + 20, y: parent_node.offsetTop + parent_node.offsetHeight, }; let pos_child_top = { x: child_node.offsetLeft + 20, y: child_node.offsetTop, }; let connector = "M" + pos_parent_bottom.x + "," + pos_parent_bottom.y + " " + "L" + pos_child_top.x + "," + pos_child_top.y; return connector; } set_path_attributes(path, parent_id, child_id) { path.setAttribute("data-parent", parent_id); path.setAttribute("data-child", child_id); const parent = $(`[id="${parent_id}"]`); if (parent.hasClass("active")) { path.setAttribute("class", "active-connector"); path.setAttribute("marker-start", "url(#arrowstart-active)"); path.setAttribute("marker-end", "url(#arrowhead-active)"); } else if (parent.hasClass("active-path")) { path.setAttribute("class", "collapsed-connector"); } } set_selected_node(node) { // remove .active class from the current node if (this.selected_node) this.selected_node.$link.removeClass("active"); // add active class to the newly selected node this.selected_node = node; node.$link.addClass("active"); } setup_node_click_action(node) { let me = this; let node_element = $(`[id="${node.id}"]`); node_element.click(function () { let el = null; if (node.is_root) { el = $(this).detach(); me.$hierarchy.empty(); $(`#connectors`).empty(); me.add_node_to_hierarchy(el, node); } else if (node_element.is(":visible") && node_element.hasClass("active-path")) { me.remove_levels_after_node(node); me.remove_orphaned_connectors(); } else { el = $(this).detach(); me.add_node_to_hierarchy(el, node); me.collapse_node(); } me.expand_node(node); }); } setup_edit_node_action(node) { let node_element = $(`[id="${node.id}"]`); let me = this; node_element.find(".btn-edit-node").click(function () { frappe.set_route("Form", me.doctype, node.id); }); } setup_node_group_action() { let me = this; $(".node-group").on("click", function () { let parent = $(this).attr("data-parent"); if (parent == "") { me.setup_hierarchy(); me.render_root_nodes(); } else { me.expand_sibling_group_node(parent); } }); } add_node_to_hierarchy(node_element, node) { this.$hierarchy.append(`<li class="level"></li>`); node_element.removeClass("active-child active-path"); this.$hierarchy.find(".level:last").append(node_element); let node_object = this.nodes[node.id]; node_object.expanded = 0; node_object.$children = null; this.nodes[node.id] = node_object; } get_node_group(nodes, parent, collapsed = true) { let limit = 2; const display_nodes = nodes.slice(0, limit); const extra_nodes = nodes.slice(limit); let html = display_nodes.map((node) => this.get_avatar(node)).join(""); if (extra_nodes.length === 1) { let node = extra_nodes[0]; html += this.get_avatar(node); } else if (extra_nodes.length > 1) { html = ` ${html} <span class="avatar avatar-small"> <div class="avatar-frame standard-image avatar-extra-count" title="${extra_nodes.map((node) => node.name).join(", ")}"> +${extra_nodes.length} </div> </span> `; } if (html) { const $node_group = $(`<div class="node-group card cursor-pointer" data-parent=${parent}> <div class="avatar-group right overlap"> ${html} </div> </div>`); if (collapsed) $node_group.addClass("collapsed"); return $node_group; } return null; } get_avatar(node) { return `<span class="avatar avatar-small" title="${node.name}"> <span class="avatar-frame" src=${node.image} style="background-image: url(${node.image})"></span> </span>`; } expand_sibling_group_node(parent) { let node_object = this.nodes[parent]; let node = node_object.$link; node.removeClass("active-child active-path"); node_object.expanded = 0; node_object.$children = null; this.nodes[node.id] = node_object; // show parent's siblings and expand parent node frappe.run_serially([ () => this.get_child_nodes(node_object.parent_id, node_object.id), (child_nodes) => this.get_node_group(child_nodes, node_object.parent_id, false), (node_group) => { if (node_group) this.$sibling_group.empty().append(node_group); }, () => this.setup_node_group_action(), () => this.reattach_and_expand_node(node, node_object), ]); } reattach_and_expand_node(node, node_object) { var el = node.detach(); this.$hierarchy.empty().append(` <li class="level"></li> `); this.$hierarchy.find(".level").append(el); $(`#connectors`).empty(); this.expand_node(node_object); } remove_levels_after_node(node) { let level = $(`[id="${node.id}"]`).parent().parent().index(); level = $(".hierarchy-mobile > li:eq(" + level + ")"); level.nextAll("li").remove(); let node_object = this.nodes[node.id]; let current_node = level.find(`[id="${node.id}"]`).detach(); current_node.removeClass("active-child active-path"); node_object.expanded = 0; node_object.$children = null; level.empty().append(current_node); } remove_orphaned_connectors() { let paths = $("#connectors > path"); $.each(paths, (_i, path) => { const parent = $(path).data("parent"); const child = $(path).data("child"); if ($(`[id="${parent}"]`).length && $(`[id="${child}"]`).length) return; $(path).remove(); }); } refresh_connectors(node_parent, node_id) { if (!node_parent) return; $(`path[data-parent="${node_parent}"]`).remove(); this.add_connector(node_parent, node_id); } };
2302_79757062/hrms
hrms/public/js/hierarchy_chart/hierarchy_chart_mobile.js
JavaScript
agpl-3.0
14,587
import "./templates/employees_with_unmarked_attendance.html"; import "./templates/feedback_summary.html"; import "./templates/feedback_history.html"; import "./templates/rating.html"; import "./utils"; import "./utils/payroll_utils"; import "./utils/leave_utils"; import "./salary_slip_deductions_report_filters.js";
2302_79757062/hrms
hrms/public/js/hrms.bundle.js
JavaScript
agpl-3.0
317
import "./templates/interview_feedback.html"; import "./templates/circular_progress_bar.html";
2302_79757062/hrms
hrms/public/js/interview.bundle.js
JavaScript
agpl-3.0
95
frappe.provide("hrms"); hrms.PerformanceFeedback = class PerformanceFeedback { constructor({ frm, wrapper }) { this.frm = frm; this.wrapper = wrapper; } refresh() { this.prepare_dom(); this.setup_feedback_view(); } prepare_dom() { this.wrapper.find(".feedback-section").remove(); } setup_feedback_view() { frappe.run_serially([ () => this.get_feedback_history(), (data) => this.render_feedback_history(data), () => this.setup_actions(), ]); } get_feedback_history() { let me = this; return new Promise((resolve) => { frappe .call({ method: "hrms.hr.doctype.appraisal.appraisal.get_feedback_history", args: { employee: me.frm.doc.employee, appraisal: me.frm.doc.name, }, }) .then((r) => resolve(r.message)); }); } async render_feedback_history(data) { const { feedback_history, reviews_per_rating, avg_feedback_score } = data || {}; const can_create = await this.can_create(); const feedback_html = frappe.render_template("performance_feedback", { feedback_history: feedback_history, average_feedback_score: avg_feedback_score, reviews_per_rating: reviews_per_rating, can_create: can_create, }); $(this.wrapper).empty(); $(feedback_html).appendTo(this.wrapper); } setup_actions() { let me = this; $(".new-feedback-btn").click(() => { me.add_feedback(); }); } add_feedback() { frappe.run_serially([ () => this.get_feedback_criteria_data(), (criteria_data) => this.show_add_feedback_dialog(criteria_data), ]); } get_feedback_criteria_data() { let me = this; return new Promise((resolve) => { frappe.db .get_doc("Appraisal Template", me.frm.doc.appraisal_template) .then(({ rating_criteria }) => { const criteria_list = []; rating_criteria.forEach((entry) => { criteria_list.push({ criteria: entry.criteria, per_weightage: entry.per_weightage, }); }); resolve(criteria_list); }); }); } show_add_feedback_dialog(criteria_data) { let me = this; const dialog = new frappe.ui.Dialog({ title: __("Add Feedback"), fields: me.get_feedback_dialog_fields(criteria_data), size: "large", minimizable: true, primary_action_label: __("Submit"), primary_action: function () { const data = dialog.get_values(); frappe.call({ method: "add_feedback", doc: me.frm.doc, args: { feedback: data.feedback, feedback_ratings: data.feedback_ratings, }, freeze: true, callback: function (r) { if (!r.exc) { frappe.run_serially([ () => me.frm.refresh_fields(), () => me.refresh(), ]); frappe.show_alert({ message: __("Feedback {0} added successfully", [ r.message?.name?.bold(), ]), indicator: "green", }); } dialog.hide(); }, }); }, }); dialog.show(); } get_feedback_dialog_fields(criteria_data) { return [ { label: "Feedback", fieldname: "feedback", fieldtype: "Text Editor", reqd: 1, enable_mentions: true, }, { label: "Feedback Rating", fieldtype: "Table", fieldname: "feedback_ratings", cannot_add_rows: true, data: criteria_data, fields: [ { fieldname: "criteria", fieldtype: "Link", in_list_view: 1, label: "Criteria", options: "Employee Feedback Criteria", reqd: 1, }, { fieldname: "per_weightage", fieldtype: "Percent", in_list_view: 1, label: "Weightage", }, { fieldname: "rating", fieldtype: "Rating", in_list_view: 1, label: "Rating", }, ], }, ]; } async can_create() { const is_employee = (await frappe.db.get_value("Employee", { user_id: frappe.session.user }, "name")) ?.message?.name || false; return is_employee && frappe.model.can_create("Employee Performance Feedback"); } };
2302_79757062/hrms
hrms/public/js/performance/performance_feedback.js
JavaScript
agpl-3.0
3,963
import "./performance/performance_feedback.js"; import "./templates/performance_feedback.html";
2302_79757062/hrms
hrms/public/js/performance.bundle.js
JavaScript
agpl-3.0
96
frappe.provide("hrms.salary_slip_deductions_report_filters"); hrms.salary_slip_deductions_report_filters = { filters: [ { fieldname: "company", label: __("Company"), fieldtype: "Link", options: "Company", reqd: 1, default: frappe.defaults.get_user_default("Company"), }, { 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: "department", label: __("Department"), fieldtype: "Link", options: "Department", }, { fieldname: "branch", label: __("Branch"), fieldtype: "Link", options: "Branch", }, ], onload: function () { return frappe.call({ method: "hrms.payroll.report.provident_fund_deductions.provident_fund_deductions.get_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); }, }); }, };
2302_79757062/hrms
hrms/public/js/salary_slip_deductions_report_filters.js
JavaScript
agpl-3.0
1,658
<div class="circular-progress mx-auto mb-3"> {% degree = Math.floor(rating*360/5) %} {% deg_right = degree > 180 ? 180 : degree %} {% deg_left = degree > 180 ? degree - 180 : 0 %} <span class="progress-left" style="--deg-left: {{ deg_left }}deg"> <span class="progress-bar" style="border-color: var(--gray-600)"></span> </span> <span class="progress-right" style="--deg-right: {{ deg_right }}deg"> <span class="progress-bar" style="border-color: var(--gray-600)"></span> </span> <div class="progress-value">{{ flt(rating, 2) }}</div> </div> <h5 class="text-center">{{ skill }}</h5>
2302_79757062/hrms
hrms/public/js/templates/circular_progress_bar.html
HTML
agpl-3.0
594
{% if data.length %} <div class="form-message yellow"> <div> {{ __( "Attendance is pending for these employees between the selected payroll dates. Mark attendance to proceed. Refer {0} for details.", ["<a href='/app/query-report/Monthly%20Attendance%20Sheet'>Monthly Attendance Sheet</a>"] ) }} </div> </div> <table class="table table-bordered small"> <thead> <tr> <th style="width: 14%" class="text-left">{{ __("Employee") }}</th> <th style="width: 16%" class="text-left">{{ __("Employee Name") }}</th> <th style="width: 12%" class="text-left">{{ __("Unmarked Days") }}</th> </tr> </thead> <tbody> {% for item in data %} <tr> <td class="text-left"> {{ item.employee }} </td> <td class="text-left"> {{ item.employee_name }} </td> <td class="text-left"> {{ item.unmarked_days }} </td> </tr> {% } %} </tbody> </table> {% } else { %} <div class="form-message green"> <div>{{ __("Attendance has been marked for all the employees between the selected payroll dates.") }}</div> </div> {% } %}
2302_79757062/hrms
hrms/public/js/templates/employees_with_unmarked_attendance.html
HTML
agpl-3.0
1,051
<div class="feedback-history mb-3"> {% if (feedback_history.length) { %} {% for (let i=0, l=feedback_history.length; i<l; i++) { %} <div class="feedback-content p-3 d-flex flex-row mt-3" data-name="{{ feedback_history[i].name }}"> <!-- Reviewer Info --> <div class="reviewer-info mb-2 col-xs-3"> <div class="row"> <div class="col-xs-2"> {{ frappe.avatar(feedback_history[i].user, "avatar-medium") }} </div> <div class="col-xs-10"> <div class="ml-2"> <div class="title font-weight-bold"> {{ strip_html(feedback_history[i].reviewer_name || feedback_history[i].user) }} </div> {% if (feedback_history[i].reviewer_designation) { %} <div class="small text-muted"> {{ strip_html(feedback_history[i].reviewer_designation) }} </div> {% } %} </div> </div> </div> </div> <!-- Feedback --> <div class="reviewer-feedback col-xs-6"> <div class="rating"> {%= frappe.render_template("rating", {number_of_stars: 5, average_rating: feedback_history[i].total_score, for_summary: false} ) %} </div> <div class="feedback my-3"> {{ feedback_history[i].feedback }} </div> </div> <!-- Feedback Date & Link --> <div class="feedback-info col-xs-3 d-flex flex-row justify-content-end align-items-baseline"> <div class="time small text-muted mr-2"> {{ frappe.datetime.comment_when(feedback_history[i].added_on) }} </div> <a href="{{ frappe.utils.get_form_link(feedback_doctype, feedback_history[i].name) }}" title="{{ __("Open Feedback") }}"> <svg class="icon icon-sm"> <use href="#icon-link-url"></use> </svg> </a> </div> </div> {% } %} {% } else { %} <div class="no-feedback d-flex flex-col justify-content-center align-items-center text-muted"> <span>{{ __("No feedback has been received yet") }}</span> </div> {% } %} </div>
2302_79757062/hrms
hrms/public/js/templates/feedback_history.html
HTML
agpl-3.0
1,982
<div class="feedback-summary-section my-4 d-flex"> <!-- Ratings Summary --> <div class="rating-summary-numbers col-3"> <div class="feedback-count mt-1 mb-2 text-secondary"> {{ __("Average Rating") }} </div> <h2 class="average-rating mb-2">{{ average_rating }}</h2> {%= frappe.render_template("rating", {number_of_stars: 5, average_rating: average_rating, for_summary: true} ) %} <div class="feedback-count text-secondary mt-2"> {{ __("based on") }} {{ cstr(feedback_count) }} {{ feedback_count > 1 ? __("reviews") : __("review") }} </div> </div> <!-- Rating Progress Bars --> <div class="rating-progress-bar-section pb-0 col-4"> {% for(let i=5; i>0; i--) { %} <div class="row {{ i!=1 && 'mb-3' }}"> <div class="col-sm-3 text-nowrap flex align-items-center"> <svg class="icon icon-sm mr-2"> <use href="#icon-star" class="like-icon"></use> </svg> <span>{{ i }}</span> </div> <div class="col-md-7"> <div class="progress rating-progress-bar" title="{{ reviews_per_rating[i-1] }} % of reviews are {{ i }} star" > <div class="progress-bar progress-bar-cosmetic" role="progressbar" aria-valuenow="{{ reviews_per_rating[i-1] }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ reviews_per_rating[i-1] }}%;" ></div> </div> </div> <div class="col-sm-1 small">{{ reviews_per_rating[i-1] }}%</div> </div> {% } %} </div> </div>
2302_79757062/hrms
hrms/public/js/templates/feedback_summary.html
HTML
agpl-3.0
1,469
<div class="feedback-section col-xs-12"> {% if feedbacks.length %} <h4 class="my-4 mx-5" style="font-size: 18px"> {{ __("Overall Average Rating") }} </h4> {%= frappe.render_template( "feedback_summary", { number_of_stars: 5, average_rating: average_rating, feedback_count: feedbacks.length, reviews_per_rating: reviews_per_rating } ) %} <div class="m-5"> <h4 class="mb-2" style="font-size: 18px">{{ __("Feedback Summary") }}</h4> <p class="mb-5 text-secondary"> {{ __("Average rating of demonstrated skills") }} </p> <div class="row"> {% for(const d of skills_average_rating) { %} <div class="col-md-4 mb-4"> {%= frappe.render_template("circular_progress_bar", {skill: d.skill, rating: d.rating * 5}) %} </div> {% } %} </div> </div> {% } %} {%= frappe.render_template("feedback_history", { feedback_history: feedbacks, feedback_doctype: "Interview Feedback" }) %} </div>
2302_79757062/hrms
hrms/public/js/templates/interview_feedback.html
HTML
agpl-3.0
923
<div class="node-card card cursor-pointer" id="{%= id %}" data-parent="{%= parent %}"> <div class="node-meta d-flex flex-row"> <div class="mr-3"> <span class="avatar node-image" title="{{ name }}"> <span class="avatar-frame" src={{image}} style="background-image: url('{{ image }}')"></span> </span> </div> <div> <div class="node-name d-flex flex-row mb-1"> <span class="ellipsis">{{ name }}</span> <div class="btn-sm btn-edit-node"> <a class="node-edit-icon"> <svg class="es-icon es-line icon-xs icon"> <use href="#es-line-edit"></use> </svg> </a> <span class="edit-chart-node text-lg">{{ __("Edit") }}</span> </div> </div> <div class="node-info d-flex flex-row mb-1"> {% if title %} <div class="node-title text-muted ellipsis">{{ title }}&nbsp;&middot;&nbsp;</div> {% endif %} {% if is_mobile %} <div class="node-connections text-muted ellipsis"> &nbsp;{{ connections }} <span class="fa fa-level-down"></span> </div> {% else %} {% if connections == 1 %} <div class="node-connections text-muted ellipsis">{{ connections }} Connection</div> {% else %} <div class="node-connections text-muted ellipsis">{{ connections }} Connections</div> {% endif %} {% endif %} </div> </div> </div> </div>
2302_79757062/hrms
hrms/public/js/templates/node_card.html
HTML
agpl-3.0
1,337
<div class="feedback-section col-xs-12"> {% if (feedback_history.length) { %} <div class="feedback-summary mb-5 pb-2"> {%= frappe.render_template( "feedback_summary", { number_of_stars: 5, average_rating: average_feedback_score, feedback_count: feedback_history.length, reviews_per_rating: reviews_per_rating } ) %} </div> {% } %} {% if (can_create) { %} <div class="new-btn pb-3 text-right"> <button class="new-feedback-btn btn btn-sm d-inline-flex align-items-center justify-content-center px-3 py-2 border" > <svg class="icon icon-sm"> <use href="#icon-add"></use> </svg> {{ __("New Feedback") }} </button> </div> {% } %} {%= frappe.render_template( "feedback_history", { feedback_history: feedback_history, feedback_doctype: "Employee Performance Feedback" } ) %} </div>
2302_79757062/hrms
hrms/public/js/templates/performance_feedback.html
HTML
agpl-3.0
884
<div class="d-flex flex-col"> <div class="rating {{ for_summary ? 'ratings-pill' : ''}}"> {% for (let i = 1; i <= number_of_stars; i++) { %} {% if (i <= average_rating) { %} {% right_class = 'star-click'; %} {% } else { %} {% right_class = ''; %} {% } %} {% if ((i <= average_rating) || ((i - 0.5) == average_rating)) { %} {% left_class = 'star-click'; %} {% } else { %} {% left_class = ''; %} {% } %} <svg class="icon icon-md" data-rating={{i}} viewBox="0 0 24 24" fill="none"> <path class="right-half {{ right_class }}" d="M11.9987 3.00011C12.177 3.00011 12.3554 3.09303 12.4471 3.27888L14.8213 8.09112C14.8941 8.23872 15.0349 8.34102 15.1978 8.3647L20.5069 9.13641C20.917 9.19602 21.0807 9.69992 20.7841 9.9892L16.9421 13.7354C16.8243 13.8503 16.7706 14.0157 16.7984 14.1779L17.7053 19.4674C17.7753 19.8759 17.3466 20.1874 16.9798 19.9945L12.2314 17.4973C12.1586 17.459 12.0786 17.4398 11.9987 17.4398V3.00011Z" fill="var(--star-fill)" stroke="var(--star-fill)"/> <path class="left-half {{ left_class }}" d="M11.9987 3.00011C11.8207 3.00011 11.6428 3.09261 11.5509 3.27762L9.15562 8.09836C9.08253 8.24546 8.94185 8.34728 8.77927 8.37075L3.42887 9.14298C3.01771 9.20233 2.85405 9.70811 3.1525 9.99707L7.01978 13.7414C7.13858 13.8564 7.19283 14.0228 7.16469 14.1857L6.25116 19.4762C6.18071 19.8842 6.6083 20.1961 6.97531 20.0045L11.7672 17.5022C11.8397 17.4643 11.9192 17.4454 11.9987 17.4454V3.00011Z" fill="var(--star-fill)" stroke="var(--star-fill)"/> </svg> {% } %} </div> {% if (!for_summary) { %} <p class="ml-3" style="line-height: 2;"> ({{ flt(average_rating, 2) }}) </p> {% } %} </div>
2302_79757062/hrms
hrms/public/js/templates/rating.html
HTML
agpl-3.0
1,661
frappe.provide("hrms"); $.extend(hrms, { proceed_save_with_reminders_frequency_change: () => { frappe.ui.hide_open_dialog(); frappe.call({ method: "hrms.hr.doctype.hr_settings.hr_settings.set_proceed_with_frequency_change", callback: () => { // nosemgrep: frappe-semgrep-rules.rules.frappe-cur-frm-usage cur_frm.save(); }, }); }, set_payroll_frequency_to_null: (frm) => { if (cint(frm.doc.salary_slip_based_on_timesheet)) { frm.set_value("payroll_frequency", ""); } }, get_current_employee: async (frm) => { const employee = ( await frappe.db.get_value("Employee", { user_id: frappe.session.user }, "name") )?.message?.name; return employee; }, validate_mandatory_fields: (frm, selected_rows, items = "Employees") => { const missing_fields = []; for (d in frm.fields_dict) { if (frm.fields_dict[d].df.reqd && !frm.doc[d] && d !== "__newname") missing_fields.push(frm.fields_dict[d].df.label); } if (missing_fields.length) { let message = __("Mandatory fields required for this action"); message += "<br><br><ul><li>" + missing_fields.join("</li><li>") + "</ul>"; frappe.throw({ message: message, title: __("Missing Fields"), }); } if (!selected_rows.length) frappe.throw({ message: __("Please select at least one row to perform this action."), title: __("No {0} Selected", [__(items)]), }); }, setup_employee_filter_group: (frm) => { const filter_wrapper = frm.fields_dict.filter_list.$wrapper; filter_wrapper.empty(); frappe.model.with_doctype("Employee", () => { frm.filter_list = new frappe.ui.FilterGroup({ parent: filter_wrapper, doctype: "Employee", on_change: () => { frm.advanced_filters = frm.filter_list .get_filters() .reduce((filters, item) => { // item[3] is the value from the array [doctype, fieldname, condition, value] if (item[3]) { filters.push(item.slice(1, 4)); } return filters; }, []); frm.trigger("get_employees"); }, }); }); }, render_employees_datatable: ( frm, columns, employees, no_data_message = __("No Data"), get_editor = null, events = {}, ) => { // section automatically collapses on applying a single filter frm.set_df_property("quick_filters_section", "collapsible", 0); frm.set_df_property("advanced_filters_section", "collapsible", 0); if (frm.employees_datatable) { frm.employees_datatable.rowmanager.checkMap = []; frm.employees_datatable.options.noDataMessage = no_data_message; frm.employees_datatable.refresh(employees, columns); return; } const $wrapper = frm.get_field("employees_html").$wrapper; const employee_wrapper = $(`<div class="employee_wrapper">`).appendTo($wrapper); const datatable_options = { columns: columns, data: employees, checkboxColumn: true, checkedRowStatus: false, serialNoColumn: false, dynamicRowHeight: true, inlineFilters: true, layout: "fluid", cellHeight: 35, noDataMessage: no_data_message, disableReorderColumn: true, getEditor: get_editor, events: events, }; frm.employees_datatable = new frappe.DataTable(employee_wrapper.get(0), datatable_options); }, handle_realtime_bulk_action_notification: (frm, event, doctype) => { frappe.realtime.off(event); frappe.realtime.on(event, (message) => { hrms.notify_bulk_action_status( doctype, message.failure, message.success, message.for_processing, ); // refresh only on complete/partial success if (message.success) frm.refresh(); }); }, notify_bulk_action_status: (doctype, failure, success, for_processing = false) => { let action = __("create/submit"); let action_past = __("created"); if (for_processing) { action = __("process"); action_past = __("processed"); } let message = ""; let title = __("Success"); let indicator = "green"; if (failure.length) { message += __("Failed to {0} {1} for employees:", [action, doctype]); message += " " + frappe.utils.comma_and(failure) + "<hr>"; message += __( "Check <a href='/app/List/Error Log?reference_doctype={0}'>{1}</a> for more details", [doctype, __("Error Log")], ); title = __("Failure"); indicator = "red"; if (success.length) { message += "<hr>"; title = __("Partial Success"); indicator = "orange"; } } if (success.length) { message += __("Successfully {0} {1} for the following employees:", [ action_past, doctype, ]); message += __( "<table class='table table-bordered'><tr><th>{0}</th><th>{1}</th></tr>", [__("Employee"), doctype], ); for (const d of success) { message += `<tr><td>${d.employee}</td><td>${d.doc}</td></tr>`; } message += "</table>"; } frappe.msgprint({ message, title, indicator, is_minimizable: true, }); }, get_doctype_fields_for_autocompletion: (doctype) => { const fields = frappe.get_meta(doctype).fields; const autocompletions = []; fields .filter((df) => !frappe.model.no_value_type.includes(df.fieldtype)) .map((df) => { autocompletions.push({ value: df.fieldname, score: 8, meta: __("{0} Field", [doctype]), }); }); return autocompletions; }, });
2302_79757062/hrms
hrms/public/js/utils/index.js
JavaScript
agpl-3.0
5,268
hrms.leave_utils = { add_view_ledger_button(frm) { if (frm.doc.__islocal || frm.doc.docstatus != 1) return; frm.add_custom_button(__("View Ledger"), () => { frappe.route_options = { from_date: frm.doc.from_date, to_date: frm.doc.to_date, transaction_type: frm.doc.doctype, transaction_name: frm.doc.name, }; frappe.set_route("query-report", "Leave Ledger"); }); }, };
2302_79757062/hrms
hrms/public/js/utils/leave_utils.js
JavaScript
agpl-3.0
402
hrms.payroll_utils = { set_autocompletions_for_condition_and_formula: function (frm, child_row = "") { const autocompletions = []; frappe.run_serially([ ...["Employee", "Salary Structure", "Salary Structure Assignment", "Salary Slip"].map( (doctype) => frappe.model.with_doctype(doctype, () => { autocompletions.push( ...hrms.get_doctype_fields_for_autocompletion(doctype), ); }), ), () => { frappe.db .get_list("Salary Component", { fields: ["salary_component_abbr"], }) .then((salary_components) => { autocompletions.push( ...salary_components.map((d) => ({ value: d.salary_component_abbr, score: 9, meta: __("Salary Component"), })), ); autocompletions.push( ...["base", "variable"].map((d) => ({ value: d, score: 10, meta: __("Salary Structure Assignment field"), })), ); if (child_row) { ["condition", "formula"].forEach((field) => { frm.set_df_property( child_row.parentfield, "autocompletions", autocompletions, frm.doc.name, field, child_row.name, ); }); frm.refresh_field(child_row.parentfield); } else { ["condition", "formula"].forEach((field) => { frm.set_df_property(field, "autocompletions", autocompletions); }); } }); }, ]); }, };
2302_79757062/hrms
hrms/public/js/utils/payroll_utils.js
JavaScript
agpl-3.0
1,464
.circular-progress { width: 80px; height: 80px; line-height: 80px; position: relative; } .circular-progress:after { content: ""; width: 100%; height: 100%; border-radius: 50%; border: 7px solid var(--gray-200); position: absolute; top: 0; left: 0; } .circular-progress > span { width: 50%; height: 100%; overflow: hidden; position: absolute; top: 0; z-index: 1; } .circular-progress .progress-left { left: 0; } .circular-progress .progress-bar { width: 100%; height: 100%; background: none; border-width: 6px; border-style: solid; position: absolute; top: 0; } .circular-progress .progress-left .progress-bar { left: 100%; border-top-right-radius: 80px; border-bottom-right-radius: 80px; border-left: 0; -webkit-transform-origin: center left; transform-origin: center left; } .circular-progress .progress-right { right: 0; } .circular-progress .progress-right .progress-bar { left: -100%; border-top-left-radius: 80px; border-bottom-left-radius: 80px; border-right: 0; -webkit-transform-origin: center right; transform-origin: center right; animation: loading-1 0.8s linear forwards; } .circular-progress .progress-value { width: 100%; height: 100%; font-size: 15px; font-weight: bold; text-align: center; position: absolute; } .circular-progress .progress-left .progress-bar { animation: loading-2 0.5s linear forwards 0.8s; } @keyframes loading-1 { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(var(--deg-right)); transform: rotate(var(--deg-right)); } } @keyframes loading-2 { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(var(--deg-left)); transform: rotate(var(--deg-left)); } }
2302_79757062/hrms
hrms/public/scss/circular_progress.scss
SCSS
agpl-3.0
1,770