blob: de2b0909dbde58547c459dffa120332c31f97155 [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 _
Manas Solankiaa172942018-06-13 16:47:41 +05307from frappe.utils import formatdate, format_datetime, getdate, get_datetime, nowdate, flt, cstr
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")
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053039 self.reload()
40 self.create_task_and_notify_user()
Manas Solankib6988462018-05-10 18:07:20 +053041
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053042 def create_task_and_notify_user(self):
Manas Solankib6988462018-05-10 18:07:20 +053043 # create the task for the given project and assign to the concerned person
44 for activity in self.activities:
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053045 if activity.task:
46 continue
47
Manas Solankib6988462018-05-10 18:07:20 +053048 task = frappe.get_doc({
49 "doctype": "Task",
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053050 "project": self.project,
Manas Solanki094e1842018-05-14 20:33:28 +053051 "subject": activity.activity_name + " : " + self.employee_name,
Manas Solankib6988462018-05-10 18:07:20 +053052 "description": activity.description,
53 "department": self.department,
Suraj Shettyc90364f2019-04-12 14:12:03 +053054 "company": self.company,
55 "task_weight": activity.task_weight
Manas Solankib6988462018-05-10 18:07:20 +053056 }).insert(ignore_permissions=True)
57 activity.db_set("task", task.name)
58 users = [activity.user] if activity.user else []
59 if activity.role:
60 user_list = frappe.db.sql_list('''select distinct(parent) from `tabHas Role`
61 where parenttype='User' and role=%s''', activity.role)
62 users = users + user_list
63
Anurag Mishraadd6bf32019-01-04 11:36:30 +053064 if "Administrator" in users:
65 users.remove("Administrator")
66
Manas Solankib6988462018-05-10 18:07:20 +053067 # assign the task the users
68 if users:
69 self.assign_task_to_users(task, set(users))
70
71 def assign_task_to_users(self, task, users):
72 for user in users:
73 args = {
74 'assign_to' : user,
75 'doctype' : task.doctype,
76 'name' : task.name,
77 'description' : task.description or task.subject,
Mangesh-Khairnar06a0afa2019-08-05 10:07:05 +053078 'notify': self.notify_users_by_email
Manas Solankib6988462018-05-10 18:07:20 +053079 }
80 assign_to.add(args)
81
82 def on_cancel(self):
83 # delete task project
84 for task in frappe.get_all("Task", filters={"project": self.project}):
Zarrar9a3b7852018-07-11 14:34:55 +053085 frappe.delete_doc("Task", task.name, force=1)
86 frappe.delete_doc("Project", self.project, force=1)
Manas Solankib6988462018-05-10 18:07:20 +053087 self.db_set('project', '')
88 for activity in self.activities:
89 activity.db_set("task", "")
90
91
92@frappe.whitelist()
93def get_onboarding_details(parent, parenttype):
Nabin Hait01b2a652018-08-28 14:09:27 +053094 return frappe.get_all("Employee Boarding Activity",
Himanshu4cb1a1e2019-06-05 10:26:01 +053095 fields=["activity_name", "role", "user", "required_for_employee_creation", "description", "task_weight"],
Manas Solankib6988462018-05-10 18:07:20 +053096 filters={"parent": parent, "parenttype": parenttype},
97 order_by= "idx")
Anand Doshi60666a22013-04-12 20:19:53 +053098
Shreya5c6ade42018-06-20 15:48:27 +053099@frappe.whitelist()
100def get_boarding_status(project):
101 status = 'Pending'
102 if project:
103 doc = frappe.get_doc('Project', project)
104 if flt(doc.percent_complete) > 0.0 and flt(doc.percent_complete) < 100.0:
105 status = 'In Process'
106 elif flt(doc.percent_complete) == 100.0:
107 status = 'Completed'
108 return status
109
Anand Doshic280d062014-05-30 14:43:36 +0530110def set_employee_name(doc):
111 if doc.employee and not doc.employee_name:
112 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +0530113
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530114def update_employee(employee, details, date=None, cancel=False):
115 internal_work_history = {}
Manas Solankib6988462018-05-10 18:07:20 +0530116 for item in details:
117 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
118 new_data = item.new if not cancel else item.current
119 if fieldtype == "Date" and new_data:
120 new_data = getdate(new_data)
121 elif fieldtype =="Datetime" and new_data:
122 new_data = get_datetime(new_data)
123 setattr(employee, item.fieldname, new_data)
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530124 if item.fieldname in ["department", "designation", "branch"]:
125 internal_work_history[item.fieldname] = item.new
126 if internal_work_history and not cancel:
127 internal_work_history["from_date"] = date
128 employee.append("internal_work_history", internal_work_history)
Manas Solankib6988462018-05-10 18:07:20 +0530129 return employee
130
Ranjithfddfffd2018-05-05 13:27:26 +0530131@frappe.whitelist()
132def get_employee_fields_label():
133 fields = []
134 for df in frappe.get_meta("Employee").get("fields"):
Ranjith Kurungadamc1030a32018-06-20 12:42:58 +0530135 if df.fieldname in ["salutation", "user_id", "employee_number", "employment_type",
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530136 "holiday_list", "branch", "department", "designation", "grade",
137 "notice_number_of_days", "reports_to", "leave_policy", "company_email"]:
138 fields.append({"value": df.fieldname, "label": df.label})
Ranjithfddfffd2018-05-05 13:27:26 +0530139 return fields
140
141@frappe.whitelist()
142def get_employee_field_property(employee, fieldname):
143 if employee and fieldname:
144 field = frappe.get_meta("Employee").get_field(fieldname)
145 value = frappe.db.get_value("Employee", employee, fieldname)
146 options = field.options
147 if field.fieldtype == "Date":
148 value = formatdate(value)
149 elif field.fieldtype == "Datetime":
150 value = format_datetime(value)
151 return {
152 "value" : value,
153 "datatype" : field.fieldtype,
154 "label" : field.label,
155 "options" : options
156 }
157 else:
158 return False
159
Jamsheer0e2cc552018-05-08 11:48:25 +0530160def validate_dates(doc, from_date, to_date):
161 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
162 if getdate(from_date) > getdate(to_date):
163 frappe.throw(_("To date can not be less than from date"))
164 elif getdate(from_date) > getdate(nowdate()):
165 frappe.throw(_("Future dates not allowed"))
166 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
167 frappe.throw(_("From date can not be less than employee's joining date"))
168 elif relieving_date and getdate(to_date) > getdate(relieving_date):
169 frappe.throw(_("To date can not greater than employee's relieving date"))
170
171def validate_overlap(doc, from_date, to_date, company = None):
172 query = """
173 select name
174 from `tab{0}`
175 where name != %(name)s
176 """
177 query += get_doc_condition(doc.doctype)
178
179 if not doc.name:
180 # hack! if name is null, it could cause problems with !=
181 doc.name = "New "+doc.doctype
182
183 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
Nabin Haitd53c2c02018-07-30 20:16:48 +0530184 "employee": doc.get("employee"),
Jamsheer0e2cc552018-05-08 11:48:25 +0530185 "from_date": from_date,
186 "to_date": to_date,
187 "name": doc.name,
188 "company": company
189 }, as_dict = 1)
190
191 if overlap_doc:
deepeshgarg00778b273a2018-10-31 18:12:03 +0530192 if doc.get("employee"):
193 exists_for = doc.employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530194 if company:
195 exists_for = company
196 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
197
198def get_doc_condition(doctype):
199 if doctype == "Compensatory Leave Request":
200 return "and employee = %(employee)s and docstatus < 2 \
201 and (work_from_date between %(from_date)s and %(to_date)s \
202 or work_end_date between %(from_date)s and %(to_date)s \
203 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
204 elif doctype == "Leave Period":
205 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
206 or to_date between %(from_date)s and %(to_date)s \
207 or (from_date < %(from_date)s and to_date > %(to_date)s))"
208
209def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
210 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
211 formatdate(from_date), formatdate(to_date)) \
212 + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
213 + _(") for {0}").format(exists_for)
214 frappe.throw(msg)
215
216def get_employee_leave_policy(employee):
217 leave_policy = frappe.db.get_value("Employee", employee, "leave_policy")
218 if not leave_policy:
219 employee_grade = frappe.db.get_value("Employee", employee, "grade")
220 if employee_grade:
221 leave_policy = frappe.db.get_value("Employee Grade", employee_grade, "default_leave_policy")
222 if not leave_policy:
223 frappe.throw(_("Employee {0} of grade {1} have no default leave policy").format(employee, employee_grade))
Jamsheer0e2cc552018-05-08 11:48:25 +0530224 if leave_policy:
225 return frappe.get_doc("Leave Policy", leave_policy)
Nabin Hait9c735e42018-07-30 10:58:49 +0530226 else:
227 frappe.throw(_("Please set leave policy for employee {0} in Employee / Grade record").format(employee))
Jamsheer0e2cc552018-05-08 11:48:25 +0530228
Ranjith5a8e6422018-05-10 15:06:49 +0530229def validate_tax_declaration(declarations):
230 subcategories = []
Nabin Hait04e7bf42019-04-25 18:44:10 +0530231 for d in declarations:
232 if d.exemption_sub_category in subcategories:
233 frappe.throw(_("More than one selection for {0} not allowed").format(d.exemption_sub_category))
234 subcategories.append(d.exemption_sub_category)
235
236def get_total_exemption_amount(declarations):
Nabin Hait04e7bf42019-04-25 18:44:10 +0530237 exemptions = frappe._dict()
238 for d in declarations:
239 exemptions.setdefault(d.exemption_category, frappe._dict())
240 category_max_amount = exemptions.get(d.exemption_category).max_amount
241 if not category_max_amount:
242 category_max_amount = frappe.db.get_value("Employee Tax Exemption Category", d.exemption_category, "max_amount")
243 exemptions.get(d.exemption_category).max_amount = category_max_amount
244 sub_category_exemption_amount = d.max_amount \
245 if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount
246
247 exemptions.get(d.exemption_category).setdefault("total_exemption_amount", 0.0)
248 exemptions.get(d.exemption_category).total_exemption_amount += flt(sub_category_exemption_amount)
249
250 if category_max_amount and exemptions.get(d.exemption_category).total_exemption_amount > category_max_amount:
251 exemptions.get(d.exemption_category).total_exemption_amount = category_max_amount
252
253 total_exemption_amount = sum([flt(d.total_exemption_amount) for d in exemptions.values()])
254 return total_exemption_amount
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530255
Jamsheer0e2cc552018-05-08 11:48:25 +0530256def get_leave_period(from_date, to_date, company):
257 leave_period = frappe.db.sql("""
258 select name, from_date, to_date
259 from `tabLeave Period`
260 where company=%(company)s and is_active=1
261 and (from_date between %(from_date)s and %(to_date)s
262 or to_date between %(from_date)s and %(to_date)s
263 or (from_date < %(from_date)s and to_date > %(to_date)s))
264 """, {
265 "from_date": from_date,
266 "to_date": to_date,
267 "company": company
268 }, as_dict=1)
269
270 if leave_period:
271 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530272
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530273def allocate_earned_leaves():
274 '''Allocate earned leaves to Employees'''
275 e_leave_types = frappe.get_all("Leave Type",
276 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding"],
277 filters={'is_earned_leave' : 1})
278 today = getdate()
Joyce Babu3d012132019-03-06 13:04:45 +0530279 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 6, "Quarterly": 4, "Monthly": 12}
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530280 if e_leave_types:
281 for e_leave_type in e_leave_types:
282 leave_allocations = frappe.db.sql("""select name, employee, from_date, to_date from `tabLeave Allocation` where '{0}'
283 between from_date and to_date and docstatus=1 and leave_type='{1}'"""
284 .format(today, e_leave_type.name), as_dict=1)
285 for allocation in leave_allocations:
286 leave_policy = get_employee_leave_policy(allocation.employee)
287 if not leave_policy:
288 continue
289 if not e_leave_type.earned_leave_frequency == "Monthly":
290 if not check_frequency_hit(allocation.from_date, today, e_leave_type.earned_leave_frequency):
291 continue
292 annual_allocation = frappe.db.sql("""select annual_allocation from `tabLeave Policy Detail`
293 where parent=%s and leave_type=%s""", (leave_policy.name, e_leave_type.name))
294 if annual_allocation and annual_allocation[0]:
295 earned_leaves = flt(annual_allocation[0][0]) / divide_by_frequency[e_leave_type.earned_leave_frequency]
296 if e_leave_type.rounding == "0.5":
297 earned_leaves = round(earned_leaves * 2) / 2
298 else:
299 earned_leaves = round(earned_leaves)
300
301 allocated_leaves = frappe.db.get_value('Leave Allocation', allocation.name, 'total_leaves_allocated')
302 new_allocation = flt(allocated_leaves) + flt(earned_leaves)
303 new_allocation = new_allocation if new_allocation <= e_leave_type.max_leaves_allowed else e_leave_type.max_leaves_allowed
304 frappe.db.set_value('Leave Allocation', allocation.name, 'total_leaves_allocated', new_allocation)
305
306def check_frequency_hit(from_date, to_date, frequency):
307 '''Return True if current date matches frequency'''
308 from_dt = get_datetime(from_date)
309 to_dt = get_datetime(to_date)
310 from dateutil import relativedelta
311 rd = relativedelta.relativedelta(to_dt, from_dt)
312 months = rd.months
313 if frequency == "Quarterly":
314 if not months % 3:
315 return True
Joyce Babu3d012132019-03-06 13:04:45 +0530316 elif frequency == "Half-Yearly":
317 if not months % 6:
318 return True
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530319 elif frequency == "Yearly":
320 if not months % 12:
321 return True
322 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530323
Ranjith155ecc12018-05-30 13:37:15 +0530324def get_salary_assignment(employee, date):
325 assignment = frappe.db.sql("""
326 select * from `tabSalary Structure Assignment`
327 where employee=%(employee)s
328 and docstatus = 1
Ranjith Kurungadamb4ad3c32018-06-25 10:29:54 +0530329 and %(on_date)s >= from_date order by from_date desc limit 1""", {
Ranjith155ecc12018-05-30 13:37:15 +0530330 'employee': employee,
331 'on_date': date,
332 }, as_dict=1)
333 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530334
Jamsheer8d66f1e2018-06-12 11:30:59 +0530335def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
336 total_given_benefit_amount = 0
337 query = """
338 select sum(sd.amount) as 'total_amount'
339 from `tabSalary Slip` ss, `tabSalary Detail` sd
340 where ss.employee=%(employee)s
341 and ss.docstatus = 1 and ss.name = sd.parent
342 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
343 and sd.parenttype = "Salary Slip"
344 and (ss.start_date between %(start_date)s and %(end_date)s
345 or ss.end_date between %(start_date)s and %(end_date)s
346 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
347 """
348
349 if component:
350 query += "and sd.salary_component = %(component)s"
351
352 sum_of_given_benefit = frappe.db.sql(query, {
353 'employee': employee,
354 'start_date': payroll_period.start_date,
355 'end_date': payroll_period.end_date,
356 'component': component
357 }, as_dict=True)
358
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530359 if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0:
Jamsheer8d66f1e2018-06-12 11:30:59 +0530360 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
361 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530362
363def get_holidays_for_employee(employee, start_date, end_date):
364 holiday_list = get_holiday_list_for_employee(employee)
365 holidays = frappe.db.sql_list('''select holiday_date from `tabHoliday`
366 where
367 parent=%(holiday_list)s
368 and holiday_date >= %(start_date)s
369 and holiday_date <= %(end_date)s''', {
370 "holiday_list": holiday_list,
371 "start_date": start_date,
372 "end_date": end_date
373 })
374
375 holidays = [cstr(i) for i in holidays]
376
377 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530378
379@erpnext.allow_regional
380def calculate_annual_eligible_hra_exemption(doc):
381 # Don't delete this method, used for localization
382 # Indian HRA Exemption Calculation
383 return {}
384
385@erpnext.allow_regional
386def calculate_hra_exemption_for_period(doc):
387 # Don't delete this method, used for localization
388 # Indian HRA Exemption Calculation
389 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530390
391def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
392 total_claimed_amount = 0
393 query = """
394 select sum(claimed_amount) as 'total_amount'
395 from `tabEmployee Benefit Claim`
396 where employee=%(employee)s
397 and docstatus = 1
398 and (claim_date between %(start_date)s and %(end_date)s)
399 """
400 if non_pro_rata:
401 query += "and pay_against_benefit_claim = 1"
402 if component:
403 query += "and earning_component = %(component)s"
404
405 sum_of_claimed_amount = frappe.db.sql(query, {
406 'employee': employee,
407 'start_date': payroll_period.start_date,
408 'end_date': payroll_period.end_date,
409 'component': component
410 }, as_dict=True)
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530411 if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0:
Jamsheer55a2f4d2018-06-20 11:04:21 +0530412 total_claimed_amount = sum_of_claimed_amount[0].total_amount
413 return total_claimed_amount