blob: cbc373841effba49f0e433906a7d910e718b12b1 [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 _
Ranjith793f8e82018-05-30 20:50:48 +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
Manas Solankib6988462018-05-10 18:07:20 +053091def update_employee(employee, details, cancel=False):
92 for item in details:
93 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
94 new_data = item.new if not cancel else item.current
95 if fieldtype == "Date" and new_data:
96 new_data = getdate(new_data)
97 elif fieldtype =="Datetime" and new_data:
98 new_data = get_datetime(new_data)
99 setattr(employee, item.fieldname, new_data)
100 return employee
101
Ranjithfddfffd2018-05-05 13:27:26 +0530102@frappe.whitelist()
103def get_employee_fields_label():
104 fields = []
105 for df in frappe.get_meta("Employee").get("fields"):
106 if df.fieldtype in ["Data", "Date", "Datetime", "Float", "Int",
107 "Link", "Percent", "Select", "Small Text"] and df.fieldname not in ["lft", "rgt", "old_parent"]:
108 fields.append({"value": df.fieldname, "label": df.label})
109 return fields
110
111@frappe.whitelist()
112def get_employee_field_property(employee, fieldname):
113 if employee and fieldname:
114 field = frappe.get_meta("Employee").get_field(fieldname)
115 value = frappe.db.get_value("Employee", employee, fieldname)
116 options = field.options
117 if field.fieldtype == "Date":
118 value = formatdate(value)
119 elif field.fieldtype == "Datetime":
120 value = format_datetime(value)
121 return {
122 "value" : value,
123 "datatype" : field.fieldtype,
124 "label" : field.label,
125 "options" : options
126 }
127 else:
128 return False
129
130def update_employee(employee, details, cancel=False):
131 for item in details:
132 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
133 new_data = item.new if not cancel else item.current
134 if fieldtype == "Date" and new_data:
135 new_data = getdate(new_data)
136 elif fieldtype =="Datetime" and new_data:
137 new_data = get_datetime(new_data)
138 setattr(employee, item.fieldname, new_data)
139 return employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530140
141def validate_dates(doc, from_date, to_date):
142 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
143 if getdate(from_date) > getdate(to_date):
144 frappe.throw(_("To date can not be less than from date"))
145 elif getdate(from_date) > getdate(nowdate()):
146 frappe.throw(_("Future dates not allowed"))
147 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
148 frappe.throw(_("From date can not be less than employee's joining date"))
149 elif relieving_date and getdate(to_date) > getdate(relieving_date):
150 frappe.throw(_("To date can not greater than employee's relieving date"))
151
152def validate_overlap(doc, from_date, to_date, company = None):
153 query = """
154 select name
155 from `tab{0}`
156 where name != %(name)s
157 """
158 query += get_doc_condition(doc.doctype)
159
160 if not doc.name:
161 # hack! if name is null, it could cause problems with !=
162 doc.name = "New "+doc.doctype
163
164 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
165 "employee": doc.employee,
166 "from_date": from_date,
167 "to_date": to_date,
168 "name": doc.name,
169 "company": company
170 }, as_dict = 1)
171
172 if overlap_doc:
173 exists_for = doc.employee
174 if company:
175 exists_for = company
176 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
177
178def get_doc_condition(doctype):
179 if doctype == "Compensatory Leave Request":
180 return "and employee = %(employee)s and docstatus < 2 \
181 and (work_from_date between %(from_date)s and %(to_date)s \
182 or work_end_date between %(from_date)s and %(to_date)s \
183 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
184 elif doctype == "Leave Period":
185 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
186 or to_date between %(from_date)s and %(to_date)s \
187 or (from_date < %(from_date)s and to_date > %(to_date)s))"
188
189def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
190 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
191 formatdate(from_date), formatdate(to_date)) \
192 + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
193 + _(") for {0}").format(exists_for)
194 frappe.throw(msg)
195
196def get_employee_leave_policy(employee):
197 leave_policy = frappe.db.get_value("Employee", employee, "leave_policy")
198 if not leave_policy:
199 employee_grade = frappe.db.get_value("Employee", employee, "grade")
200 if employee_grade:
201 leave_policy = frappe.db.get_value("Employee Grade", employee_grade, "default_leave_policy")
202 if not leave_policy:
203 frappe.throw(_("Employee {0} of grade {1} have no default leave policy").format(employee, employee_grade))
204 else:
205 frappe.throw(_("Employee {0} has no grade to get default leave policy").format(employee))
206 if leave_policy:
207 return frappe.get_doc("Leave Policy", leave_policy)
208
Ranjith5a8e6422018-05-10 15:06:49 +0530209def validate_tax_declaration(declarations):
210 subcategories = []
211 for declaration in declarations:
212 if declaration.exemption_sub_category in subcategories:
213 frappe.throw(_("More than one selection for {0} not \
214 allowed").format(declaration.exemption_sub_category), frappe.ValidationError)
215 subcategories.append(declaration.exemption_sub_category)
216 max_amount = frappe.db.get_value("Employee Tax Exemption Sub Category", \
217 declaration.exemption_sub_category, "max_amount")
218 if declaration.amount > max_amount:
219 frappe.throw(_("Max exemption amount for {0} is {1}").format(\
220 declaration.exemption_sub_category, max_amount), frappe.ValidationError)
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530221
Jamsheer0e2cc552018-05-08 11:48:25 +0530222def get_leave_period(from_date, to_date, company):
223 leave_period = frappe.db.sql("""
224 select name, from_date, to_date
225 from `tabLeave Period`
226 where company=%(company)s and is_active=1
227 and (from_date between %(from_date)s and %(to_date)s
228 or to_date between %(from_date)s and %(to_date)s
229 or (from_date < %(from_date)s and to_date > %(to_date)s))
230 """, {
231 "from_date": from_date,
232 "to_date": to_date,
233 "company": company
234 }, as_dict=1)
235
236 if leave_period:
237 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530238
239def get_payroll_period(from_date, to_date, company):
Ranjith58363e62018-05-17 10:00:33 +0530240 payroll_period = frappe.db.sql("""select pp.name, pd.start_date, pd.end_date from
Ranjithb485b1e2018-05-16 23:01:40 +0530241 `tabPayroll Period Date` pd join `tabPayroll Period` pp on
242 pd.parent=pp.name where pd.start_date<=%s and pd.end_date>= %s
243 and pp.company=%s""", (from_date, to_date, company), as_dict=1)
244 return payroll_period[0] if payroll_period else None
Ranjith155ecc12018-05-30 13:37:15 +0530245
246def get_salary_assignment(employee, date):
247 assignment = frappe.db.sql("""
248 select * from `tabSalary Structure Assignment`
249 where employee=%(employee)s
250 and docstatus = 1
251 and (
252 (%(on_date)s between from_date and ifnull(to_date, '2199-12-31'))
253 )""", {
254 'employee': employee,
255 'on_date': date,
256 }, as_dict=1)
257 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530258
259def calculate_eligible_hra_exemption(company, employee, monthly_house_rent, rented_in_metro_city):
260 hra_component = frappe.db.get_value("Company", company, "hra_component")
261 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
262 if hra_component:
263 assignment = get_salary_assignment(employee, getdate())
264 if assignment and frappe.db.exists("Salary Detail", {
265 "parent": assignment.salary_structure,
266 "salary_component": hra_component, "parentfield": "earnings"}):
267 hra_amount = get_hra_from_salary_slip(employee, assignment.salary_structure, hra_component)
268 if hra_amount:
269 if monthly_house_rent:
270 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
271 assignment.base, hra_amount, monthly_house_rent,
272 rented_in_metro_city)
273 if annual_exemption > 0:
274 monthly_exemption = annual_exemption / 12
275 else:
276 annual_exemption = 0
277 return {"hra_amount": hra_amount, "annual_exemption": annual_exemption, "monthly_exemption": monthly_exemption}
278
279def get_hra_from_salary_slip(employee, salary_structure, hra_component):
280 salary_slip = make_salary_slip(salary_structure, employee=employee)
281 for earning in salary_slip.earnings:
282 if earning.salary_component == hra_component:
283 return earning.amount
284
285def calculate_hra_exemption(salary_structure, base, monthly_hra, monthly_house_rent, rented_in_metro_city):
286 # TODO make this configurable
287 exemptions = []
288 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
289 # case 1: The actual amount allotted by the employer as the HRA.
290 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
291 actual_annual_rent = monthly_house_rent * 12
292 annual_base = get_annual_component_pay(frequency, base)
293 # case 2: Actual rent paid less 10% of the basic salary.
294 exemptions.append(flt(actual_annual_rent) - flt(annual_base * 0.1))
295 # case 3: 50% of the basic salary, if the employee is staying in a metro city (40% for a non-metro city).
296 exemptions.append(annual_base * 0.5 if rented_in_metro_city else annual_base * 0.4)
297 # return minimum of 3 cases
298 return min(exemptions)
299
300def get_annual_component_pay(frequency, amount):
301 if frequency == "Daily":
302 return amount * 365
303 elif frequency == "Weekly":
304 return amount * 52
305 elif frequency == "Fortnightly":
306 return amount * 26
307 elif frequency == "Monthly":
308 return amount * 12
309 elif frequency == "Bimonthly":
310 return amount * 6