blob: ebb17343471cbb39489d59d128e0359929c17998 [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
Jannat Patel1175e062021-06-01 10:53:00 +0530272@frappe.whitelist()
Jamsheer0e2cc552018-05-08 11:48:25 +0530273def get_leave_period(from_date, to_date, company):
274 leave_period = frappe.db.sql("""
275 select name, from_date, to_date
276 from `tabLeave Period`
277 where company=%(company)s and is_active=1
278 and (from_date between %(from_date)s and %(to_date)s
279 or to_date between %(from_date)s and %(to_date)s
280 or (from_date < %(from_date)s and to_date > %(to_date)s))
281 """, {
282 "from_date": from_date,
283 "to_date": to_date,
284 "company": company
285 }, as_dict=1)
286
287 if leave_period:
288 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530289
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530290def generate_leave_encashment():
291 ''' Generates a draft leave encashment on allocation expiry '''
292 from erpnext.hr.doctype.leave_encashment.leave_encashment import create_leave_encashment
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530293
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530294 if frappe.db.get_single_value('HR Settings', 'auto_leave_encashment'):
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530295 leave_type = frappe.get_all('Leave Type', filters={'allow_encashment': 1}, fields=['name'])
296 leave_type=[l['name'] for l in leave_type]
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530297
298 leave_allocation = frappe.get_all("Leave Allocation", filters={
299 'to_date': add_days(today(), -1),
300 'leave_type': ('in', leave_type)
301 }, fields=['employee', 'leave_period', 'leave_type', 'to_date', 'total_leaves_allocated', 'new_leaves_allocated'])
302
303 create_leave_encashment(leave_allocation=leave_allocation)
304
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530305def allocate_earned_leaves():
306 '''Allocate earned leaves to Employees'''
Anurag Mishra755b7732020-11-25 16:05:17 +0530307 e_leave_types = get_earned_leaves()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530308 today = getdate()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530309
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530310 for e_leave_type in e_leave_types:
Anurag Mishra755b7732020-11-25 16:05:17 +0530311
312 leave_allocations = get_leave_allocations(today, e_leave_type.name)
313
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530314 for allocation in leave_allocations:
Anurag Mishra755b7732020-11-25 16:05:17 +0530315
316 if not allocation.leave_policy_assignment and not allocation.leave_policy:
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530317 continue
Anurag Mishra755b7732020-11-25 16:05:17 +0530318
319 leave_policy = allocation.leave_policy if allocation.leave_policy else frappe.db.get_value(
320 "Leave Policy Assignment", allocation.leave_policy_assignment, ["leave_policy"])
321
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530322 annual_allocation = frappe.db.get_value("Leave Policy Detail", filters={
Anurag Mishra755b7732020-11-25 16:05:17 +0530323 'parent': leave_policy,
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530324 'leave_type': e_leave_type.name
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530325 }, fieldname=['annual_allocation'])
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530326
Anurag Mishra755b7732020-11-25 16:05:17 +0530327 from_date=allocation.from_date
Mangesh-Khairnar5d5f5b42020-02-20 13:25:55 +0530328
Anurag Mishra755b7732020-11-25 16:05:17 +0530329 if e_leave_type.based_on_date_of_joining_date:
330 from_date = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530331
Anurag Mishra755b7732020-11-25 16:05:17 +0530332 if check_effective_date(from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.based_on_date_of_joining_date):
333 update_previous_leave_allocation(allocation, annual_allocation, e_leave_type)
334
335def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type):
Nabin Hait190106a2021-03-02 13:38:14 +0530336 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 +0530337
338 allocation = frappe.get_doc('Leave Allocation', allocation.name)
339 new_allocation = flt(allocation.total_leaves_allocated) + flt(earned_leaves)
340
341 if new_allocation > e_leave_type.max_leaves_allowed and e_leave_type.max_leaves_allowed > 0:
342 new_allocation = e_leave_type.max_leaves_allowed
343
344 if new_allocation != allocation.total_leaves_allocated:
345 allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
346 today_date = today()
347 create_additional_leave_ledger_entry(allocation, earned_leaves, today_date)
348
Nabin Hait190106a2021-03-02 13:38:14 +0530349def get_monthly_earned_leave(annual_leaves, frequency, rounding):
350 earned_leaves = 0.0
351 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 6, "Quarterly": 4, "Monthly": 12}
352 if annual_leaves:
353 earned_leaves = flt(annual_leaves) / divide_by_frequency[frequency]
354 if rounding:
355 if rounding == "0.25":
356 earned_leaves = round(earned_leaves * 4) / 4
357 elif rounding == "0.5":
358 earned_leaves = round(earned_leaves * 2) / 2
359 else:
360 earned_leaves = round(earned_leaves)
361
362 return earned_leaves
363
Anurag Mishra755b7732020-11-25 16:05:17 +0530364
365def get_leave_allocations(date, leave_type):
366 return frappe.db.sql("""select name, employee, from_date, to_date, leave_policy_assignment, leave_policy
367 from `tabLeave Allocation`
368 where
369 %s between from_date and to_date and docstatus=1
370 and leave_type=%s""",
371 (date, leave_type), as_dict=1)
372
373
374def get_earned_leaves():
375 return frappe.get_all("Leave Type",
376 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding", "based_on_date_of_joining"],
377 filters={'is_earned_leave' : 1})
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530378
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530379def create_additional_leave_ledger_entry(allocation, leaves, date):
380 ''' Create leave ledger entry for leave types '''
381 allocation.new_leaves_allocated = leaves
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530382 allocation.from_date = date
Mangesh-Khairnar5cbe6162019-08-08 17:06:15 +0530383 allocation.unused_leaves = 0
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530384 allocation.create_leave_ledger_entry()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530385
Anurag Mishra755b7732020-11-25 16:05:17 +0530386def check_effective_date(from_date, to_date, frequency, based_on_date_of_joining_date):
387 import calendar
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530388 from dateutil import relativedelta
Anurag Mishra755b7732020-11-25 16:05:17 +0530389
390 from_date = get_datetime(from_date)
391 to_date = get_datetime(to_date)
392 rd = relativedelta.relativedelta(to_date, from_date)
393 #last day of month
394 last_day = calendar.monthrange(to_date.year, to_date.month)[1]
395
396 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):
397 if frequency == "Monthly":
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530398 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530399 elif frequency == "Quarterly" and rd.months % 3:
Joyce Babu3d012132019-03-06 13:04:45 +0530400 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530401 elif frequency == "Half-Yearly" and rd.months % 6:
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530402 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530403 elif frequency == "Yearly" and rd.months % 12:
404 return True
405
406 if frappe.flags.in_test:
407 return True
408
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530409 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530410
Anurag Mishra755b7732020-11-25 16:05:17 +0530411
Ranjith155ecc12018-05-30 13:37:15 +0530412def get_salary_assignment(employee, date):
413 assignment = frappe.db.sql("""
414 select * from `tabSalary Structure Assignment`
415 where employee=%(employee)s
416 and docstatus = 1
Ranjith Kurungadamb4ad3c32018-06-25 10:29:54 +0530417 and %(on_date)s >= from_date order by from_date desc limit 1""", {
Ranjith155ecc12018-05-30 13:37:15 +0530418 'employee': employee,
419 'on_date': date,
420 }, as_dict=1)
421 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530422
Jamsheer8d66f1e2018-06-12 11:30:59 +0530423def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
424 total_given_benefit_amount = 0
425 query = """
426 select sum(sd.amount) as 'total_amount'
427 from `tabSalary Slip` ss, `tabSalary Detail` sd
428 where ss.employee=%(employee)s
429 and ss.docstatus = 1 and ss.name = sd.parent
430 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
431 and sd.parenttype = "Salary Slip"
432 and (ss.start_date between %(start_date)s and %(end_date)s
433 or ss.end_date between %(start_date)s and %(end_date)s
434 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
435 """
436
437 if component:
438 query += "and sd.salary_component = %(component)s"
439
440 sum_of_given_benefit = frappe.db.sql(query, {
441 'employee': employee,
442 'start_date': payroll_period.start_date,
443 'end_date': payroll_period.end_date,
444 'component': component
445 }, as_dict=True)
446
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530447 if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0:
Jamsheer8d66f1e2018-06-12 11:30:59 +0530448 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
449 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530450
451def get_holidays_for_employee(employee, start_date, end_date):
452 holiday_list = get_holiday_list_for_employee(employee)
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530453
Jamsheercc25eb02018-06-13 15:14:24 +0530454 holidays = frappe.db.sql_list('''select holiday_date from `tabHoliday`
455 where
456 parent=%(holiday_list)s
457 and holiday_date >= %(start_date)s
458 and holiday_date <= %(end_date)s''', {
459 "holiday_list": holiday_list,
460 "start_date": start_date,
461 "end_date": end_date
462 })
463
464 holidays = [cstr(i) for i in holidays]
465
466 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530467
468@erpnext.allow_regional
469def calculate_annual_eligible_hra_exemption(doc):
470 # Don't delete this method, used for localization
471 # Indian HRA Exemption Calculation
472 return {}
473
474@erpnext.allow_regional
475def calculate_hra_exemption_for_period(doc):
476 # Don't delete this method, used for localization
477 # Indian HRA Exemption Calculation
478 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530479
480def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
481 total_claimed_amount = 0
482 query = """
483 select sum(claimed_amount) as 'total_amount'
484 from `tabEmployee Benefit Claim`
485 where employee=%(employee)s
486 and docstatus = 1
487 and (claim_date between %(start_date)s and %(end_date)s)
488 """
489 if non_pro_rata:
490 query += "and pay_against_benefit_claim = 1"
491 if component:
492 query += "and earning_component = %(component)s"
493
494 sum_of_claimed_amount = frappe.db.sql(query, {
495 'employee': employee,
496 'start_date': payroll_period.start_date,
497 'end_date': payroll_period.end_date,
498 'component': component
499 }, as_dict=True)
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530500 if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0:
Jamsheer55a2f4d2018-06-20 11:04:21 +0530501 total_claimed_amount = sum_of_claimed_amount[0].total_amount
502 return total_claimed_amount
Anurag Mishra755b7732020-11-25 16:05:17 +0530503
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530504def share_doc_with_approver(doc, user):
505 # if approver does not have permissions, share
506 if not frappe.has_permission(doc=doc, ptype="submit", user=user):
Rucha Mahabal8c055b52021-04-04 18:45:06 +0530507 frappe.share.add(doc.doctype, doc.name, user, submit=1,
508 flags={"ignore_share_permission": True})
509
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530510 frappe.msgprint(_("Shared with the user {0} with {1} access").format(
511 user, frappe.bold("submit"), alert=True))
512
513 # remove shared doc if approver changes
514 doc_before_save = doc.get_doc_before_save()
515 if doc_before_save:
516 approvers = {
517 "Leave Application": "leave_approver",
518 "Expense Claim": "expense_approver",
519 "Shift Request": "approver"
520 }
521
522 approver = approvers.get(doc.doctype)
523 if doc_before_save.get(approver) != doc.get(approver):
524 frappe.share.remove(doc.doctype, doc.name, doc_before_save.get(approver))