blob: 2540b3db63b46486b860c883e3ee2baee002a00b [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Anand Doshi60666a22013-04-12 20:19:53 +05303
Rohandb2d1962021-03-09 21:03:45 +05304import erpnext
5import frappe
Jamsheercc25eb02018-06-13 15:14:24 +05306from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
Rohandb2d1962021-03-09 21:03:45 +05307from frappe import _
8from frappe.desk.form import assign_to
9from frappe.model.document import Document
10from frappe.utils import (add_days, cstr, flt, format_datetime, formatdate,
11 get_datetime, getdate, nowdate, today, unique)
12
Manas Solankib6988462018-05-10 18:07:20 +053013
Nabin Hait58ee6c12020-04-26 17:45:57 +053014class DuplicateDeclarationError(frappe.ValidationError): pass
15
Rohandb2d1962021-03-09 21:03:45 +053016
Manas Solankib6988462018-05-10 18:07:20 +053017class EmployeeBoardingController(Document):
18 '''
19 Create the project and the task for the boarding process
20 Assign to the concerned person and roles as per the onboarding/separation template
21 '''
22 def validate(self):
23 # remove the task if linked before submitting the form
24 if self.amended_from:
25 for activity in self.activities:
26 activity.task = ''
27
28 def on_submit(self):
29 # create the project for the given employee onboarding
Manas Solanki70899f52018-05-15 18:52:14 +053030 project_name = _(self.doctype) + " : "
Manas Solankib6988462018-05-10 18:07:20 +053031 if self.doctype == "Employee Onboarding":
Manas Solanki70899f52018-05-15 18:52:14 +053032 project_name += self.job_applicant
Manas Solankib6988462018-05-10 18:07:20 +053033 else:
Manas Solanki70899f52018-05-15 18:52:14 +053034 project_name += self.employee
Rucha Mahabalf1bdfac2021-05-03 18:37:00 +053035
Manas Solankib6988462018-05-10 18:07:20 +053036 project = frappe.get_doc({
37 "doctype": "Project",
38 "project_name": project_name,
39 "expected_start_date": self.date_of_joining if self.doctype == "Employee Onboarding" else self.resignation_letter_date,
40 "department": self.department,
41 "company": self.company
Rucha Mahabalf1bdfac2021-05-03 18:37:00 +053042 }).insert(ignore_permissions=True, ignore_mandatory=True)
43
Manas Solankib6988462018-05-10 18:07:20 +053044 self.db_set("project", project.name)
Shreya5c6ade42018-06-20 15:48:27 +053045 self.db_set("boarding_status", "Pending")
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053046 self.reload()
47 self.create_task_and_notify_user()
Manas Solankib6988462018-05-10 18:07:20 +053048
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053049 def create_task_and_notify_user(self):
Manas Solankib6988462018-05-10 18:07:20 +053050 # create the task for the given project and assign to the concerned person
51 for activity in self.activities:
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053052 if activity.task:
53 continue
54
Manas Solankib6988462018-05-10 18:07:20 +053055 task = frappe.get_doc({
Rohandb2d1962021-03-09 21:03:45 +053056 "doctype": "Task",
57 "project": self.project,
58 "subject": activity.activity_name + " : " + self.employee_name,
59 "description": activity.description,
60 "department": self.department,
61 "company": self.company,
62 "task_weight": activity.task_weight
63 }).insert(ignore_permissions=True)
Manas Solankib6988462018-05-10 18:07:20 +053064 activity.db_set("task", task.name)
Rohandb2d1962021-03-09 21:03:45 +053065
Manas Solankib6988462018-05-10 18:07:20 +053066 users = [activity.user] if activity.user else []
67 if activity.role:
Rohandb2d1962021-03-09 21:03:45 +053068 user_list = frappe.db.sql_list('''
69 SELECT
70 DISTINCT(has_role.parent)
71 FROM
72 `tabHas Role` has_role
73 LEFT JOIN `tabUser` user
74 ON has_role.parent = user.name
75 WHERE
76 has_role.parenttype = 'User'
77 AND user.enabled = 1
78 AND has_role.role = %s
79 ''', activity.role)
80 users = unique(users + user_list)
Manas Solankib6988462018-05-10 18:07:20 +053081
Anurag Mishraadd6bf32019-01-04 11:36:30 +053082 if "Administrator" in users:
83 users.remove("Administrator")
84
Manas Solankib6988462018-05-10 18:07:20 +053085 # assign the task the users
86 if users:
Rohandb2d1962021-03-09 21:03:45 +053087 self.assign_task_to_users(task, users)
Manas Solankib6988462018-05-10 18:07:20 +053088
89 def assign_task_to_users(self, task, users):
90 for user in users:
91 args = {
Anurag Mishra225802e2020-06-04 14:11:18 +053092 'assign_to': [user],
93 'doctype': task.doctype,
94 'name': task.name,
95 'description': task.description or task.subject,
96 'notify': self.notify_users_by_email
Manas Solankib6988462018-05-10 18:07:20 +053097 }
98 assign_to.add(args)
99
100 def on_cancel(self):
101 # delete task project
102 for task in frappe.get_all("Task", filters={"project": self.project}):
Zarrar9a3b7852018-07-11 14:34:55 +0530103 frappe.delete_doc("Task", task.name, force=1)
104 frappe.delete_doc("Project", self.project, force=1)
Manas Solankib6988462018-05-10 18:07:20 +0530105 self.db_set('project', '')
106 for activity in self.activities:
107 activity.db_set("task", "")
108
109
110@frappe.whitelist()
111def get_onboarding_details(parent, parenttype):
Nabin Hait01b2a652018-08-28 14:09:27 +0530112 return frappe.get_all("Employee Boarding Activity",
Himanshu4cb1a1e2019-06-05 10:26:01 +0530113 fields=["activity_name", "role", "user", "required_for_employee_creation", "description", "task_weight"],
Manas Solankib6988462018-05-10 18:07:20 +0530114 filters={"parent": parent, "parenttype": parenttype},
115 order_by= "idx")
Anand Doshi60666a22013-04-12 20:19:53 +0530116
Shreya5c6ade42018-06-20 15:48:27 +0530117@frappe.whitelist()
118def get_boarding_status(project):
119 status = 'Pending'
120 if project:
121 doc = frappe.get_doc('Project', project)
122 if flt(doc.percent_complete) > 0.0 and flt(doc.percent_complete) < 100.0:
123 status = 'In Process'
124 elif flt(doc.percent_complete) == 100.0:
125 status = 'Completed'
126 return status
127
Anand Doshic280d062014-05-30 14:43:36 +0530128def set_employee_name(doc):
129 if doc.employee and not doc.employee_name:
130 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +0530131
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530132def update_employee(employee, details, date=None, cancel=False):
133 internal_work_history = {}
Manas Solankib6988462018-05-10 18:07:20 +0530134 for item in details:
135 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
136 new_data = item.new if not cancel else item.current
137 if fieldtype == "Date" and new_data:
138 new_data = getdate(new_data)
139 elif fieldtype =="Datetime" and new_data:
140 new_data = get_datetime(new_data)
141 setattr(employee, item.fieldname, new_data)
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530142 if item.fieldname in ["department", "designation", "branch"]:
143 internal_work_history[item.fieldname] = item.new
144 if internal_work_history and not cancel:
145 internal_work_history["from_date"] = date
146 employee.append("internal_work_history", internal_work_history)
Manas Solankib6988462018-05-10 18:07:20 +0530147 return employee
148
Ranjithfddfffd2018-05-05 13:27:26 +0530149@frappe.whitelist()
150def get_employee_fields_label():
151 fields = []
152 for df in frappe.get_meta("Employee").get("fields"):
Ranjith Kurungadamc1030a32018-06-20 12:42:58 +0530153 if df.fieldname in ["salutation", "user_id", "employee_number", "employment_type",
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530154 "holiday_list", "branch", "department", "designation", "grade",
155 "notice_number_of_days", "reports_to", "leave_policy", "company_email"]:
156 fields.append({"value": df.fieldname, "label": df.label})
Ranjithfddfffd2018-05-05 13:27:26 +0530157 return fields
158
159@frappe.whitelist()
160def get_employee_field_property(employee, fieldname):
161 if employee and fieldname:
162 field = frappe.get_meta("Employee").get_field(fieldname)
163 value = frappe.db.get_value("Employee", employee, fieldname)
164 options = field.options
165 if field.fieldtype == "Date":
166 value = formatdate(value)
167 elif field.fieldtype == "Datetime":
168 value = format_datetime(value)
169 return {
170 "value" : value,
171 "datatype" : field.fieldtype,
172 "label" : field.label,
173 "options" : options
174 }
175 else:
176 return False
177
Jamsheer0e2cc552018-05-08 11:48:25 +0530178def validate_dates(doc, from_date, to_date):
179 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
180 if getdate(from_date) > getdate(to_date):
181 frappe.throw(_("To date can not be less than from date"))
182 elif getdate(from_date) > getdate(nowdate()):
183 frappe.throw(_("Future dates not allowed"))
184 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
185 frappe.throw(_("From date can not be less than employee's joining date"))
186 elif relieving_date and getdate(to_date) > getdate(relieving_date):
187 frappe.throw(_("To date can not greater than employee's relieving date"))
188
189def validate_overlap(doc, from_date, to_date, company = None):
190 query = """
191 select name
192 from `tab{0}`
193 where name != %(name)s
194 """
195 query += get_doc_condition(doc.doctype)
196
197 if not doc.name:
198 # hack! if name is null, it could cause problems with !=
199 doc.name = "New "+doc.doctype
200
201 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
Nabin Haitd53c2c02018-07-30 20:16:48 +0530202 "employee": doc.get("employee"),
Jamsheer0e2cc552018-05-08 11:48:25 +0530203 "from_date": from_date,
204 "to_date": to_date,
205 "name": doc.name,
206 "company": company
207 }, as_dict = 1)
208
209 if overlap_doc:
deepeshgarg00778b273a2018-10-31 18:12:03 +0530210 if doc.get("employee"):
211 exists_for = doc.employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530212 if company:
213 exists_for = company
214 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
215
216def get_doc_condition(doctype):
217 if doctype == "Compensatory Leave Request":
218 return "and employee = %(employee)s and docstatus < 2 \
219 and (work_from_date between %(from_date)s and %(to_date)s \
220 or work_end_date between %(from_date)s and %(to_date)s \
221 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
222 elif doctype == "Leave Period":
223 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
224 or to_date between %(from_date)s and %(to_date)s \
225 or (from_date < %(from_date)s and to_date > %(to_date)s))"
226
227def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
228 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
229 formatdate(from_date), formatdate(to_date)) \
Rushabh Mehta542bc012020-11-18 15:00:34 +0530230 + """ <b><a href="/app/Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
Jamsheer0e2cc552018-05-08 11:48:25 +0530231 + _(") for {0}").format(exists_for)
232 frappe.throw(msg)
233
Nabin Hait58ee6c12020-04-26 17:45:57 +0530234def validate_duplicate_exemption_for_payroll_period(doctype, docname, payroll_period, employee):
235 existing_record = frappe.db.exists(doctype, {
236 "payroll_period": payroll_period,
237 "employee": employee,
238 'docstatus': ['<', 2],
239 'name': ['!=', docname]
240 })
241 if existing_record:
242 frappe.throw(_("{0} already exists for employee {1} and period {2}")
243 .format(doctype, employee, payroll_period), DuplicateDeclarationError)
244
Ranjith5a8e6422018-05-10 15:06:49 +0530245def validate_tax_declaration(declarations):
246 subcategories = []
Nabin Hait04e7bf42019-04-25 18:44:10 +0530247 for d in declarations:
248 if d.exemption_sub_category in subcategories:
249 frappe.throw(_("More than one selection for {0} not allowed").format(d.exemption_sub_category))
250 subcategories.append(d.exemption_sub_category)
251
252def get_total_exemption_amount(declarations):
Nabin Hait04e7bf42019-04-25 18:44:10 +0530253 exemptions = frappe._dict()
254 for d in declarations:
255 exemptions.setdefault(d.exemption_category, frappe._dict())
256 category_max_amount = exemptions.get(d.exemption_category).max_amount
257 if not category_max_amount:
258 category_max_amount = frappe.db.get_value("Employee Tax Exemption Category", d.exemption_category, "max_amount")
259 exemptions.get(d.exemption_category).max_amount = category_max_amount
260 sub_category_exemption_amount = d.max_amount \
261 if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount
262
263 exemptions.get(d.exemption_category).setdefault("total_exemption_amount", 0.0)
264 exemptions.get(d.exemption_category).total_exemption_amount += flt(sub_category_exemption_amount)
265
266 if category_max_amount and exemptions.get(d.exemption_category).total_exemption_amount > category_max_amount:
267 exemptions.get(d.exemption_category).total_exemption_amount = category_max_amount
268
269 total_exemption_amount = sum([flt(d.total_exemption_amount) for d in exemptions.values()])
270 return total_exemption_amount
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530271
Jamsheer0e2cc552018-05-08 11:48:25 +0530272def get_leave_period(from_date, to_date, company):
273 leave_period = frappe.db.sql("""
274 select name, from_date, to_date
275 from `tabLeave Period`
276 where company=%(company)s and is_active=1
277 and (from_date between %(from_date)s and %(to_date)s
278 or to_date between %(from_date)s and %(to_date)s
279 or (from_date < %(from_date)s and to_date > %(to_date)s))
280 """, {
281 "from_date": from_date,
282 "to_date": to_date,
283 "company": company
284 }, as_dict=1)
285
286 if leave_period:
287 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530288
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530289def generate_leave_encashment():
290 ''' Generates a draft leave encashment on allocation expiry '''
291 from erpnext.hr.doctype.leave_encashment.leave_encashment import create_leave_encashment
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530292
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530293 if frappe.db.get_single_value('HR Settings', 'auto_leave_encashment'):
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530294 leave_type = frappe.get_all('Leave Type', filters={'allow_encashment': 1}, fields=['name'])
295 leave_type=[l['name'] for l in leave_type]
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530296
297 leave_allocation = frappe.get_all("Leave Allocation", filters={
298 'to_date': add_days(today(), -1),
299 'leave_type': ('in', leave_type)
300 }, fields=['employee', 'leave_period', 'leave_type', 'to_date', 'total_leaves_allocated', 'new_leaves_allocated'])
301
302 create_leave_encashment(leave_allocation=leave_allocation)
303
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530304def allocate_earned_leaves():
305 '''Allocate earned leaves to Employees'''
Anurag Mishra755b7732020-11-25 16:05:17 +0530306 e_leave_types = get_earned_leaves()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530307 today = getdate()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530308
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530309 for e_leave_type in e_leave_types:
Anurag Mishra755b7732020-11-25 16:05:17 +0530310
311 leave_allocations = get_leave_allocations(today, e_leave_type.name)
312
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530313 for allocation in leave_allocations:
Anurag Mishra755b7732020-11-25 16:05:17 +0530314
315 if not allocation.leave_policy_assignment and not allocation.leave_policy:
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530316 continue
Anurag Mishra755b7732020-11-25 16:05:17 +0530317
318 leave_policy = allocation.leave_policy if allocation.leave_policy else frappe.db.get_value(
319 "Leave Policy Assignment", allocation.leave_policy_assignment, ["leave_policy"])
320
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530321 annual_allocation = frappe.db.get_value("Leave Policy Detail", filters={
Anurag Mishra755b7732020-11-25 16:05:17 +0530322 'parent': leave_policy,
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530323 'leave_type': e_leave_type.name
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530324 }, fieldname=['annual_allocation'])
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530325
Anurag Mishra755b7732020-11-25 16:05:17 +0530326 from_date=allocation.from_date
Mangesh-Khairnar5d5f5b42020-02-20 13:25:55 +0530327
Anurag Mishra755b7732020-11-25 16:05:17 +0530328 if e_leave_type.based_on_date_of_joining_date:
329 from_date = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530330
Anurag Mishra755b7732020-11-25 16:05:17 +0530331 if check_effective_date(from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.based_on_date_of_joining_date):
332 update_previous_leave_allocation(allocation, annual_allocation, e_leave_type)
333
334def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type):
Nabin Hait190106a2021-03-02 13:38:14 +0530335 earned_leaves = get_monthly_earned_leave(annual_allocation, e_leave_type.earned_leave_frequency, e_leave_type.rounding)
Anurag Mishra755b7732020-11-25 16:05:17 +0530336
337 allocation = frappe.get_doc('Leave Allocation', allocation.name)
338 new_allocation = flt(allocation.total_leaves_allocated) + flt(earned_leaves)
339
340 if new_allocation > e_leave_type.max_leaves_allowed and e_leave_type.max_leaves_allowed > 0:
341 new_allocation = e_leave_type.max_leaves_allowed
342
343 if new_allocation != allocation.total_leaves_allocated:
344 allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
345 today_date = today()
346 create_additional_leave_ledger_entry(allocation, earned_leaves, today_date)
347
Nabin Hait190106a2021-03-02 13:38:14 +0530348def get_monthly_earned_leave(annual_leaves, frequency, rounding):
349 earned_leaves = 0.0
350 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 6, "Quarterly": 4, "Monthly": 12}
351 if annual_leaves:
352 earned_leaves = flt(annual_leaves) / divide_by_frequency[frequency]
353 if rounding:
354 if rounding == "0.25":
355 earned_leaves = round(earned_leaves * 4) / 4
356 elif rounding == "0.5":
357 earned_leaves = round(earned_leaves * 2) / 2
358 else:
359 earned_leaves = round(earned_leaves)
360
361 return earned_leaves
362
Anurag Mishra755b7732020-11-25 16:05:17 +0530363
364def get_leave_allocations(date, leave_type):
365 return frappe.db.sql("""select name, employee, from_date, to_date, leave_policy_assignment, leave_policy
366 from `tabLeave Allocation`
367 where
368 %s between from_date and to_date and docstatus=1
369 and leave_type=%s""",
370 (date, leave_type), as_dict=1)
371
372
373def get_earned_leaves():
374 return frappe.get_all("Leave Type",
375 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding", "based_on_date_of_joining"],
376 filters={'is_earned_leave' : 1})
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530377
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530378def create_additional_leave_ledger_entry(allocation, leaves, date):
379 ''' Create leave ledger entry for leave types '''
380 allocation.new_leaves_allocated = leaves
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530381 allocation.from_date = date
Mangesh-Khairnar5cbe6162019-08-08 17:06:15 +0530382 allocation.unused_leaves = 0
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530383 allocation.create_leave_ledger_entry()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530384
Anurag Mishra755b7732020-11-25 16:05:17 +0530385def check_effective_date(from_date, to_date, frequency, based_on_date_of_joining_date):
386 import calendar
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530387 from dateutil import relativedelta
Anurag Mishra755b7732020-11-25 16:05:17 +0530388
389 from_date = get_datetime(from_date)
390 to_date = get_datetime(to_date)
391 rd = relativedelta.relativedelta(to_date, from_date)
392 #last day of month
393 last_day = calendar.monthrange(to_date.year, to_date.month)[1]
394
395 if (from_date.day == to_date.day and based_on_date_of_joining_date) or (not based_on_date_of_joining_date and to_date.day == last_day):
396 if frequency == "Monthly":
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530397 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530398 elif frequency == "Quarterly" and rd.months % 3:
Joyce Babu3d012132019-03-06 13:04:45 +0530399 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530400 elif frequency == "Half-Yearly" and rd.months % 6:
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530401 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530402 elif frequency == "Yearly" and rd.months % 12:
403 return True
404
405 if frappe.flags.in_test:
406 return True
407
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530408 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530409
Anurag Mishra755b7732020-11-25 16:05:17 +0530410
Ranjith155ecc12018-05-30 13:37:15 +0530411def get_salary_assignment(employee, date):
412 assignment = frappe.db.sql("""
413 select * from `tabSalary Structure Assignment`
414 where employee=%(employee)s
415 and docstatus = 1
Ranjith Kurungadamb4ad3c32018-06-25 10:29:54 +0530416 and %(on_date)s >= from_date order by from_date desc limit 1""", {
Ranjith155ecc12018-05-30 13:37:15 +0530417 'employee': employee,
418 'on_date': date,
419 }, as_dict=1)
420 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530421
Jamsheer8d66f1e2018-06-12 11:30:59 +0530422def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
423 total_given_benefit_amount = 0
424 query = """
425 select sum(sd.amount) as 'total_amount'
426 from `tabSalary Slip` ss, `tabSalary Detail` sd
427 where ss.employee=%(employee)s
428 and ss.docstatus = 1 and ss.name = sd.parent
429 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
430 and sd.parenttype = "Salary Slip"
431 and (ss.start_date between %(start_date)s and %(end_date)s
432 or ss.end_date between %(start_date)s and %(end_date)s
433 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
434 """
435
436 if component:
437 query += "and sd.salary_component = %(component)s"
438
439 sum_of_given_benefit = frappe.db.sql(query, {
440 'employee': employee,
441 'start_date': payroll_period.start_date,
442 'end_date': payroll_period.end_date,
443 'component': component
444 }, as_dict=True)
445
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530446 if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0:
Jamsheer8d66f1e2018-06-12 11:30:59 +0530447 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
448 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530449
450def get_holidays_for_employee(employee, start_date, end_date):
451 holiday_list = get_holiday_list_for_employee(employee)
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530452
Jamsheercc25eb02018-06-13 15:14:24 +0530453 holidays = frappe.db.sql_list('''select holiday_date from `tabHoliday`
454 where
455 parent=%(holiday_list)s
456 and holiday_date >= %(start_date)s
457 and holiday_date <= %(end_date)s''', {
458 "holiday_list": holiday_list,
459 "start_date": start_date,
460 "end_date": end_date
461 })
462
463 holidays = [cstr(i) for i in holidays]
464
465 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530466
467@erpnext.allow_regional
468def calculate_annual_eligible_hra_exemption(doc):
469 # Don't delete this method, used for localization
470 # Indian HRA Exemption Calculation
471 return {}
472
473@erpnext.allow_regional
474def calculate_hra_exemption_for_period(doc):
475 # Don't delete this method, used for localization
476 # Indian HRA Exemption Calculation
477 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530478
479def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
480 total_claimed_amount = 0
481 query = """
482 select sum(claimed_amount) as 'total_amount'
483 from `tabEmployee Benefit Claim`
484 where employee=%(employee)s
485 and docstatus = 1
486 and (claim_date between %(start_date)s and %(end_date)s)
487 """
488 if non_pro_rata:
489 query += "and pay_against_benefit_claim = 1"
490 if component:
491 query += "and earning_component = %(component)s"
492
493 sum_of_claimed_amount = frappe.db.sql(query, {
494 'employee': employee,
495 'start_date': payroll_period.start_date,
496 'end_date': payroll_period.end_date,
497 'component': component
498 }, as_dict=True)
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530499 if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0:
Jamsheer55a2f4d2018-06-20 11:04:21 +0530500 total_claimed_amount = sum_of_claimed_amount[0].total_amount
501 return total_claimed_amount
Anurag Mishra755b7732020-11-25 16:05:17 +0530502
503def grant_leaves_automatically():
504 automatically_allocate_leaves_based_on_leave_policy = frappe.db.get_singles_value("HR Settings", "automatically_allocate_leaves_based_on_leave_policy")
505 if automatically_allocate_leaves_based_on_leave_policy:
506 lpa = frappe.db.get_all("Leave Policy Assignment", filters={"effective_from": getdate(), "docstatus": 1, "leaves_allocated":0})
507 for assignment in lpa:
508 frappe.get_doc("Leave Policy Assignment", assignment.name).grant_leave_alloc_for_employee()
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530509
510def share_doc_with_approver(doc, user):
511 # if approver does not have permissions, share
512 if not frappe.has_permission(doc=doc, ptype="submit", user=user):
Rucha Mahabal8c055b52021-04-04 18:45:06 +0530513 frappe.share.add(doc.doctype, doc.name, user, submit=1,
514 flags={"ignore_share_permission": True})
515
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530516 frappe.msgprint(_("Shared with the user {0} with {1} access").format(
517 user, frappe.bold("submit"), alert=True))
518
519 # remove shared doc if approver changes
520 doc_before_save = doc.get_doc_before_save()
521 if doc_before_save:
522 approvers = {
523 "Leave Application": "leave_approver",
524 "Expense Claim": "expense_approver",
525 "Shift Request": "approver"
526 }
527
528 approver = approvers.get(doc.doctype)
529 if doc_before_save.get(approver) != doc.get(approver):
530 frappe.share.remove(doc.doctype, doc.name, doc_before_save.get(approver))