blob: 4fe9f6b285ac7e0caf9aacbf203ef1681ef6f267 [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
4from __future__ import unicode_literals
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +05305import frappe, erpnext
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05306from frappe import _
Mangesh-Khairnarf281f002019-08-05 14:47:02 +05307from frappe.utils import formatdate, format_datetime, getdate, get_datetime, nowdate, flt, cstr, add_days, today
Manas Solankib6988462018-05-10 18:07:20 +05308from frappe.model.document import Document
9from frappe.desk.form import assign_to
Jamsheercc25eb02018-06-13 15:14:24 +053010from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
Manas Solankib6988462018-05-10 18:07:20 +053011
12class EmployeeBoardingController(Document):
13 '''
14 Create the project and the task for the boarding process
15 Assign to the concerned person and roles as per the onboarding/separation template
16 '''
17 def validate(self):
18 # remove the task if linked before submitting the form
19 if self.amended_from:
20 for activity in self.activities:
21 activity.task = ''
22
23 def on_submit(self):
24 # create the project for the given employee onboarding
Manas Solanki70899f52018-05-15 18:52:14 +053025 project_name = _(self.doctype) + " : "
Manas Solankib6988462018-05-10 18:07:20 +053026 if self.doctype == "Employee Onboarding":
Manas Solanki70899f52018-05-15 18:52:14 +053027 project_name += self.job_applicant
Manas Solankib6988462018-05-10 18:07:20 +053028 else:
Manas Solanki70899f52018-05-15 18:52:14 +053029 project_name += self.employee
Manas Solankib6988462018-05-10 18:07:20 +053030 project = frappe.get_doc({
31 "doctype": "Project",
32 "project_name": project_name,
33 "expected_start_date": self.date_of_joining if self.doctype == "Employee Onboarding" else self.resignation_letter_date,
34 "department": self.department,
35 "company": self.company
36 }).insert(ignore_permissions=True)
37 self.db_set("project", project.name)
Shreya5c6ade42018-06-20 15:48:27 +053038 self.db_set("boarding_status", "Pending")
Manas Solankib6988462018-05-10 18:07:20 +053039
40 # create the task for the given project and assign to the concerned person
41 for activity in self.activities:
42 task = frappe.get_doc({
43 "doctype": "Task",
44 "project": project.name,
Manas Solanki094e1842018-05-14 20:33:28 +053045 "subject": activity.activity_name + " : " + self.employee_name,
Manas Solankib6988462018-05-10 18:07:20 +053046 "description": activity.description,
47 "department": self.department,
Suraj Shettyc90364f2019-04-12 14:12:03 +053048 "company": self.company,
49 "task_weight": activity.task_weight
Manas Solankib6988462018-05-10 18:07:20 +053050 }).insert(ignore_permissions=True)
51 activity.db_set("task", task.name)
52 users = [activity.user] if activity.user else []
53 if activity.role:
54 user_list = frappe.db.sql_list('''select distinct(parent) from `tabHas Role`
55 where parenttype='User' and role=%s''', activity.role)
56 users = users + user_list
57
Anurag Mishraadd6bf32019-01-04 11:36:30 +053058 if "Administrator" in users:
59 users.remove("Administrator")
60
Manas Solankib6988462018-05-10 18:07:20 +053061 # assign the task the users
62 if users:
63 self.assign_task_to_users(task, set(users))
64
65 def assign_task_to_users(self, task, users):
66 for user in users:
67 args = {
68 'assign_to' : user,
69 'doctype' : task.doctype,
70 'name' : task.name,
71 'description' : task.description or task.subject,
72 }
73 assign_to.add(args)
74
75 def on_cancel(self):
76 # delete task project
77 for task in frappe.get_all("Task", filters={"project": self.project}):
Zarrar9a3b7852018-07-11 14:34:55 +053078 frappe.delete_doc("Task", task.name, force=1)
79 frappe.delete_doc("Project", self.project, force=1)
Manas Solankib6988462018-05-10 18:07:20 +053080 self.db_set('project', '')
81 for activity in self.activities:
82 activity.db_set("task", "")
83
84
85@frappe.whitelist()
86def get_onboarding_details(parent, parenttype):
Nabin Hait01b2a652018-08-28 14:09:27 +053087 return frappe.get_all("Employee Boarding Activity",
Himanshu4cb1a1e2019-06-05 10:26:01 +053088 fields=["activity_name", "role", "user", "required_for_employee_creation", "description", "task_weight"],
Manas Solankib6988462018-05-10 18:07:20 +053089 filters={"parent": parent, "parenttype": parenttype},
90 order_by= "idx")
Anand Doshi60666a22013-04-12 20:19:53 +053091
Shreya5c6ade42018-06-20 15:48:27 +053092@frappe.whitelist()
93def get_boarding_status(project):
94 status = 'Pending'
95 if project:
96 doc = frappe.get_doc('Project', project)
97 if flt(doc.percent_complete) > 0.0 and flt(doc.percent_complete) < 100.0:
98 status = 'In Process'
99 elif flt(doc.percent_complete) == 100.0:
100 status = 'Completed'
101 return status
102
Anand Doshic280d062014-05-30 14:43:36 +0530103def set_employee_name(doc):
104 if doc.employee and not doc.employee_name:
105 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +0530106
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530107def update_employee(employee, details, date=None, cancel=False):
108 internal_work_history = {}
Manas Solankib6988462018-05-10 18:07:20 +0530109 for item in details:
110 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
111 new_data = item.new if not cancel else item.current
112 if fieldtype == "Date" and new_data:
113 new_data = getdate(new_data)
114 elif fieldtype =="Datetime" and new_data:
115 new_data = get_datetime(new_data)
116 setattr(employee, item.fieldname, new_data)
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530117 if item.fieldname in ["department", "designation", "branch"]:
118 internal_work_history[item.fieldname] = item.new
119 if internal_work_history and not cancel:
120 internal_work_history["from_date"] = date
121 employee.append("internal_work_history", internal_work_history)
Manas Solankib6988462018-05-10 18:07:20 +0530122 return employee
123
Ranjithfddfffd2018-05-05 13:27:26 +0530124@frappe.whitelist()
125def get_employee_fields_label():
126 fields = []
127 for df in frappe.get_meta("Employee").get("fields"):
Ranjith Kurungadamc1030a32018-06-20 12:42:58 +0530128 if df.fieldname in ["salutation", "user_id", "employee_number", "employment_type",
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530129 "holiday_list", "branch", "department", "designation", "grade",
130 "notice_number_of_days", "reports_to", "leave_policy", "company_email"]:
131 fields.append({"value": df.fieldname, "label": df.label})
Ranjithfddfffd2018-05-05 13:27:26 +0530132 return fields
133
134@frappe.whitelist()
135def get_employee_field_property(employee, fieldname):
136 if employee and fieldname:
137 field = frappe.get_meta("Employee").get_field(fieldname)
138 value = frappe.db.get_value("Employee", employee, fieldname)
139 options = field.options
140 if field.fieldtype == "Date":
141 value = formatdate(value)
142 elif field.fieldtype == "Datetime":
143 value = format_datetime(value)
144 return {
145 "value" : value,
146 "datatype" : field.fieldtype,
147 "label" : field.label,
148 "options" : options
149 }
150 else:
151 return False
152
Jamsheer0e2cc552018-05-08 11:48:25 +0530153def validate_dates(doc, from_date, to_date):
154 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
155 if getdate(from_date) > getdate(to_date):
156 frappe.throw(_("To date can not be less than from date"))
157 elif getdate(from_date) > getdate(nowdate()):
158 frappe.throw(_("Future dates not allowed"))
159 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
160 frappe.throw(_("From date can not be less than employee's joining date"))
161 elif relieving_date and getdate(to_date) > getdate(relieving_date):
162 frappe.throw(_("To date can not greater than employee's relieving date"))
163
164def validate_overlap(doc, from_date, to_date, company = None):
165 query = """
166 select name
167 from `tab{0}`
168 where name != %(name)s
169 """
170 query += get_doc_condition(doc.doctype)
171
172 if not doc.name:
173 # hack! if name is null, it could cause problems with !=
174 doc.name = "New "+doc.doctype
175
176 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
Nabin Haitd53c2c02018-07-30 20:16:48 +0530177 "employee": doc.get("employee"),
Jamsheer0e2cc552018-05-08 11:48:25 +0530178 "from_date": from_date,
179 "to_date": to_date,
180 "name": doc.name,
181 "company": company
182 }, as_dict = 1)
183
184 if overlap_doc:
deepeshgarg00778b273a2018-10-31 18:12:03 +0530185 if doc.get("employee"):
186 exists_for = doc.employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530187 if company:
188 exists_for = company
189 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
190
191def get_doc_condition(doctype):
192 if doctype == "Compensatory Leave Request":
193 return "and employee = %(employee)s and docstatus < 2 \
194 and (work_from_date between %(from_date)s and %(to_date)s \
195 or work_end_date between %(from_date)s and %(to_date)s \
196 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
197 elif doctype == "Leave Period":
198 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
199 or to_date between %(from_date)s and %(to_date)s \
200 or (from_date < %(from_date)s and to_date > %(to_date)s))"
201
202def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
203 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
204 formatdate(from_date), formatdate(to_date)) \
205 + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
206 + _(") for {0}").format(exists_for)
207 frappe.throw(msg)
208
209def get_employee_leave_policy(employee):
210 leave_policy = frappe.db.get_value("Employee", employee, "leave_policy")
211 if not leave_policy:
212 employee_grade = frappe.db.get_value("Employee", employee, "grade")
213 if employee_grade:
214 leave_policy = frappe.db.get_value("Employee Grade", employee_grade, "default_leave_policy")
215 if not leave_policy:
216 frappe.throw(_("Employee {0} of grade {1} have no default leave policy").format(employee, employee_grade))
Jamsheer0e2cc552018-05-08 11:48:25 +0530217 if leave_policy:
218 return frappe.get_doc("Leave Policy", leave_policy)
Nabin Hait9c735e42018-07-30 10:58:49 +0530219 else:
220 frappe.throw(_("Please set leave policy for employee {0} in Employee / Grade record").format(employee))
Jamsheer0e2cc552018-05-08 11:48:25 +0530221
Ranjith5a8e6422018-05-10 15:06:49 +0530222def validate_tax_declaration(declarations):
223 subcategories = []
Nabin Hait04e7bf42019-04-25 18:44:10 +0530224 for d in declarations:
225 if d.exemption_sub_category in subcategories:
226 frappe.throw(_("More than one selection for {0} not allowed").format(d.exemption_sub_category))
227 subcategories.append(d.exemption_sub_category)
228
229def get_total_exemption_amount(declarations):
Nabin Hait04e7bf42019-04-25 18:44:10 +0530230 exemptions = frappe._dict()
231 for d in declarations:
232 exemptions.setdefault(d.exemption_category, frappe._dict())
233 category_max_amount = exemptions.get(d.exemption_category).max_amount
234 if not category_max_amount:
235 category_max_amount = frappe.db.get_value("Employee Tax Exemption Category", d.exemption_category, "max_amount")
236 exemptions.get(d.exemption_category).max_amount = category_max_amount
237 sub_category_exemption_amount = d.max_amount \
238 if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount
239
240 exemptions.get(d.exemption_category).setdefault("total_exemption_amount", 0.0)
241 exemptions.get(d.exemption_category).total_exemption_amount += flt(sub_category_exemption_amount)
242
243 if category_max_amount and exemptions.get(d.exemption_category).total_exemption_amount > category_max_amount:
244 exemptions.get(d.exemption_category).total_exemption_amount = category_max_amount
245
246 total_exemption_amount = sum([flt(d.total_exemption_amount) for d in exemptions.values()])
247 return total_exemption_amount
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530248
Jamsheer0e2cc552018-05-08 11:48:25 +0530249def get_leave_period(from_date, to_date, company):
250 leave_period = frappe.db.sql("""
251 select name, from_date, to_date
252 from `tabLeave Period`
253 where company=%(company)s and is_active=1
254 and (from_date between %(from_date)s and %(to_date)s
255 or to_date between %(from_date)s and %(to_date)s
256 or (from_date < %(from_date)s and to_date > %(to_date)s))
257 """, {
258 "from_date": from_date,
259 "to_date": to_date,
260 "company": company
261 }, as_dict=1)
262
263 if leave_period:
264 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530265
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530266def generate_leave_encashment():
267 ''' Generates a draft leave encashment on allocation expiry '''
268 from erpnext.hr.doctype.leave_encashment.leave_encashment import create_leave_encashment
269 if frappe.db.get_single_value('HR Settings', 'auto_leave_encashment'):
270 leave_type = frappe.db.sql_list("SELECT name FROM `tabLeave Type` WHERE `allow_encashment`=1")
271
272 leave_allocation = frappe.get_all("Leave Allocation", filters={
273 'to_date': add_days(today(), -1),
274 'leave_type': ('in', leave_type)
275 }, fields=['employee', 'leave_period', 'leave_type', 'to_date', 'total_leaves_allocated', 'new_leaves_allocated'])
276
277 create_leave_encashment(leave_allocation=leave_allocation)
278
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530279def allocate_earned_leaves():
280 '''Allocate earned leaves to Employees'''
281 e_leave_types = frappe.get_all("Leave Type",
282 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding"],
283 filters={'is_earned_leave' : 1})
284 today = getdate()
Joyce Babu3d012132019-03-06 13:04:45 +0530285 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 6, "Quarterly": 4, "Monthly": 12}
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530286
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530287 for e_leave_type in e_leave_types:
288 leave_allocations = frappe.db.sql("""select name, employee, from_date, to_date from `tabLeave Allocation` where '{0}'
289 between from_date and to_date and docstatus=1 and leave_type='{1}'"""
290 .format(today, e_leave_type.name), as_dict=1)
291 for allocation in leave_allocations:
292 leave_policy = get_employee_leave_policy(allocation.employee)
293 if not leave_policy:
294 continue
295 if not e_leave_type.earned_leave_frequency == "Monthly":
296 if not check_frequency_hit(allocation.from_date, today, e_leave_type.earned_leave_frequency):
297 continue
298 annual_allocation = frappe.db.sql("""select annual_allocation from `tabLeave Policy Detail`
299 where parent=%s and leave_type=%s""", (leave_policy.name, e_leave_type.name))
300 if annual_allocation and annual_allocation[0]:
301 earned_leaves = flt(annual_allocation[0][0]) / divide_by_frequency[e_leave_type.earned_leave_frequency]
302 if e_leave_type.rounding == "0.5":
303 earned_leaves = round(earned_leaves * 2) / 2
304 else:
305 earned_leaves = round(earned_leaves)
306
307 allocation = frappe.get_doc('Leave Allocation', allocation.name)
308 new_allocation = flt(allocation.total_leaves_allocated) + flt(earned_leaves)
309 new_allocation = new_allocation if new_allocation <= e_leave_type.max_leaves_allowed else e_leave_type.max_leaves_allowed
310
311 if new_allocation == allocation.total_leaves_allocated:
312 continue
313 allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
314 create_earned_leave_ledger_entry(allocation, earned_leaves, today)
315
316
317def create_earned_leave_ledger_entry(allocation, earned_leaves, date):
318 ''' Create leave ledger entry based on the earned leave frequency '''
319 allocation.new_leaves_allocated = earned_leaves
320 allocation.from_date = date
Mangesh-Khairnar5cbe6162019-08-08 17:06:15 +0530321 allocation.unused_leaves = 0
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530322 allocation.create_leave_ledger_entry()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530323
324def check_frequency_hit(from_date, to_date, frequency):
325 '''Return True if current date matches frequency'''
326 from_dt = get_datetime(from_date)
327 to_dt = get_datetime(to_date)
328 from dateutil import relativedelta
329 rd = relativedelta.relativedelta(to_dt, from_dt)
330 months = rd.months
331 if frequency == "Quarterly":
332 if not months % 3:
333 return True
Joyce Babu3d012132019-03-06 13:04:45 +0530334 elif frequency == "Half-Yearly":
335 if not months % 6:
336 return True
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530337 elif frequency == "Yearly":
338 if not months % 12:
339 return True
340 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530341
Ranjith155ecc12018-05-30 13:37:15 +0530342def get_salary_assignment(employee, date):
343 assignment = frappe.db.sql("""
344 select * from `tabSalary Structure Assignment`
345 where employee=%(employee)s
346 and docstatus = 1
Ranjith Kurungadamb4ad3c32018-06-25 10:29:54 +0530347 and %(on_date)s >= from_date order by from_date desc limit 1""", {
Ranjith155ecc12018-05-30 13:37:15 +0530348 'employee': employee,
349 'on_date': date,
350 }, as_dict=1)
351 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530352
Jamsheer8d66f1e2018-06-12 11:30:59 +0530353def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
354 total_given_benefit_amount = 0
355 query = """
356 select sum(sd.amount) as 'total_amount'
357 from `tabSalary Slip` ss, `tabSalary Detail` sd
358 where ss.employee=%(employee)s
359 and ss.docstatus = 1 and ss.name = sd.parent
360 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
361 and sd.parenttype = "Salary Slip"
362 and (ss.start_date between %(start_date)s and %(end_date)s
363 or ss.end_date between %(start_date)s and %(end_date)s
364 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
365 """
366
367 if component:
368 query += "and sd.salary_component = %(component)s"
369
370 sum_of_given_benefit = frappe.db.sql(query, {
371 'employee': employee,
372 'start_date': payroll_period.start_date,
373 'end_date': payroll_period.end_date,
374 'component': component
375 }, as_dict=True)
376
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530377 if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0:
Jamsheer8d66f1e2018-06-12 11:30:59 +0530378 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
379 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530380
381def get_holidays_for_employee(employee, start_date, end_date):
382 holiday_list = get_holiday_list_for_employee(employee)
383 holidays = frappe.db.sql_list('''select holiday_date from `tabHoliday`
384 where
385 parent=%(holiday_list)s
386 and holiday_date >= %(start_date)s
387 and holiday_date <= %(end_date)s''', {
388 "holiday_list": holiday_list,
389 "start_date": start_date,
390 "end_date": end_date
391 })
392
393 holidays = [cstr(i) for i in holidays]
394
395 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530396
397@erpnext.allow_regional
398def calculate_annual_eligible_hra_exemption(doc):
399 # Don't delete this method, used for localization
400 # Indian HRA Exemption Calculation
401 return {}
402
403@erpnext.allow_regional
404def calculate_hra_exemption_for_period(doc):
405 # Don't delete this method, used for localization
406 # Indian HRA Exemption Calculation
407 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530408
409def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
410 total_claimed_amount = 0
411 query = """
412 select sum(claimed_amount) as 'total_amount'
413 from `tabEmployee Benefit Claim`
414 where employee=%(employee)s
415 and docstatus = 1
416 and (claim_date between %(start_date)s and %(end_date)s)
417 """
418 if non_pro_rata:
419 query += "and pay_against_benefit_claim = 1"
420 if component:
421 query += "and earning_component = %(component)s"
422
423 sum_of_claimed_amount = frappe.db.sql(query, {
424 'employee': employee,
425 'start_date': payroll_period.start_date,
426 'end_date': payroll_period.end_date,
427 'component': component
428 }, as_dict=True)
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530429 if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0:
Jamsheer55a2f4d2018-06-20 11:04:21 +0530430 total_claimed_amount = sum_of_claimed_amount[0].total_amount
431 return total_claimed_amount