blob: 11dbdf25d9808a8e0a3de27aeff56ec054f8e5c8 [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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe import _
Ranjith Kurungadam375db612018-06-01 16:09:28 +05307from frappe.utils import formatdate, format_datetime, getdate, get_datetime, nowdate, flt
Manas Solankib6988462018-05-10 18:07:20 +05308from frappe.model.document import Document
9from frappe.desk.form import assign_to
Ranjith793f8e82018-05-30 20:50:48 +053010from erpnext.hr.doctype.salary_structure.salary_structure import make_salary_slip
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"):
112 if df.fieldtype in ["Data", "Date", "Datetime", "Float", "Int",
113 "Link", "Percent", "Select", "Small Text"] and df.fieldname not in ["lft", "rgt", "old_parent"]:
114 fields.append({"value": df.fieldname, "label": df.label})
115 return fields
116
117@frappe.whitelist()
118def get_employee_field_property(employee, fieldname):
119 if employee and fieldname:
120 field = frappe.get_meta("Employee").get_field(fieldname)
121 value = frappe.db.get_value("Employee", employee, fieldname)
122 options = field.options
123 if field.fieldtype == "Date":
124 value = formatdate(value)
125 elif field.fieldtype == "Datetime":
126 value = format_datetime(value)
127 return {
128 "value" : value,
129 "datatype" : field.fieldtype,
130 "label" : field.label,
131 "options" : options
132 }
133 else:
134 return False
135
Jamsheer0e2cc552018-05-08 11:48:25 +0530136def validate_dates(doc, from_date, to_date):
137 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
138 if getdate(from_date) > getdate(to_date):
139 frappe.throw(_("To date can not be less than from date"))
140 elif getdate(from_date) > getdate(nowdate()):
141 frappe.throw(_("Future dates not allowed"))
142 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
143 frappe.throw(_("From date can not be less than employee's joining date"))
144 elif relieving_date and getdate(to_date) > getdate(relieving_date):
145 frappe.throw(_("To date can not greater than employee's relieving date"))
146
147def validate_overlap(doc, from_date, to_date, company = None):
148 query = """
149 select name
150 from `tab{0}`
151 where name != %(name)s
152 """
153 query += get_doc_condition(doc.doctype)
154
155 if not doc.name:
156 # hack! if name is null, it could cause problems with !=
157 doc.name = "New "+doc.doctype
158
159 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
160 "employee": doc.employee,
161 "from_date": from_date,
162 "to_date": to_date,
163 "name": doc.name,
164 "company": company
165 }, as_dict = 1)
166
167 if overlap_doc:
168 exists_for = doc.employee
169 if company:
170 exists_for = company
171 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
172
173def get_doc_condition(doctype):
174 if doctype == "Compensatory Leave Request":
175 return "and employee = %(employee)s and docstatus < 2 \
176 and (work_from_date between %(from_date)s and %(to_date)s \
177 or work_end_date between %(from_date)s and %(to_date)s \
178 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
179 elif doctype == "Leave Period":
180 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
181 or to_date between %(from_date)s and %(to_date)s \
182 or (from_date < %(from_date)s and to_date > %(to_date)s))"
183
184def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
185 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
186 formatdate(from_date), formatdate(to_date)) \
187 + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
188 + _(") for {0}").format(exists_for)
189 frappe.throw(msg)
190
191def get_employee_leave_policy(employee):
192 leave_policy = frappe.db.get_value("Employee", employee, "leave_policy")
193 if not leave_policy:
194 employee_grade = frappe.db.get_value("Employee", employee, "grade")
195 if employee_grade:
196 leave_policy = frappe.db.get_value("Employee Grade", employee_grade, "default_leave_policy")
197 if not leave_policy:
198 frappe.throw(_("Employee {0} of grade {1} have no default leave policy").format(employee, employee_grade))
199 else:
200 frappe.throw(_("Employee {0} has no grade to get default leave policy").format(employee))
201 if leave_policy:
202 return frappe.get_doc("Leave Policy", leave_policy)
203
Ranjith5a8e6422018-05-10 15:06:49 +0530204def validate_tax_declaration(declarations):
205 subcategories = []
206 for declaration in declarations:
207 if declaration.exemption_sub_category in subcategories:
208 frappe.throw(_("More than one selection for {0} not \
209 allowed").format(declaration.exemption_sub_category), frappe.ValidationError)
210 subcategories.append(declaration.exemption_sub_category)
211 max_amount = frappe.db.get_value("Employee Tax Exemption Sub Category", \
212 declaration.exemption_sub_category, "max_amount")
213 if declaration.amount > max_amount:
214 frappe.throw(_("Max exemption amount for {0} is {1}").format(\
215 declaration.exemption_sub_category, max_amount), frappe.ValidationError)
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530216
Jamsheer0e2cc552018-05-08 11:48:25 +0530217def get_leave_period(from_date, to_date, company):
218 leave_period = frappe.db.sql("""
219 select name, from_date, to_date
220 from `tabLeave Period`
221 where company=%(company)s and is_active=1
222 and (from_date between %(from_date)s and %(to_date)s
223 or to_date between %(from_date)s and %(to_date)s
224 or (from_date < %(from_date)s and to_date > %(to_date)s))
225 """, {
226 "from_date": from_date,
227 "to_date": to_date,
228 "company": company
229 }, as_dict=1)
230
231 if leave_period:
232 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530233
234def get_payroll_period(from_date, to_date, company):
Jamsheercf414cc2018-05-22 14:22:42 +0530235 payroll_period = frappe.db.sql("""select name, start_date, end_date from
236 `tabPayroll Period`
237 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 +0530238 return payroll_period[0] if payroll_period else None
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530239
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530240def allocate_earned_leaves():
241 '''Allocate earned leaves to Employees'''
242 e_leave_types = frappe.get_all("Leave Type",
243 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding"],
244 filters={'is_earned_leave' : 1})
245 today = getdate()
246 divide_by_frequency = {"Yearly": 1, "Quarterly": 4, "Monthly": 12}
247 if e_leave_types:
248 for e_leave_type in e_leave_types:
249 leave_allocations = frappe.db.sql("""select name, employee, from_date, to_date from `tabLeave Allocation` where '{0}'
250 between from_date and to_date and docstatus=1 and leave_type='{1}'"""
251 .format(today, e_leave_type.name), as_dict=1)
252 for allocation in leave_allocations:
253 leave_policy = get_employee_leave_policy(allocation.employee)
254 if not leave_policy:
255 continue
256 if not e_leave_type.earned_leave_frequency == "Monthly":
257 if not check_frequency_hit(allocation.from_date, today, e_leave_type.earned_leave_frequency):
258 continue
259 annual_allocation = frappe.db.sql("""select annual_allocation from `tabLeave Policy Detail`
260 where parent=%s and leave_type=%s""", (leave_policy.name, e_leave_type.name))
261 if annual_allocation and annual_allocation[0]:
262 earned_leaves = flt(annual_allocation[0][0]) / divide_by_frequency[e_leave_type.earned_leave_frequency]
263 if e_leave_type.rounding == "0.5":
264 earned_leaves = round(earned_leaves * 2) / 2
265 else:
266 earned_leaves = round(earned_leaves)
267
268 allocated_leaves = frappe.db.get_value('Leave Allocation', allocation.name, 'total_leaves_allocated')
269 new_allocation = flt(allocated_leaves) + flt(earned_leaves)
270 new_allocation = new_allocation if new_allocation <= e_leave_type.max_leaves_allowed else e_leave_type.max_leaves_allowed
271 frappe.db.set_value('Leave Allocation', allocation.name, 'total_leaves_allocated', new_allocation)
272
273def check_frequency_hit(from_date, to_date, frequency):
274 '''Return True if current date matches frequency'''
275 from_dt = get_datetime(from_date)
276 to_dt = get_datetime(to_date)
277 from dateutil import relativedelta
278 rd = relativedelta.relativedelta(to_dt, from_dt)
279 months = rd.months
280 if frequency == "Quarterly":
281 if not months % 3:
282 return True
283 elif frequency == "Yearly":
284 if not months % 12:
285 return True
286 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530287
Ranjith155ecc12018-05-30 13:37:15 +0530288def get_salary_assignment(employee, date):
289 assignment = frappe.db.sql("""
290 select * from `tabSalary Structure Assignment`
291 where employee=%(employee)s
292 and docstatus = 1
293 and (
294 (%(on_date)s between from_date and ifnull(to_date, '2199-12-31'))
295 )""", {
296 'employee': employee,
297 'on_date': date,
298 }, as_dict=1)
299 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530300
301def calculate_eligible_hra_exemption(company, employee, monthly_house_rent, rented_in_metro_city):
302 hra_component = frappe.db.get_value("Company", company, "hra_component")
303 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
304 if hra_component:
305 assignment = get_salary_assignment(employee, getdate())
306 if assignment and frappe.db.exists("Salary Detail", {
307 "parent": assignment.salary_structure,
308 "salary_component": hra_component, "parentfield": "earnings"}):
309 hra_amount = get_hra_from_salary_slip(employee, assignment.salary_structure, hra_component)
310 if hra_amount:
311 if monthly_house_rent:
312 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
313 assignment.base, hra_amount, monthly_house_rent,
314 rented_in_metro_city)
315 if annual_exemption > 0:
316 monthly_exemption = annual_exemption / 12
317 else:
318 annual_exemption = 0
319 return {"hra_amount": hra_amount, "annual_exemption": annual_exemption, "monthly_exemption": monthly_exemption}
320
321def get_hra_from_salary_slip(employee, salary_structure, hra_component):
322 salary_slip = make_salary_slip(salary_structure, employee=employee)
323 for earning in salary_slip.earnings:
324 if earning.salary_component == hra_component:
325 return earning.amount
326
327def calculate_hra_exemption(salary_structure, base, monthly_hra, monthly_house_rent, rented_in_metro_city):
328 # TODO make this configurable
329 exemptions = []
330 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
331 # case 1: The actual amount allotted by the employer as the HRA.
332 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
333 actual_annual_rent = monthly_house_rent * 12
334 annual_base = get_annual_component_pay(frequency, base)
335 # case 2: Actual rent paid less 10% of the basic salary.
336 exemptions.append(flt(actual_annual_rent) - flt(annual_base * 0.1))
337 # case 3: 50% of the basic salary, if the employee is staying in a metro city (40% for a non-metro city).
338 exemptions.append(annual_base * 0.5 if rented_in_metro_city else annual_base * 0.4)
339 # return minimum of 3 cases
340 return min(exemptions)
341
342def get_annual_component_pay(frequency, amount):
343 if frequency == "Daily":
344 return amount * 365
345 elif frequency == "Weekly":
346 return amount * 52
347 elif frequency == "Fortnightly":
348 return amount * 26
349 elif frequency == "Monthly":
350 return amount * 12
351 elif frequency == "Bimonthly":
Ranjith Kurungadame46639f2018-06-11 11:24:44 +0530352 return amount * 6