blob: 0c4c1cafb07e0b90cdbf99b2ea97f99b3fd19c0e [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
Manas Solankib6988462018-05-10 18:07:20 +053035 project = frappe.get_doc({
36 "doctype": "Project",
37 "project_name": project_name,
38 "expected_start_date": self.date_of_joining if self.doctype == "Employee Onboarding" else self.resignation_letter_date,
39 "department": self.department,
40 "company": self.company
41 }).insert(ignore_permissions=True)
42 self.db_set("project", project.name)
Shreya5c6ade42018-06-20 15:48:27 +053043 self.db_set("boarding_status", "Pending")
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053044 self.reload()
45 self.create_task_and_notify_user()
Manas Solankib6988462018-05-10 18:07:20 +053046
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053047 def create_task_and_notify_user(self):
Manas Solankib6988462018-05-10 18:07:20 +053048 # create the task for the given project and assign to the concerned person
49 for activity in self.activities:
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053050 if activity.task:
51 continue
52
Manas Solankib6988462018-05-10 18:07:20 +053053 task = frappe.get_doc({
Rohandb2d1962021-03-09 21:03:45 +053054 "doctype": "Task",
55 "project": self.project,
56 "subject": activity.activity_name + " : " + self.employee_name,
57 "description": activity.description,
58 "department": self.department,
59 "company": self.company,
60 "task_weight": activity.task_weight
61 }).insert(ignore_permissions=True)
Manas Solankib6988462018-05-10 18:07:20 +053062 activity.db_set("task", task.name)
Rohandb2d1962021-03-09 21:03:45 +053063
Manas Solankib6988462018-05-10 18:07:20 +053064 users = [activity.user] if activity.user else []
65 if activity.role:
Rohandb2d1962021-03-09 21:03:45 +053066 user_list = frappe.db.sql_list('''
67 SELECT
68 DISTINCT(has_role.parent)
69 FROM
70 `tabHas Role` has_role
71 LEFT JOIN `tabUser` user
72 ON has_role.parent = user.name
73 WHERE
74 has_role.parenttype = 'User'
75 AND user.enabled = 1
76 AND has_role.role = %s
77 ''', activity.role)
78 users = unique(users + user_list)
Manas Solankib6988462018-05-10 18:07:20 +053079
Anurag Mishraadd6bf32019-01-04 11:36:30 +053080 if "Administrator" in users:
81 users.remove("Administrator")
82
Manas Solankib6988462018-05-10 18:07:20 +053083 # assign the task the users
84 if users:
Rohandb2d1962021-03-09 21:03:45 +053085 self.assign_task_to_users(task, users)
Manas Solankib6988462018-05-10 18:07:20 +053086
87 def assign_task_to_users(self, task, users):
88 for user in users:
89 args = {
Anurag Mishra225802e2020-06-04 14:11:18 +053090 'assign_to': [user],
91 'doctype': task.doctype,
92 'name': task.name,
93 'description': task.description or task.subject,
94 'notify': self.notify_users_by_email
Manas Solankib6988462018-05-10 18:07:20 +053095 }
96 assign_to.add(args)
97
98 def on_cancel(self):
99 # delete task project
100 for task in frappe.get_all("Task", filters={"project": self.project}):
Zarrar9a3b7852018-07-11 14:34:55 +0530101 frappe.delete_doc("Task", task.name, force=1)
102 frappe.delete_doc("Project", self.project, force=1)
Manas Solankib6988462018-05-10 18:07:20 +0530103 self.db_set('project', '')
104 for activity in self.activities:
105 activity.db_set("task", "")
106
107
108@frappe.whitelist()
109def get_onboarding_details(parent, parenttype):
Nabin Hait01b2a652018-08-28 14:09:27 +0530110 return frappe.get_all("Employee Boarding Activity",
Himanshu4cb1a1e2019-06-05 10:26:01 +0530111 fields=["activity_name", "role", "user", "required_for_employee_creation", "description", "task_weight"],
Manas Solankib6988462018-05-10 18:07:20 +0530112 filters={"parent": parent, "parenttype": parenttype},
113 order_by= "idx")
Anand Doshi60666a22013-04-12 20:19:53 +0530114
Shreya5c6ade42018-06-20 15:48:27 +0530115@frappe.whitelist()
116def get_boarding_status(project):
117 status = 'Pending'
118 if project:
119 doc = frappe.get_doc('Project', project)
120 if flt(doc.percent_complete) > 0.0 and flt(doc.percent_complete) < 100.0:
121 status = 'In Process'
122 elif flt(doc.percent_complete) == 100.0:
123 status = 'Completed'
124 return status
125
Anand Doshic280d062014-05-30 14:43:36 +0530126def set_employee_name(doc):
127 if doc.employee and not doc.employee_name:
128 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +0530129
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530130def update_employee(employee, details, date=None, cancel=False):
131 internal_work_history = {}
Manas Solankib6988462018-05-10 18:07:20 +0530132 for item in details:
133 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
134 new_data = item.new if not cancel else item.current
135 if fieldtype == "Date" and new_data:
136 new_data = getdate(new_data)
137 elif fieldtype =="Datetime" and new_data:
138 new_data = get_datetime(new_data)
139 setattr(employee, item.fieldname, new_data)
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530140 if item.fieldname in ["department", "designation", "branch"]:
141 internal_work_history[item.fieldname] = item.new
142 if internal_work_history and not cancel:
143 internal_work_history["from_date"] = date
144 employee.append("internal_work_history", internal_work_history)
Manas Solankib6988462018-05-10 18:07:20 +0530145 return employee
146
Ranjithfddfffd2018-05-05 13:27:26 +0530147@frappe.whitelist()
148def get_employee_fields_label():
149 fields = []
150 for df in frappe.get_meta("Employee").get("fields"):
Ranjith Kurungadamc1030a32018-06-20 12:42:58 +0530151 if df.fieldname in ["salutation", "user_id", "employee_number", "employment_type",
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530152 "holiday_list", "branch", "department", "designation", "grade",
153 "notice_number_of_days", "reports_to", "leave_policy", "company_email"]:
154 fields.append({"value": df.fieldname, "label": df.label})
Ranjithfddfffd2018-05-05 13:27:26 +0530155 return fields
156
157@frappe.whitelist()
158def get_employee_field_property(employee, fieldname):
159 if employee and fieldname:
160 field = frappe.get_meta("Employee").get_field(fieldname)
161 value = frappe.db.get_value("Employee", employee, fieldname)
162 options = field.options
163 if field.fieldtype == "Date":
164 value = formatdate(value)
165 elif field.fieldtype == "Datetime":
166 value = format_datetime(value)
167 return {
168 "value" : value,
169 "datatype" : field.fieldtype,
170 "label" : field.label,
171 "options" : options
172 }
173 else:
174 return False
175
Jamsheer0e2cc552018-05-08 11:48:25 +0530176def validate_dates(doc, from_date, to_date):
177 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
178 if getdate(from_date) > getdate(to_date):
179 frappe.throw(_("To date can not be less than from date"))
180 elif getdate(from_date) > getdate(nowdate()):
181 frappe.throw(_("Future dates not allowed"))
182 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
183 frappe.throw(_("From date can not be less than employee's joining date"))
184 elif relieving_date and getdate(to_date) > getdate(relieving_date):
185 frappe.throw(_("To date can not greater than employee's relieving date"))
186
187def validate_overlap(doc, from_date, to_date, company = None):
188 query = """
189 select name
190 from `tab{0}`
191 where name != %(name)s
192 """
193 query += get_doc_condition(doc.doctype)
194
195 if not doc.name:
196 # hack! if name is null, it could cause problems with !=
197 doc.name = "New "+doc.doctype
198
199 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
Nabin Haitd53c2c02018-07-30 20:16:48 +0530200 "employee": doc.get("employee"),
Jamsheer0e2cc552018-05-08 11:48:25 +0530201 "from_date": from_date,
202 "to_date": to_date,
203 "name": doc.name,
204 "company": company
205 }, as_dict = 1)
206
207 if overlap_doc:
deepeshgarg00778b273a2018-10-31 18:12:03 +0530208 if doc.get("employee"):
209 exists_for = doc.employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530210 if company:
211 exists_for = company
212 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
213
214def get_doc_condition(doctype):
215 if doctype == "Compensatory Leave Request":
216 return "and employee = %(employee)s and docstatus < 2 \
217 and (work_from_date between %(from_date)s and %(to_date)s \
218 or work_end_date between %(from_date)s and %(to_date)s \
219 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
220 elif doctype == "Leave Period":
221 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
222 or to_date between %(from_date)s and %(to_date)s \
223 or (from_date < %(from_date)s and to_date > %(to_date)s))"
224
225def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
226 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
227 formatdate(from_date), formatdate(to_date)) \
Rushabh Mehta542bc012020-11-18 15:00:34 +0530228 + """ <b><a href="/app/Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
Jamsheer0e2cc552018-05-08 11:48:25 +0530229 + _(") for {0}").format(exists_for)
230 frappe.throw(msg)
231
Nabin Hait58ee6c12020-04-26 17:45:57 +0530232def validate_duplicate_exemption_for_payroll_period(doctype, docname, payroll_period, employee):
233 existing_record = frappe.db.exists(doctype, {
234 "payroll_period": payroll_period,
235 "employee": employee,
236 'docstatus': ['<', 2],
237 'name': ['!=', docname]
238 })
239 if existing_record:
240 frappe.throw(_("{0} already exists for employee {1} and period {2}")
241 .format(doctype, employee, payroll_period), DuplicateDeclarationError)
242
Ranjith5a8e6422018-05-10 15:06:49 +0530243def validate_tax_declaration(declarations):
244 subcategories = []
Nabin Hait04e7bf42019-04-25 18:44:10 +0530245 for d in declarations:
246 if d.exemption_sub_category in subcategories:
247 frappe.throw(_("More than one selection for {0} not allowed").format(d.exemption_sub_category))
248 subcategories.append(d.exemption_sub_category)
249
250def get_total_exemption_amount(declarations):
Nabin Hait04e7bf42019-04-25 18:44:10 +0530251 exemptions = frappe._dict()
252 for d in declarations:
253 exemptions.setdefault(d.exemption_category, frappe._dict())
254 category_max_amount = exemptions.get(d.exemption_category).max_amount
255 if not category_max_amount:
256 category_max_amount = frappe.db.get_value("Employee Tax Exemption Category", d.exemption_category, "max_amount")
257 exemptions.get(d.exemption_category).max_amount = category_max_amount
258 sub_category_exemption_amount = d.max_amount \
259 if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount
260
261 exemptions.get(d.exemption_category).setdefault("total_exemption_amount", 0.0)
262 exemptions.get(d.exemption_category).total_exemption_amount += flt(sub_category_exemption_amount)
263
264 if category_max_amount and exemptions.get(d.exemption_category).total_exemption_amount > category_max_amount:
265 exemptions.get(d.exemption_category).total_exemption_amount = category_max_amount
266
267 total_exemption_amount = sum([flt(d.total_exemption_amount) for d in exemptions.values()])
268 return total_exemption_amount
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530269
Jamsheer0e2cc552018-05-08 11:48:25 +0530270def get_leave_period(from_date, to_date, company):
271 leave_period = frappe.db.sql("""
272 select name, from_date, to_date
273 from `tabLeave Period`
274 where company=%(company)s and is_active=1
275 and (from_date between %(from_date)s and %(to_date)s
276 or to_date between %(from_date)s and %(to_date)s
277 or (from_date < %(from_date)s and to_date > %(to_date)s))
278 """, {
279 "from_date": from_date,
280 "to_date": to_date,
281 "company": company
282 }, as_dict=1)
283
284 if leave_period:
285 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530286
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530287def generate_leave_encashment():
288 ''' Generates a draft leave encashment on allocation expiry '''
289 from erpnext.hr.doctype.leave_encashment.leave_encashment import create_leave_encashment
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530290
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530291 if frappe.db.get_single_value('HR Settings', 'auto_leave_encashment'):
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530292 leave_type = frappe.get_all('Leave Type', filters={'allow_encashment': 1}, fields=['name'])
293 leave_type=[l['name'] for l in leave_type]
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530294
295 leave_allocation = frappe.get_all("Leave Allocation", filters={
296 'to_date': add_days(today(), -1),
297 'leave_type': ('in', leave_type)
298 }, fields=['employee', 'leave_period', 'leave_type', 'to_date', 'total_leaves_allocated', 'new_leaves_allocated'])
299
300 create_leave_encashment(leave_allocation=leave_allocation)
301
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530302def allocate_earned_leaves():
303 '''Allocate earned leaves to Employees'''
Anurag Mishra755b7732020-11-25 16:05:17 +0530304 e_leave_types = get_earned_leaves()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530305 today = getdate()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530306
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530307 for e_leave_type in e_leave_types:
Anurag Mishra755b7732020-11-25 16:05:17 +0530308
309 leave_allocations = get_leave_allocations(today, e_leave_type.name)
310
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530311 for allocation in leave_allocations:
Anurag Mishra755b7732020-11-25 16:05:17 +0530312
313 if not allocation.leave_policy_assignment and not allocation.leave_policy:
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530314 continue
Anurag Mishra755b7732020-11-25 16:05:17 +0530315
316 leave_policy = allocation.leave_policy if allocation.leave_policy else frappe.db.get_value(
317 "Leave Policy Assignment", allocation.leave_policy_assignment, ["leave_policy"])
318
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530319 annual_allocation = frappe.db.get_value("Leave Policy Detail", filters={
Anurag Mishra755b7732020-11-25 16:05:17 +0530320 'parent': leave_policy,
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530321 'leave_type': e_leave_type.name
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530322 }, fieldname=['annual_allocation'])
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530323
Anurag Mishra755b7732020-11-25 16:05:17 +0530324 from_date=allocation.from_date
Mangesh-Khairnar5d5f5b42020-02-20 13:25:55 +0530325
Anurag Mishra755b7732020-11-25 16:05:17 +0530326 if e_leave_type.based_on_date_of_joining_date:
327 from_date = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530328
Anurag Mishra755b7732020-11-25 16:05:17 +0530329 if check_effective_date(from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.based_on_date_of_joining_date):
330 update_previous_leave_allocation(allocation, annual_allocation, e_leave_type)
331
332def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type):
Nabin Hait190106a2021-03-02 13:38:14 +0530333 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 +0530334
335 allocation = frappe.get_doc('Leave Allocation', allocation.name)
336 new_allocation = flt(allocation.total_leaves_allocated) + flt(earned_leaves)
337
338 if new_allocation > e_leave_type.max_leaves_allowed and e_leave_type.max_leaves_allowed > 0:
339 new_allocation = e_leave_type.max_leaves_allowed
340
341 if new_allocation != allocation.total_leaves_allocated:
342 allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
343 today_date = today()
344 create_additional_leave_ledger_entry(allocation, earned_leaves, today_date)
345
Nabin Hait190106a2021-03-02 13:38:14 +0530346def get_monthly_earned_leave(annual_leaves, frequency, rounding):
347 earned_leaves = 0.0
348 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 6, "Quarterly": 4, "Monthly": 12}
349 if annual_leaves:
350 earned_leaves = flt(annual_leaves) / divide_by_frequency[frequency]
351 if rounding:
352 if rounding == "0.25":
353 earned_leaves = round(earned_leaves * 4) / 4
354 elif rounding == "0.5":
355 earned_leaves = round(earned_leaves * 2) / 2
356 else:
357 earned_leaves = round(earned_leaves)
358
359 return earned_leaves
360
Anurag Mishra755b7732020-11-25 16:05:17 +0530361
362def get_leave_allocations(date, leave_type):
363 return frappe.db.sql("""select name, employee, from_date, to_date, leave_policy_assignment, leave_policy
364 from `tabLeave Allocation`
365 where
366 %s between from_date and to_date and docstatus=1
367 and leave_type=%s""",
368 (date, leave_type), as_dict=1)
369
370
371def get_earned_leaves():
372 return frappe.get_all("Leave Type",
373 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding", "based_on_date_of_joining"],
374 filters={'is_earned_leave' : 1})
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530375
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530376def create_additional_leave_ledger_entry(allocation, leaves, date):
377 ''' Create leave ledger entry for leave types '''
378 allocation.new_leaves_allocated = leaves
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530379 allocation.from_date = date
Mangesh-Khairnar5cbe6162019-08-08 17:06:15 +0530380 allocation.unused_leaves = 0
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530381 allocation.create_leave_ledger_entry()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530382
Anurag Mishra755b7732020-11-25 16:05:17 +0530383def check_effective_date(from_date, to_date, frequency, based_on_date_of_joining_date):
384 import calendar
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530385 from dateutil import relativedelta
Anurag Mishra755b7732020-11-25 16:05:17 +0530386
387 from_date = get_datetime(from_date)
388 to_date = get_datetime(to_date)
389 rd = relativedelta.relativedelta(to_date, from_date)
390 #last day of month
391 last_day = calendar.monthrange(to_date.year, to_date.month)[1]
392
393 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):
394 if frequency == "Monthly":
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530395 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530396 elif frequency == "Quarterly" and rd.months % 3:
Joyce Babu3d012132019-03-06 13:04:45 +0530397 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530398 elif frequency == "Half-Yearly" and rd.months % 6:
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530399 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530400 elif frequency == "Yearly" and rd.months % 12:
401 return True
402
403 if frappe.flags.in_test:
404 return True
405
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530406 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530407
Anurag Mishra755b7732020-11-25 16:05:17 +0530408
Ranjith155ecc12018-05-30 13:37:15 +0530409def get_salary_assignment(employee, date):
410 assignment = frappe.db.sql("""
411 select * from `tabSalary Structure Assignment`
412 where employee=%(employee)s
413 and docstatus = 1
Ranjith Kurungadamb4ad3c32018-06-25 10:29:54 +0530414 and %(on_date)s >= from_date order by from_date desc limit 1""", {
Ranjith155ecc12018-05-30 13:37:15 +0530415 'employee': employee,
416 'on_date': date,
417 }, as_dict=1)
418 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530419
Jamsheer8d66f1e2018-06-12 11:30:59 +0530420def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
421 total_given_benefit_amount = 0
422 query = """
423 select sum(sd.amount) as 'total_amount'
424 from `tabSalary Slip` ss, `tabSalary Detail` sd
425 where ss.employee=%(employee)s
426 and ss.docstatus = 1 and ss.name = sd.parent
427 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
428 and sd.parenttype = "Salary Slip"
429 and (ss.start_date between %(start_date)s and %(end_date)s
430 or ss.end_date between %(start_date)s and %(end_date)s
431 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
432 """
433
434 if component:
435 query += "and sd.salary_component = %(component)s"
436
437 sum_of_given_benefit = frappe.db.sql(query, {
438 'employee': employee,
439 'start_date': payroll_period.start_date,
440 'end_date': payroll_period.end_date,
441 'component': component
442 }, as_dict=True)
443
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530444 if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0:
Jamsheer8d66f1e2018-06-12 11:30:59 +0530445 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
446 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530447
448def get_holidays_for_employee(employee, start_date, end_date):
449 holiday_list = get_holiday_list_for_employee(employee)
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530450
Jamsheercc25eb02018-06-13 15:14:24 +0530451 holidays = frappe.db.sql_list('''select holiday_date from `tabHoliday`
452 where
453 parent=%(holiday_list)s
454 and holiday_date >= %(start_date)s
455 and holiday_date <= %(end_date)s''', {
456 "holiday_list": holiday_list,
457 "start_date": start_date,
458 "end_date": end_date
459 })
460
461 holidays = [cstr(i) for i in holidays]
462
463 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530464
465@erpnext.allow_regional
466def calculate_annual_eligible_hra_exemption(doc):
467 # Don't delete this method, used for localization
468 # Indian HRA Exemption Calculation
469 return {}
470
471@erpnext.allow_regional
472def calculate_hra_exemption_for_period(doc):
473 # Don't delete this method, used for localization
474 # Indian HRA Exemption Calculation
475 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530476
477def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
478 total_claimed_amount = 0
479 query = """
480 select sum(claimed_amount) as 'total_amount'
481 from `tabEmployee Benefit Claim`
482 where employee=%(employee)s
483 and docstatus = 1
484 and (claim_date between %(start_date)s and %(end_date)s)
485 """
486 if non_pro_rata:
487 query += "and pay_against_benefit_claim = 1"
488 if component:
489 query += "and earning_component = %(component)s"
490
491 sum_of_claimed_amount = frappe.db.sql(query, {
492 'employee': employee,
493 'start_date': payroll_period.start_date,
494 'end_date': payroll_period.end_date,
495 'component': component
496 }, as_dict=True)
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530497 if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0:
Jamsheer55a2f4d2018-06-20 11:04:21 +0530498 total_claimed_amount = sum_of_claimed_amount[0].total_amount
499 return total_claimed_amount
Anurag Mishra755b7732020-11-25 16:05:17 +0530500
501def grant_leaves_automatically():
502 automatically_allocate_leaves_based_on_leave_policy = frappe.db.get_singles_value("HR Settings", "automatically_allocate_leaves_based_on_leave_policy")
503 if automatically_allocate_leaves_based_on_leave_policy:
504 lpa = frappe.db.get_all("Leave Policy Assignment", filters={"effective_from": getdate(), "docstatus": 1, "leaves_allocated":0})
505 for assignment in lpa:
506 frappe.get_doc("Leave Policy Assignment", assignment.name).grant_leave_alloc_for_employee()