blob: abbf302e5b315d2ad30235fb570ca3b0f879f0d0 [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)
38
39 # create the task for the given project and assign to the concerned person
40 for activity in self.activities:
41 task = frappe.get_doc({
42 "doctype": "Task",
43 "project": project.name,
Manas Solanki094e1842018-05-14 20:33:28 +053044 "subject": activity.activity_name + " : " + self.employee_name,
Manas Solankib6988462018-05-10 18:07:20 +053045 "description": activity.description,
46 "department": self.department,
47 "company": self.company
48 }).insert(ignore_permissions=True)
49 activity.db_set("task", task.name)
50 users = [activity.user] if activity.user else []
51 if activity.role:
52 user_list = frappe.db.sql_list('''select distinct(parent) from `tabHas Role`
53 where parenttype='User' and role=%s''', activity.role)
54 users = users + user_list
55
56 # assign the task the users
57 if users:
58 self.assign_task_to_users(task, set(users))
59
60 def assign_task_to_users(self, task, users):
61 for user in users:
62 args = {
63 'assign_to' : user,
64 'doctype' : task.doctype,
65 'name' : task.name,
66 'description' : task.description or task.subject,
67 }
68 assign_to.add(args)
69
70 def on_cancel(self):
71 # delete task project
72 for task in frappe.get_all("Task", filters={"project": self.project}):
73 frappe.delete_doc("Task", task.name)
74 frappe.delete_doc("Project", self.project)
75 self.db_set('project', '')
76 for activity in self.activities:
77 activity.db_set("task", "")
78
79
80@frappe.whitelist()
81def get_onboarding_details(parent, parenttype):
82 return frappe.get_list("Employee Boarding Activity",
83 fields=["activity_name", "role", "user", "required_for_employee_creation", "description"],
84 filters={"parent": parent, "parenttype": parenttype},
85 order_by= "idx")
Anand Doshi60666a22013-04-12 20:19:53 +053086
Anand Doshic280d062014-05-30 14:43:36 +053087def set_employee_name(doc):
88 if doc.employee and not doc.employee_name:
89 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +053090
Ranjith Kurungadame46639f2018-06-11 11:24:44 +053091def update_employee(employee, details, date=None, cancel=False):
92 internal_work_history = {}
Manas Solankib6988462018-05-10 18:07:20 +053093 for item in details:
94 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
95 new_data = item.new if not cancel else item.current
96 if fieldtype == "Date" and new_data:
97 new_data = getdate(new_data)
98 elif fieldtype =="Datetime" and new_data:
99 new_data = get_datetime(new_data)
100 setattr(employee, item.fieldname, new_data)
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530101 if item.fieldname in ["department", "designation", "branch"]:
102 internal_work_history[item.fieldname] = item.new
103 if internal_work_history and not cancel:
104 internal_work_history["from_date"] = date
105 employee.append("internal_work_history", internal_work_history)
Manas Solankib6988462018-05-10 18:07:20 +0530106 return employee
107
Ranjithfddfffd2018-05-05 13:27:26 +0530108@frappe.whitelist()
109def get_employee_fields_label():
110 fields = []
111 for df in frappe.get_meta("Employee").get("fields"):
Ranjith Kurungadamc1030a32018-06-20 12:42:58 +0530112 if df.fieldname in ["salutation", "user_id", "employee_number", "employment_type",
113 "holiday_list", "branch", "department", "designation", "grade",
114 "notice_number_of_days", "reports_to", "leave_policy", "company_email"]:
Ranjithfddfffd2018-05-05 13:27:26 +0530115 fields.append({"value": df.fieldname, "label": df.label})
116 return fields
117
118@frappe.whitelist()
119def get_employee_field_property(employee, fieldname):
120 if employee and fieldname:
121 field = frappe.get_meta("Employee").get_field(fieldname)
122 value = frappe.db.get_value("Employee", employee, fieldname)
123 options = field.options
124 if field.fieldtype == "Date":
125 value = formatdate(value)
126 elif field.fieldtype == "Datetime":
127 value = format_datetime(value)
128 return {
129 "value" : value,
130 "datatype" : field.fieldtype,
131 "label" : field.label,
132 "options" : options
133 }
134 else:
135 return False
136
Jamsheer0e2cc552018-05-08 11:48:25 +0530137def validate_dates(doc, from_date, to_date):
138 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
139 if getdate(from_date) > getdate(to_date):
140 frappe.throw(_("To date can not be less than from date"))
141 elif getdate(from_date) > getdate(nowdate()):
142 frappe.throw(_("Future dates not allowed"))
143 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
144 frappe.throw(_("From date can not be less than employee's joining date"))
145 elif relieving_date and getdate(to_date) > getdate(relieving_date):
146 frappe.throw(_("To date can not greater than employee's relieving date"))
147
148def validate_overlap(doc, from_date, to_date, company = None):
149 query = """
150 select name
151 from `tab{0}`
152 where name != %(name)s
153 """
154 query += get_doc_condition(doc.doctype)
155
156 if not doc.name:
157 # hack! if name is null, it could cause problems with !=
158 doc.name = "New "+doc.doctype
159
160 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
161 "employee": doc.employee,
162 "from_date": from_date,
163 "to_date": to_date,
164 "name": doc.name,
165 "company": company
166 }, as_dict = 1)
167
168 if overlap_doc:
169 exists_for = doc.employee
170 if company:
171 exists_for = company
172 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
173
174def get_doc_condition(doctype):
175 if doctype == "Compensatory Leave Request":
176 return "and employee = %(employee)s and docstatus < 2 \
177 and (work_from_date between %(from_date)s and %(to_date)s \
178 or work_end_date between %(from_date)s and %(to_date)s \
179 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
180 elif doctype == "Leave Period":
181 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
182 or to_date between %(from_date)s and %(to_date)s \
183 or (from_date < %(from_date)s and to_date > %(to_date)s))"
184
185def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
186 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
187 formatdate(from_date), formatdate(to_date)) \
188 + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
189 + _(") for {0}").format(exists_for)
190 frappe.throw(msg)
191
192def get_employee_leave_policy(employee):
193 leave_policy = frappe.db.get_value("Employee", employee, "leave_policy")
194 if not leave_policy:
195 employee_grade = frappe.db.get_value("Employee", employee, "grade")
196 if employee_grade:
197 leave_policy = frappe.db.get_value("Employee Grade", employee_grade, "default_leave_policy")
198 if not leave_policy:
199 frappe.throw(_("Employee {0} of grade {1} have no default leave policy").format(employee, employee_grade))
200 else:
201 frappe.throw(_("Employee {0} has no grade to get default leave policy").format(employee))
202 if leave_policy:
203 return frappe.get_doc("Leave Policy", leave_policy)
204
Ranjith5a8e6422018-05-10 15:06:49 +0530205def validate_tax_declaration(declarations):
206 subcategories = []
207 for declaration in declarations:
208 if declaration.exemption_sub_category in subcategories:
209 frappe.throw(_("More than one selection for {0} not \
210 allowed").format(declaration.exemption_sub_category), frappe.ValidationError)
211 subcategories.append(declaration.exemption_sub_category)
212 max_amount = frappe.db.get_value("Employee Tax Exemption Sub Category", \
213 declaration.exemption_sub_category, "max_amount")
214 if declaration.amount > max_amount:
215 frappe.throw(_("Max exemption amount for {0} is {1}").format(\
216 declaration.exemption_sub_category, max_amount), frappe.ValidationError)
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530217
Jamsheer0e2cc552018-05-08 11:48:25 +0530218def get_leave_period(from_date, to_date, company):
219 leave_period = frappe.db.sql("""
220 select name, from_date, to_date
221 from `tabLeave Period`
222 where company=%(company)s and is_active=1
223 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 """, {
227 "from_date": from_date,
228 "to_date": to_date,
229 "company": company
230 }, as_dict=1)
231
232 if leave_period:
233 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530234
235def get_payroll_period(from_date, to_date, company):
Jamsheercf414cc2018-05-22 14:22:42 +0530236 payroll_period = frappe.db.sql("""select name, start_date, end_date from
237 `tabPayroll Period`
238 where start_date<=%s and end_date>= %s and company=%s""", (from_date, to_date, company), as_dict=1)
Ranjithb485b1e2018-05-16 23:01:40 +0530239 return payroll_period[0] if payroll_period else None
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530240
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530241def allocate_earned_leaves():
242 '''Allocate earned leaves to Employees'''
243 e_leave_types = frappe.get_all("Leave Type",
244 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding"],
245 filters={'is_earned_leave' : 1})
246 today = getdate()
247 divide_by_frequency = {"Yearly": 1, "Quarterly": 4, "Monthly": 12}
248 if e_leave_types:
249 for e_leave_type in e_leave_types:
250 leave_allocations = frappe.db.sql("""select name, employee, from_date, to_date from `tabLeave Allocation` where '{0}'
251 between from_date and to_date and docstatus=1 and leave_type='{1}'"""
252 .format(today, e_leave_type.name), as_dict=1)
253 for allocation in leave_allocations:
254 leave_policy = get_employee_leave_policy(allocation.employee)
255 if not leave_policy:
256 continue
257 if not e_leave_type.earned_leave_frequency == "Monthly":
258 if not check_frequency_hit(allocation.from_date, today, e_leave_type.earned_leave_frequency):
259 continue
260 annual_allocation = frappe.db.sql("""select annual_allocation from `tabLeave Policy Detail`
261 where parent=%s and leave_type=%s""", (leave_policy.name, e_leave_type.name))
262 if annual_allocation and annual_allocation[0]:
263 earned_leaves = flt(annual_allocation[0][0]) / divide_by_frequency[e_leave_type.earned_leave_frequency]
264 if e_leave_type.rounding == "0.5":
265 earned_leaves = round(earned_leaves * 2) / 2
266 else:
267 earned_leaves = round(earned_leaves)
268
269 allocated_leaves = frappe.db.get_value('Leave Allocation', allocation.name, 'total_leaves_allocated')
270 new_allocation = flt(allocated_leaves) + flt(earned_leaves)
271 new_allocation = new_allocation if new_allocation <= e_leave_type.max_leaves_allowed else e_leave_type.max_leaves_allowed
272 frappe.db.set_value('Leave Allocation', allocation.name, 'total_leaves_allocated', new_allocation)
273
274def check_frequency_hit(from_date, to_date, frequency):
275 '''Return True if current date matches frequency'''
276 from_dt = get_datetime(from_date)
277 to_dt = get_datetime(to_date)
278 from dateutil import relativedelta
279 rd = relativedelta.relativedelta(to_dt, from_dt)
280 months = rd.months
281 if frequency == "Quarterly":
282 if not months % 3:
283 return True
284 elif frequency == "Yearly":
285 if not months % 12:
286 return True
287 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530288
Ranjith155ecc12018-05-30 13:37:15 +0530289def get_salary_assignment(employee, date):
290 assignment = frappe.db.sql("""
291 select * from `tabSalary Structure Assignment`
292 where employee=%(employee)s
293 and docstatus = 1
294 and (
295 (%(on_date)s between from_date and ifnull(to_date, '2199-12-31'))
296 )""", {
297 'employee': employee,
298 'on_date': date,
299 }, as_dict=1)
300 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530301
Jamsheer8d66f1e2018-06-12 11:30:59 +0530302def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
303 total_given_benefit_amount = 0
304 query = """
305 select sum(sd.amount) as 'total_amount'
306 from `tabSalary Slip` ss, `tabSalary Detail` sd
307 where ss.employee=%(employee)s
308 and ss.docstatus = 1 and ss.name = sd.parent
309 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
310 and sd.parenttype = "Salary Slip"
311 and (ss.start_date between %(start_date)s and %(end_date)s
312 or ss.end_date between %(start_date)s and %(end_date)s
313 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
314 """
315
316 if component:
317 query += "and sd.salary_component = %(component)s"
318
319 sum_of_given_benefit = frappe.db.sql(query, {
320 'employee': employee,
321 'start_date': payroll_period.start_date,
322 'end_date': payroll_period.end_date,
323 'component': component
324 }, as_dict=True)
325
326 if sum_of_given_benefit and sum_of_given_benefit[0].total_amount > 0:
327 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
328 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530329
330def get_holidays_for_employee(employee, start_date, end_date):
331 holiday_list = get_holiday_list_for_employee(employee)
332 holidays = frappe.db.sql_list('''select holiday_date from `tabHoliday`
333 where
334 parent=%(holiday_list)s
335 and holiday_date >= %(start_date)s
336 and holiday_date <= %(end_date)s''', {
337 "holiday_list": holiday_list,
338 "start_date": start_date,
339 "end_date": end_date
340 })
341
342 holidays = [cstr(i) for i in holidays]
343
344 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530345
346@erpnext.allow_regional
347def calculate_annual_eligible_hra_exemption(doc):
348 # Don't delete this method, used for localization
349 # Indian HRA Exemption Calculation
350 return {}
351
352@erpnext.allow_regional
353def calculate_hra_exemption_for_period(doc):
354 # Don't delete this method, used for localization
355 # Indian HRA Exemption Calculation
356 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530357
358def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
359 total_claimed_amount = 0
360 query = """
361 select sum(claimed_amount) as 'total_amount'
362 from `tabEmployee Benefit Claim`
363 where employee=%(employee)s
364 and docstatus = 1
365 and (claim_date between %(start_date)s and %(end_date)s)
366 """
367 if non_pro_rata:
368 query += "and pay_against_benefit_claim = 1"
369 if component:
370 query += "and earning_component = %(component)s"
371
372 sum_of_claimed_amount = frappe.db.sql(query, {
373 'employee': employee,
374 'start_date': payroll_period.start_date,
375 'end_date': payroll_period.end_date,
376 'component': component
377 }, as_dict=True)
378 if sum_of_claimed_amount and sum_of_claimed_amount[0].total_amount > 0:
379 total_claimed_amount = sum_of_claimed_amount[0].total_amount
380 return total_claimed_amount